From f5fd8fb18064d6a4e17a673b61e0f0f42d1115f0 Mon Sep 17 00:00:00 2001 From: sqwk Date: Thu, 18 Aug 2016 11:48:34 +0200 Subject: [PATCH 001/554] Add Paper.js Type Definitions --- paper/paper.d.ts | 4008 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 4008 insertions(+) create mode 100644 paper/paper.d.ts diff --git a/paper/paper.d.ts b/paper/paper.d.ts new file mode 100644 index 0000000000..9fc0c154a1 --- /dev/null +++ b/paper/paper.d.ts @@ -0,0 +1,4008 @@ +// Type definitions for Paper.js v0.9.22 +// Project: http://paperjs.org/ +// Definitions by: Clark Stevenson +// forked from https://github.com/clark-stevenson/paper.d.ts + +declare module 'paper' { + + /** + * The version of Paper.js, as a string. + */ + export var version: string; + + /** + * Gives access to paper's configurable settings. + */ + export var settings: { + + applyMatrix: boolean; + handleSize: number; + hitTolerance: number; + + }; + + /** + * The currently active project. + */ + export var project: Project; + + /** + * The list of all open projects within the current Paper.js context. + */ + export var projects: Project[]; + + /** + * The reference to the active project's view. + * Read Only. + */ + export var view: View; + + /** + * The reference to the active tool. + */ + export var tool: Tool; + + /** + * The list of available tools. + */ + export var tools: Tool[]; + + /** + * Injects the paper scope into any other given scope. Can be used for examle to inject the currently active PaperScope into the window's global scope, to emulate PaperScript-style globally accessible Paper classes and objects + * Please note: Using this method may override native constructors (e.g. Path, RGBColor). This may cause problems when using Paper.js in conjunction with other libraries that rely on these constructors. Keep the library scoped if you encounter issues caused by this. + * @param scope - + */ + export function install(scope: any): void; + + /** + * Sets up an empty project for us. If a canvas is provided, it also creates a View for it, both linked to this scope. + * @param element - the HTML canvas element this scope should be associated with, or an ID string by which to find the element. + */ + export function setup(canvas: HTMLCanvasElement | string): void; + + /** + * Activates this PaperScope, so all newly created items will be placed in its active project. + */ + export function activate(): void; + + /** + * An affine transform performs a linear mapping from 2D coordinates to other 2D coordinates that preserves the "straightness" and "parallelness" of lines. + * Such a coordinate transformation can be represented by a 3 row by 3 column matrix with an implied last row of [ 0 0 1 ]. This matrix transforms source coordinates (x,y) into destination coordinates (x',y') by considering them to be a column vector and multiplying the coordinate vector by the matrix according to the following process: + * This class is optimized for speed and minimizes calculations based on its knowledge of the underlying matrix (as opposed to say simply performing matrix multiplication). + */ + export class Matrix { + + /** + * Creates a 2D affine transform. + * @param a - the a property of the transform + * @param c - the c property of the transform + * @param b - the b property of the transform + * @param d - the d property of the transform + * @param tx - the tx property of the transform + * @param ty - the ty property of the transform + */ + constructor(a: number, c: number, b: number, d: number, tx: number, ty: number); + + /** + * The value that affects the transformation along the x axis when scaling or rotating, positioned at (0, 0) in the transformation matrix. + */ + a: number; + + /** + * The value that affects the transformation along the y axis when rotating or skewing, positioned at (1, 0) in the transformation matrix. + */ + c: number; + + /** + * The value that affects the transformation along the x axis when rotating or skewing, positioned at (0, 1) in the transformation matrix. + */ + b: number; + + /** + * The value that affects the transformation along the y axis when scaling or rotating, positioned at (1, 1) in the transformation matrix. + */ + d: number; + + /** + * The distance by which to translate along the x axis, positioned at (2, 0) in the transformation matrix. + */ + tx: number; + + /** + * The distance by which to translate along the y axis, positioned at (2, 1) in the transformation matrix. + */ + ty: number; + + /** + * The transform values as an array, in the same sequence as they are passed to initialize(a, c,b,d,tx,ty). + * Read only. + */ + values: number; + + /** + * The translation of the matrix as a vector. + * Read only. + */ + translation: Point; + + /** + * The scaling values of the matrix, if it can be decomposed. + * Read only. + */ + scaling: Point; + + /** + * The rotation angle of the matrix, if it can be decomposed. + * Read only. + */ + rotation: number; + + /** + * Sets this transform to the matrix specified by the 6 values. + * @param a - the a property of the transform + * @param c - the c property of the transform + * @param b - the b property of the transform + * @param d - the d property of the transform + * @param tx - the tx property of the transform + * @param ty - the ty property of the transform + */ + set(a: number, c: number, b: number, d: number, tx: number, ty: number): Matrix; + + /** + * Returns a copy of this transform + */ + clone(): Matrix; + + /** + * Checks whether the two matrices describe the same transformation. + * @param matrix - the matrix to compare this matrix to + */ + equals(matrix: Matrix): boolean; + + /** + * returns a string representation of this transform + */ + toString(): string; + + /** + * Resets the matrix by setting its values to the ones of the identity matrix that results in no transformation. + */ + reset(): void; + + /** + * Attempts to apply the matrix to the content of item that it belongs to, meaning its transformation is baked into the item's content or children. + * @param recursively - controls whether to apply transformations recursively on children + */ + apply(): boolean; + + /** + * Concatenates this transform with a translate transformation. + * @param point - the vector to translate by + */ + translate(point: Point): Matrix; + + /** + * Concatenates this transform with a translate transformation. + * @param dx - the distance to translate in the x direction + * @param dy - the distance to translate in the y direction + */ + translate(dx: number, dy: number): Matrix; + + /** + * Concatenates this transform with a scaling transformation. + * @param scale - the scaling factor + * @param center [optional] - the center for the scaling transformation + */ + scale(scale: number, center?: Point): Matrix; + + /** + * Concatenates this transform with a scaling transformation. + * @param hor - the horizontal scaling factor + * @param ver - the vertical scaling factor + * @param center [optional] - the center for the scaling transformation + */ + scale(hor: number, ver: number, center?: Point): Matrix; + + /** + * Concatenates this transform with a rotation transformation around an anchor point. + * @param angle - the angle of rotation measured in degrees + * @param center - the anchor point to rotate around + */ + rotate(angle: number, center: Point): Matrix; + + /** + * Concatenates this transform with a rotation transformation around an anchor point. + * @param angle - the angle of rotation measured in degrees + * @param x - the x coordinate of the anchor point + * @param y - the y coordinate of the anchor point + */ + rotate(angle: number, x: number, y: number): Matrix; + + /** + * Concatenates this transform with a shear transformation. + * @param shear - the shear factor in x and y direction + * @param center [optional] - the center for the shear transformation + */ + shear(shear: Point, center?: Point): Matrix; + + /** + * Concatenates this transform with a shear transformation. + * @param hor - the horizontal shear factor + * @param ver - the vertical shear factor + * @param center [optional] - the center for the shear transformation + */ + shear(hor: number, ver: number, center?: Point): Matrix; + + /** + * Concatenates this transform with a skew transformation. + * @param skew - the skew angles in x and y direction in degrees + * @param center [optional] - the center for the skew transformation + */ + skew(skew: Point, center?: Point): Matrix; + + /** + * Concatenates this transform with a skew transformation. + * @param hor - the horizontal skew angle in degrees + * @param ver - the vertical skew angle in degrees + * @param center [optional] - the center for the skew transformation + */ + skew(hor: number, ver: number, center?: Point): Matrix; + + /** + * Concatenates the given affine transform to this transform. + * @param mx - the transform to concatenate + */ + concatenate(mx: Matrix): Matrix; + + /** + * Pre-concatenates the given affine transform to this transform. + * @param mx - the transform to preconcatenate + */ + preConcatenate(mx: Matrix): Matrix; + + /** + * Returns a new instance of the result of the concatenation of the given affine transform with this transform. + * @param mx - the transform to concatenate + */ + chain(mx: Matrix): Matrix; + + /** + * Returns whether this transform is the identity transform + */ + isIdentity(): boolean; + + /** + * Returns whether the transform is invertible. A transform is not invertible if the determinant is 0 or any value is non-finite or NaN. + */ + isInvertible(): boolean; + + /** + * Checks whether the matrix is singular or not. Singular matrices cannot be inverted. + */ + isSingular(): boolean; + + /** + * Transforms a point and returns the result. + * @param point - the point to be transformed + */ + transform(point: Point): Matrix; + + /** + * Transforms an array of coordinates by this matrix and stores the results into the destination array, which is also returned. + * @param src - the array containing the source points as x, y value pairs + * @param dst - the array into which to store the transformed point pairs + * @param count - the number of points to transform + */ + transform(src: number[], dst: number[], count: number): number[]; + + /** + * Inverse transforms a point and returns the result. + * @param point - the point to be transformed + */ + inverseTransform(point: Point): Matrix; + + /** + * Attempts to decompose the affine transformation described by this matrix into scaling, rotation and shearing, and returns an object with these properties if it succeeded, null otherwise. + */ + decompose(): any; + + /** + * Creates the inversion of the transformation of the matrix and returns it as a new insteance. If the matrix is not invertible (in which case isSingular() returns true), null is returned. + */ + inverted(): Matrix; + + /** + * Applies this matrix to the specified Canvas Context. + * @param ctx - + */ + applyToContext(ctx: CanvasRenderingContext2D): void; + + } + /** + * The Point object represents a point in the two dimensional space of the Paper.js project. It is also used to represent two dimensional vector objects. + */ + export class Point { + + /** + * Returns a new point object with the smallest x and y of the supplied points. + * @param point1 - + * @param point2 - + */ + static min(point1: Point, point2: Point): Point; + + /** + * Returns a new point object with the largest x and y of the supplied points. + * @param point1 - + * @param point2 - + */ + static max(point1: Point, point2: Point): Point; + + /** + * Returns a point object with random x and y values between 0 and 1. + */ + static random(): Point; + + /** + * Creates a Point object with the given x and y coordinates. + * @param x - the x coordinate + * @param y - the y coordinate + */ + constructor(x: number, y: number); + + /** + * Creates a Point object using the numbers in the given array as coordinates. + * @param array - an array of numbers to use as coordinates + */ + constructor(values: number[]); + + /** + * Creates a Point object using the properties in the given object. + * @param object - the object describing the point's properties + */ + constructor(object: any); + + /** + * Creates a Point object using the width and height values of the given Size object. + * @param size - the size width and height to use + */ + constructor(size: Size); + + /** + * Creates a Point object using the coordinates of the given Point object. + * @param point - the point to copy + */ + constructor(point: Point); + + /** + * The x coordinate of the point + */ + x: number; + + /** + * The y coordinate of the point + */ + y: number; + + /** + * The length of the vector that is represented by this point's coordinates. + * Each point can be interpreted as a vector that points from the origin (x = 0, y = 0) to the point's location. + * Setting the length changes the location but keeps the vector's angle. + */ + length: number; + + /** + * The vector's angle in degrees, measured from the x-axis to the vector. + */ + angle: number; + + /** + * The vector's angle in radians, measured from the x-axis to the vector. + */ + angleInRadians: number; + + /** + * The quadrant of the angle of the point. + * Angles between 0 and 90 degrees are in quadrant 1. Angles between 90 and 180 degrees are in quadrant 2, angles between 180 and 270 degrees are in quadrant 3 and angles between 270 and 360 degrees are in quadrant 4. + * Read only. + */ + quadrant: number; + + /** + * This property is only present if the point is an anchor or control point of a Segment or a Curve. In this case, it returns true it is selected, false otherwise + */ + selected: boolean; + + /** + * Checks whether the coordinates of the point are equal to that of the supplied point. + * @param point - the point to check against + */ + equals(point: Point): boolean; + + /** + * Returns a copy of the point. + */ + clone(): Point; + + /** + * a string representation of the point + */ + toString(): string; + + /** + * Returns the smaller angle between two vectors. The angle is unsigned, no information about rotational direction is given. + * @param point - + */ + getAngle(Point: Point): number; + + /** + * Returns the smaller angle between two vectors in radians. The angle is unsigned, no information about rotational direction is given. + * @param point: Point + */ + getAngleInRadians(point: Point): number; + + /** + * Returns the angle between two vectors. The angle is directional and signed, giving information about the rotational direction. + * Read more about angle units and orientation in the description of the angle property. + * @param point - + */ + getDirectedAngle(point: Point): number; + + /** + * Returns the distance between the point and another point. + * @param point - + * @param squared [optional] - Controls whether the distance should remain squared, or its square root should be calculated. default: false + */ + getDistance(point: Point, squared?: boolean): number; + + /** + * Normalize modifies the length of the vector to 1 without changing its angle and returns it as a new point. The optional length parameter defines the length to normalize to. + * The object itself is not modified! + * @param length [optional] - The length of the normalized vector, default: 1 + */ + normalize(length?: number): Point; + + /** + * Rotates the point by the given angle around an optional center point. + * The object itself is not modified. + * Read more about angle units and orientation in the description of the angle property. + * @param angle - the rotation angle + * @param center - the center point of the rotation + */ + rotate(angle: number, center: Point): Point; + + /** + * Transforms the point by the matrix as a new point. The object itself is not modified! + * @param matrix - + */ + transform(matrix: Matrix): Point; + + /** + * Checks whether the point is inside the boundaries of the rectangle. + * @param rect - the rectangle to check against + */ + isInside(rect: Rectangle): boolean; + + /** + * Checks if the point is within a given distance of another point. + * @param point - the point to check against + * @param tolerance - the maximum distance allowed + */ + isClose(point: Point, tolerance: number): boolean; + + /** + * Checks if the vector represented by this point is colinear (parallel) to another vector. + * @param point - the vector to check against + */ + isColinear(point: Point): boolean; + + /** + * Checks if the vector represented by this point is orthogonal (perpendicular) to another vector. + * @param point - the vector to check against + */ + isOrthogonal(point: Point): boolean; + + /** + * Checks if this point has both the x and y coordinate set to 0. + */ + isZero(): boolean; + + /** + * Checks if this point has an undefined value for at least one of its coordinates. + */ + isNan(): boolean; + + /** + * Returns the dot product of the point and another point. + * @param point - + */ + dot(point: Point): number; + + /** + * Returns the cross product of the point and another point. + * @param point - + */ + cross(point: Point): number; + + /** + * Returns the projection of the point on another point. + * Both points are interpreted as vectors. + * @param point - + */ + project(point: Point): Point; + + /** + * Returns a new point with rounded x and y values. The object itself is not modified! + */ + round(): Point; + + /** + * Returns a new point with the nearest greater non-fractional values to the specified x and y values. The object itself is not modified! + */ + ceil(): Point; + + /** + * Returns a new point with the nearest smaller non-fractional values to the specified x and y values. The object itself is not modified! + */ + floor(): Point; + + /** + * Returns a new point with the absolute values of the specified x and y values. The object itself is not modified! + */ + abs(): Point; + + } + /** + * A Rectangle specifies an area that is enclosed by it's top-left point (x, y), its width, and its height. It should not be confused with a rectangular path, it is not an item. + */ + export class Rectangle { + + /** + * Creates a Rectangle object. + * @param point - the top-left point of the rectangle + * @param size - the size of the rectangle + */ + constructor(point: Point, size: Size); + + /** + * Creates a rectangle object. + * @param x - the left coordinate + * @param y - the top coordinate + * @param width - the width + * @param height - the height + */ + constructor(x: number, y: number, width: number, height: number); + + /** + * Creates a Rectangle object. + * @param object - an object containing properties to be set on the rectangle. + */ + constructor(object: any); + + /** + * Creates a rectangle object from the passed points. These do not necessarily need to be the top left and bottom right corners, the constructor figures out how to fit a rectangle between them. + * @param from - The first point defining the rectangle + * @param to - The second point defining the rectangle + */ + constructor(from: Point, to: Point); + + /** + * Creates a new rectangle object from the passed rectangle object. + * @param rt - the rectangle to copy from + */ + constructor(rt: Rectangle); + + /** + * The x position of the rectangle. + */ + x: number; + + /** + * The y position of the rectangle. + */ + y: number; + + /** + * The width of the rectangle. + */ + width: number; + + /** + * The height of the rectangle. + */ + height: number; + + /** + * The top-left point of the rectangle + */ + point: Point; + + /** + * The size of the rectangle + */ + size: Size; + + /** + * The position of the left hand side of the rectangle. Note that this doesn't move the whole rectangle; the right hand side stays where it was. + */ + left: number; + + /** + * The top coordinate of the rectangle. Note that this doesn't move the whole rectangle: the bottom won't move. + */ + top: number; + + /** + * The position of the right hand side of the rectangle. Note that this doesn't move the whole rectangle; the left hand side stays where it was. + */ + right: number; + + /** + * The bottom coordinate of the rectangle. Note that this doesn't move the whole rectangle: the top won't move. + */ + bottom: number; + + /** + * The center point of the rectangle. + */ + center: Point; + + /** + * The top-left point of the rectangle. + */ + topLeft: Point; + + /** + * The top-right point of the rectangle. + */ + topRight: Point; + + /** + * The bottom-left point of the rectangle. + */ + bottomLeft: Point; + + /** + * The bottom-right point of the rectangle. + */ + bottomRight: Point; + + /** + * The left-center point of the rectangle. + */ + leftCenter: Point; + + /** + * The top-center point of the rectangle. + */ + topCenter: Point; + + /** + * The right-center point of the rectangle. + */ + rightCenter: Point; + + /** + * The bottom-center point of the rectangle. + */ + bottomCenter: Point; + + /** + * The area of the rectangle in square points. + * Read only. + */ + area: number; + + /** + * Specifies whether an item's bounds are selected and will also mark the item as selected. + * Paper.js draws the visual bounds of selected items on top of your project. This can be useful for debugging. + */ + selected: boolean; + + /** + * Returns a copy of the rectangle. + */ + clone(): Rectangle; + + /** + * Checks whether the coordinates and size of the rectangle are equal to that of the supplied rectangle. + * @param rect - the rectangle to check against + */ + equals(rect: Rectangle): boolean; + + /** + * a string representation of this rectangle + */ + toString(): string; + + /** + * Returns true if the rectangle is empty, false otherwise + */ + isEmpty(): boolean; + + /** + * Tests if the specified point is inside the boundary of the rectangle. + * @param point - the specified point + */ + contains(point: Point): boolean; + + /** + * Tests if the interior of the rectangle entirely contains the specified rectangle. + * @param rect - The specified rectangle + */ + contains(rect: Rectangle): boolean; + + /** + * Tests if the interior of this rectangle intersects the interior of another rectangle. Rectangles just touching each other are considered as non-intersecting. + * @param rect - the specified rectangle + */ + intersects(rect: Rectangle): boolean; + + /** + * Returns a new rectangle representing the intersection of this rectangle with the specified rectangle. + * @param rect - The rectangle to be intersected with this rectangle + */ + intersect(rect: Rectangle): Rectangle; + + /** + * Returns a new rectangle representing the union of this rectangle with the specified rectangle. + * @param rect - the rectangle to be combined with this rectangle + */ + unite(rect: Rectangle): Rectangle; + + /** + * Adds a point to this rectangle. The resulting rectangle is the smallest rectangle that contains both the original rectangle and the specified point. + * After adding a point, a call to contains(point) with the added point as an argument does not necessarily return true. + * The rectangle.contains(point) method does not return true for points on the right or bottom edges of a rectangle. Therefore, if the added point falls on the left or bottom edge of the enlarged rectangle, rectangle.contains(point) returns false for that point. + * @param point - the point to add to the rectangle + */ + include(point: Point): Point; + + /** + * Expands the rectangle by the specified amount in horizontal and vertical directions. + * @param amount - the amount to expand the rectangle in both directions + */ + expand(amount: number | Size | Point): void; + + /** + * Expands the rectangle by the specified amounts in horizontal and vertical directions. + * @param hor - the amount to expand the rectangle in horizontal direction + * @param ver - the amount to expand the rectangle in vertical direction + */ + expand(hor: number, ver: number): void; + + /** + * Scales the rectangle by the specified amount from its center. + * @param amount - the amount to scale by + */ + scale(amount: number): void; + + /** + * Scales the rectangle in horizontal direction by the specified hor amount and in vertical direction by the specified ver amount from its center. + * @param hor - the amount to scale the rectangle in horizontal direction + * @param ver - the amount to scale the rectangle in vertical direction + */ + scale(hor: number, ver: number): void; + + } + /** + * The Size object is used to describe the size or dimensions of something, through its width and height properties. + */ + export class Size { + + /** + * Returns a new size object with the smallest width and height of the supplied sizes. + * @param size1 - the first size + * @param size2 - the second size + */ + static min(size1: Size, size2: Size): Size; + + /** + * Returns a new size object with the largest width and height of the supplied sizes. + * @param size1 - the first size + * @param size2 - the second size + */ + static max(size1: Size, size2: Size): Size; + + /** + * Returns a size object with random width and height values between 0 and 1. + */ + static random(): Size; + + /** + * Creates a Size object with the given width and height values. + * @param width - the width + * @param height - the height + */ + constructor(width: number, height: number); + + /** + * Creates a Size object using the numbers in the given array as dimensions. + * @param array - an array of numbers + */ + constructor(array: number[]); + + /** + * Creates a Size object using the properties in the given object. + * @param object - the object literal containing properies (width:10, height:10 etc) + */ + constructor(object: any); + + /** + * Creates a Size object using the coordinates of the given Size object. + * @param size - the size to duplicate from + */ + constructor(size: Size); + + /** + * Creates a Size object using the point.x and point.y values of the given Point object. + * @param point - the point from which to create a size + */ + constructor(point: Point); + + /** + * The width of the size + */ + width: number; + + /** + * The height of the size + */ + height: number; + + /** + * WARNING - This seems undocumented/incorrect + */ + equals(): boolean; + + /** + * Returns a copy of the size. + */ + clone(): Size; + + /** + * a string representation of the size + */ + toString(): string; + + /** + * Checks if this size has both the width and height set to 0. + */ + isZero(): boolean; + + /** + * Checks if the width or the height of the size are NaN. + */ + isNan(): boolean; + + /** + * Returns a new size with rounded width and height values. The object itself is not modified! + */ + round(): Size; + + /** + * Returns a new size with the nearest greater non-fractional values to the specified width and height values. The object itself is not modified! + */ + ceil(): Size; + + /** + * Returns a new size with the nearest smaller non-fractional values to the specified width and height values. The object itself is not modified! + */ + floor(): Size; + + /** + * Returns a new size with the absolute values of the specified width and height values. The object itself is not modified! + */ + abs(): Size; + + } + export interface IFrameEvent { + + /** + * the number of times the frame event was fired. + */ + count: number; + + /** + * the total amount of time passed since the first + */ + time: number; + + /** + * + */ + delta: number; + + } + /** + * The PaperScope class represents the scope associated with a Paper context. When working with PaperScript, these scopes are automatically created for us, and through clever scoping the properties and methods of the active scope seem to become part of the global scope. + * When working with normal JavaScript code, PaperScope objects need to be manually created and handled. + * Paper classes can only be accessed through PaperScope objects. Thus in PaperScript they are global, while in JavaScript, they are available on the global paper object. For JavaScript you can use paperScope.install(scope) to install the Paper classes and objects on the global scope. Note that when working with more than one scope, this still works for classes, but not for objects like paperScope.project, since they are not updated in the injected scope if scopes are switched. + * The global paper object is simply a reference to the currently active PaperScope. + */ + export class PaperScope { + + /** + * The version of Paper.js, as a string. + */ + version: string; + + /** + * Gives access to paper's configurable settings. + */ + settings: { + + applyMatrix: boolean; + handleSize: number; + hitTolerance: number; + + }; + + /** + * The currently active project. + */ + project: Project; + + /** + * The list of all open projects within the current Paper.js context. + */ + projects: Project[]; + + /** + * The reference to the active project's view. + * Read Only. + */ + view: View; + + /** + * The reference to the active tool. + */ + tool: Tool; + + /** + * The list of available tools. + */ + tools: Tool[]; + + /** + * Injects the paper scope into any other given scope. Can be used for examle to inject the currently active PaperScope into the window's global scope, to emulate PaperScript-style globally accessible Paper classes and objects + * Please note: Using this method may override native constructors (e.g. Path, RGBColor). This may cause problems when using Paper.js in conjunction with other libraries that rely on these constructors. Keep the library scoped if you encounter issues caused by this. + * @param scope - + */ + install(scope: any): void; + + /** + * Sets up an empty project for us. If a canvas is provided, it also creates a View for it, both linked to this scope. + * @param element - the HTML canvas element this scope should be associated with, or an ID string by which to find the element. + */ + setup(canvas: HTMLCanvasElement | string): void; + + /** + * Activates this PaperScope, so all newly created items will be placed in its active project. + */ + activate(): void; + + /** + * Retrieves a PaperScope object with the given scope id. + * @param id - + */ + static get(id: string): PaperScope; + + } + /** + * The Item type allows you to access and modify the items in Paper.js projects. Its functionality is inherited by different project item types such as Path, CompoundPath, Group, Layer and Raster. They each add a layer of functionality that is unique to their type, but share the underlying properties and functions that they inherit from Item. + */ + export class Item { + + /** + * The tangential vector to the #curve at the given location. + */ + tangent: Point; + + /** + * The normal vector to the #curve at the given location. + */ + normal: Point; + + /** + * The curvature of the #curve at the given location. + */ + curvature: number; + + /** + * The unique id of the item. + * Read Only. + */ + id: number; + + /** + * The class name of the item as a string. + * String('Group', 'Layer', 'Path', 'CompoundPath', 'Shape', 'Raster', 'PlacedSymbol', 'PointText') + */ + className: string; + + /** + * The name of the item. If the item has a name, it can be accessed by name through its parent's children list. + */ + name: string; + + /** + * The path style of the item. + */ + style: Style; + + /** + * Specifies whether the item is visible. When set to false, the item won't be drawn. + */ + visible: boolean; + + /** + * The blend mode with which the item is composited onto the canvas. Both the standard canvas compositing modes, as well as the new CSS blend modes are supported. If blend-modes cannot be rendered natively, they are emulated. Be aware that emulation can have an impact on performance. + * String('normal', 'multiply', 'screen', 'overlay', 'soft-light', 'hard-light', 'color-dodge', 'color-burn', 'darken', 'lighten', 'difference', 'exclusion', 'hue', 'saturation', 'luminosity', 'color', 'add', 'subtract', 'average', 'pin-light', 'negation', 'source-over', 'source-in', 'source-out', 'source-atop', 'destination-over', 'destination-in', 'destination-out', 'destination-atop', 'lighter', 'darker', 'copy', 'xor') + */ + blendMode: string; + + /** + * The opacity of the item as a value between 0 and 1. + */ + opacity: number; + + /** + * Specifies whether the item is selected. This will also return true for Group items if they are partially selected, e.g. groups containing selected or partially selected paths. + * Paper.js draws the visual outlines of selected items on top of your project. This can be useful for debugging, as it allows you to see the construction of paths, position of path curves, individual segment points and bounding boxes of symbol and raster items. + */ + selected: boolean; + + /** + * Specifies whether the item defines a clip mask. This can only be set on paths, compound paths, and text frame objects, and only if the item is already contained within a clipping group. + */ + clipMask: boolean; + + /** + * A plain javascript object which can be used to store arbitrary data on the item. + */ + data: any; + + /** + * The item's position within the parent item's coordinate system. By default, this is the rectangle.center of the item's bounds rectangle. + */ + position: Point; + + /** + * The item's pivot point specified in the item coordinate system, defining the point around which all transformations are hinging. This is also the reference point for position. By default, it is set to null, meaning the rectangle.center of the item's bounds rectangle is used as pivot. + */ + pivot: Point; + + /** + * The bounding rectangle of the item excluding stroke width. + */ + bounds: Rectangle; + + /** + * The bounding rectangle of the item including stroke width. + */ + strokeBounds: Rectangle; + + /** + * The bounding rectangle of the item including handles. + */ + handleBounds: Rectangle; + + /** + * The current rotation angle of the item, as described by its matrix. + */ + rotation: number; + + /** + * The current scale factor of the item, as described by its matrix. + */ + scaling: Point; + + /** + * The item's transformation matrix, defining position and dimensions in relation to its parent item in which it is contained. + */ + matrix: Matrix; + + /** + * The item's global transformation matrix in relation to the global project coordinate space. Note that the view's transformations resulting from zooming and panning are not factored in. + * Read Only. + */ + globalMatrix: Matrix; + + /** + * Controls whether the transformations applied to the item (e.g. through transform(matrix), rotate(angle), scale(scale), etc.) are stored in its matrix property, or whether they are directly applied to its contents or children (passed on to the segments in Path items, the children of Group items, etc.). + */ + applyMatrix: boolean; + + /** + * The project that this item belongs to. + * Read only. + */ + project: Project; + + /** + * The view that this item belongs to. + * Read Only. + */ + view: View; + + /** + * The layer that this item is contained within. + * Read Only. + */ + layer: Layer; + + /** + * The item that this item is contained within. + */ + parent: Item; + + /** + * The children items contained within this item. Items that define a name can also be accessed by name. + * Please note: The children array should not be modified directly using array functions. To remove single items from the children list, use item.remove(), to remove all items from the children list, use item.removeChildren(). To add items to the children list, use item.addChild(item) or item.insertChild(index, item). + */ + children: Item[]; + + /** + * The first item contained within this item. This is a shortcut for accessing item.children[0]. + */ + firstChild: Item; + + /** + * The last item contained within this item.This is a shortcut for accessing item.children[item.children.length - 1]. + */ + lastChild: Item; + + /** + * The next item on the same level as this item. + * Read Only. + */ + nextSibling: Item; + + /** + * The previous item on the same level as this item. + * Read Only. + */ + previousSibling: Item; + + /** + * The index of this item within the list of its parent's children. + * Read only. + */ + index: number; + + /** + * The color of the stroke. + */ + strokeColor: Color | string; + + /** + * The width of the stroke. + */ + strokeWidth: number; + + /** + * The shape to be used at the beginning and end of open Path items, when they have a stroke. + * String('round', 'square', 'butt') + */ + strokeCap: string; + + /** + * The shape to be used at the segments and corners of Path items when they have a stroke. + * String('miter', 'round', 'bevel') + */ + strokeJoin: string; + + /** + * The dash offset of the stroke. + */ + dashOffset: number; + + /** + * Specifies whether the stroke is to be drawn taking the current affine transformation into account (the default behavior), or whether it should appear as a non-scaling stroke. + */ + strokeScaling: boolean; + + /** + * Specifies an array containing the dash and gap lengths of the stroke. + */ + dashArray: number[]; + + /** + * When two line segments meet at a sharp angle and miter joins have been specified for item.strokeJoin, it is possible for the miter to extend far beyond the item.strokeWidth of the path. The miterLimit imposes a limit on the ratio of the miter length to the item.strokeWidth. + */ + miterLimit: number; + + /** + * The winding-rule with which the shape gets filled. Please note that only modern browsers support winding-rules other than 'nonzero'. + * String('nonzero', 'evenodd') + */ + windingRule: string; + + /** + * The fill color of the item. + */ + fillColor: Color | string; + + /** + * The color the item is highlighted with when selected. If the item does not specify its own color, the color defined by its layer is used instead. + */ + selectedColor: Color | string; + + /** + * Item level handler function to be called on each frame of an animation. + * The function receives an event object which contains information about the frame event: + */ + onFrame: (event: IFrameEvent) => void; + + /** + * The function to be called when the mouse button is pushed down on the item. The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseDown: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse button is released over the item. + * The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseUp: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse clicks on the item. The function receives a MouseEvent object which contains information about the mouse event. + */ + onClick: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse double clicks on the item. The function receives a MouseEvent object which contains information about the mouse event. + */ + onDoubleClick: (event: MouseEvent) => void; + + /** + * The function to be called repeatedly when the mouse moves on top of the item. The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseMove: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse moves over the item. This function will only be called again, once the mouse moved outside of the item first. The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseEnter: (event: MouseEvent) => void; + + /** + * The function to be called when the mouse moves out of the item. + * The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseLeave: (event: MouseEvent) => void; + + /** + * Sets those properties of the passed object literal on this item to the values defined in the object literal, if the item has property of the given name (or a setter defined for it). + */ + set(props: any): Item; + + /** + * Clones the item within the same project and places the copy above the item. + * @param insert [optional] - specifies whether the copy should be inserted into the DOM. When set to true, it is inserted above the original. default: true + */ + clone(insert?: boolean): Item; + + /** + * When passed a project, copies the item to the project, or duplicates it within the same project. When passed an item, copies the item into the specified item. + * @param item - the item or project to copy the item to + */ + copyTo(item: Item): Item; + + /** + * Rasterizes the item into a newly created Raster object. The item itself is not removed after rasterization. + * @param resolution [optional] - the resolution of the raster in pixels per inch (DPI). If not specified, the value of view.resolution is used. default: view.resolution + */ + rasterize(resolution: number): Raster; + + /** + * Checks whether the item's geometry contains the given point. + * @param point - The point to check for. + */ + contains(point: Point): boolean; + + /** + * + * @param rect - the rectangle to check against + */ + isInside(rect: Rectangle): boolean; + + /** + * + * @param item - the item to check against + */ + intersects(item: Item): boolean; + + /** + * Perform a hit-test on the items contained within the project at the location of the specified point. + * The options object allows you to control the specifics of the hit-test and may contain a combination of the following values: + * @param point - the point where the hit-test should be performed + * @param options.tolerance -the tolerance of the hit-test in points. Can also be controlled through paperScope.settings.hitTolerance + * @param options.class - only hit-test again a certain item class and its sub-classes: Group, Layer, Path, CompoundPath, Shape, Raster, PlacedSymbol, PointText, etc. + * @param options.fill - hit-test the fill of items. + * @param options.stroke - hit-test the stroke of path items, taking into account the setting of stroke color and width. + * @param options.segments - hit-test for segment.point of Path items. + * @param options.curves - hit-test the curves of path items, without taking the stroke color or width into account. + * @param options.handles - hit-test for the handles. (segment.handleIn / segment.handleOut) of path segments. + * @param options.ends - only hit-test for the first or last segment points of open path items. + * @param options.bounds - hit-test the corners and side-centers of the bounding rectangle of items (item.bounds). + * @param options.center - hit-test the rectangle.center of the bounding rectangle of items (item.bounds). + * @param options.guides - hit-test items that have Item#guide set to true. + * @param options.selected - only hit selected items. + */ + hitTest(point: Point, options?: { tolerance?: number; class?: string; fill?: boolean; stroke?: boolean; segments?: boolean; curves?: boolean; handles?: boolean; ends?: boolean; bounds?: boolean; center?: boolean; guides?: boolean; selected?: boolean; }): HitResult; + + /** + * Checks whether the item matches the criteria described by the given object, by iterating over all of its properties and matching against their values through matches(name, compare). + * See project.getItems(match) for a selection of illustrated examples. + * @param match - the criteria to match against. + */ + matches(match: any): boolean; + + /** + * Checks whether the item matches the given criteria. Extended matching is possible by providing a compare function or a regular expression. + * Matching points, colors only work as a comparison of the full object, not partial matching (e.g. only providing the x-coordinate to match all points with that x-value). Partial matching does work for item.data. + * @param name - the name of the state to match against. + * @param compare - the value, function or regular expression to compare against. + */ + matches(name: string, compare: any): boolean; + + /** + * Fetch the descendants (children or children of children) of this item that match the properties in the specified object. + * Extended matching is possible by providing a compare function or regular expression. Matching points, colors only work as a comparison of the full object, not partial matching (e.g. only providing the x- coordinate to match all points with that x-value). Partial matching does work for item.data. + * Matching items against a rectangular area is also possible, by setting either match.inside or match.overlapping to a rectangle describing the area in which the items either have to be fully or partly contained. + * @param match.inside - the rectangle in which the items need to be fully contained. + * @param match.overlapping - the rectangle with which the items need to at least partly overlap. + */ + getItems(match: any): Item[]; + + /** + * Fetch the first descendant (child or child of child) of this item that matches the properties in the specified object. + * Extended matching is possible by providing a compare function or regular expression. Matching points, colors only work as a comparison of the full object, not partial matching (e.g. only providing the x- coordinate to match all points with that x-value). Partial matching does work for item.data. + * @param match - the criteria to match against + */ + getItem(match: any): Item; + + /** + * Exports (serializes) the project with all its layers and child items to a JSON data string. + * @param options [optional] - default {asString: true, precision: 5} + * @param options.asString - whether the JSON is returned as a Object or a String. + * @param options.precision - the amount of fractional digits in numbers used in JSON data. + */ + exportJSON(options?: { asString?: boolean; precision?: number }): string; + + /** + * Imports (deserializes) the stored JSON data into the project. + * Note that the project is not cleared first. You can call project.clear() to do so. + */ + importJSON(json: string): void; + + /** + * Exports the project with all its layers and child items as an SVG DOM, all contained in one top level SVG group node. + * @param options [optional] the export options, default: { asString: false, precision: 5, matchShapes: false } + * @param options.asString - whether a SVG node or a String is to be returned. + * @param options.precision - the amount of fractional digits in numbers used in SVG data. + * @param options.matchShapes - whether path items should tried to be converted to shape items, if their geometries can be made to match + */ + exportSVG(options?: { asString?: boolean; precision?: number; matchShapes?: boolean }): SVGElement; + + /** + * Converts the provided SVG content into Paper.js items and adds them to the active layer of this project. + * Note that the project is not cleared first. You can call project.clear() to do so. + * @param svg - the SVG content to import + * @param options [optional] - the import options, default: { expandShapes: false } + * @param options.expandShapes - whether imported shape items should be expanded to path items. + */ + importSVG(svg: SVGElement | string, options?: any): Item; + + /** + * Adds the specified item as a child of this item at the end of the its children list. You can use this function for groups, compound paths and layers. + * @param item - the item to add as a child + */ + addChild(item: Item): Item; + + /** + * Inserts the specified item as a child of this item at the specified index in its children list. You can use this function for groups, compound paths and layers. + * @param index - the index + * @param item - the item to be inserted as a child + */ + insertChild(index: number, item: Item): Item; + + /** + * Adds the specified items as children of this item at the end of the its children list. You can use this function for groups, compound paths and layers. + * @param items - The items to be added as children + */ + addChildren(items: Item[]): Item[]; + + /** + * Inserts the specified items as children of this item at the specified index in its children list. You can use this function for groups, compound paths and layers. + * @param index - + * @param items - The items to be appended as children + */ + insertChildren(index: number, items: Item[]): Item[]; + + /** + * Inserts this item above the specified item. + * @param item - the item above which it should be inserted + */ + insertAbove(item: Item): Item; + + /** + * Inserts this item below the specified item. + * @param item - the item below which it should be inserted + */ + insertBelow(item: Item): Item; + + /** + * Sends this item to the back of all other items within the same parent. + */ + sendToBack(): void; + + /** + * Brings this item to the front of all other items within the same parent. + */ + bringToFront(): void; + + /** + * If this is a group, layer or compound-path with only one child-item, the child-item is moved outside and the parent is erased. Otherwise, the item itself is returned unmodified. + */ + reduce(): Item; + + /** + * Removes the item and all its children from the project. The item is not destroyed and can be inserted again after removal. + */ + remove(): boolean; + + /** + * Replaces this item with the provided new item which will takes its place in the project hierarchy instead. + * @param item - the item to replace this one with + */ + replaceWith(item: Item): boolean; + + /** + * Removes all of the item's children (if any). + */ + removeChildren(): Item[]; + + /** + * Removes the children from the specified from index to the to index from the parent's children array. + * @param from - the beginning index, inclusive + * @param to [optional] - the ending index, exclusive, default: children.length + */ + removeChildren(from: number, to?: number): Item[]; + + /** + * Reverses the order of the item's children + */ + reverseChildren(): void; + + /** + * Specifies whether the item has any content or not. The meaning of what content is differs from type to type. For example, a Group with no children, a TextItem with no text content and a Path with no segments all are considered empty. + */ + isEmpty(): boolean; + + /** + * Checks whether the item has a fill. + */ + hasFill(): boolean; + + /** + * Checks whether the item has a stroke. + */ + hasStroke(): boolean; + + /** + * Checks whether the item has a shadow. + */ + hasShadow(): boolean; + + /** + * Checks if the item contains any children items. + */ + hasChildren(): boolean; + + /** + * Checks whether the item and all its parents are inserted into the DOM or not. + */ + isInserted(): boolean; + + /** + * Checks if this item is above the specified item in the stacking order of the project. + * @param item - The item to check against + */ + isAbove(item: Item): boolean; + + /** + * Checks if the item is below the specified item in the stacking order of the project. + * @param item - The item to check against + */ + isBelow(item: Item): boolean; + + /** + * Checks whether the specified item is the parent of the item. + * @param item - The item to check against + */ + isParent(item: Item): boolean; + + /** + * Checks whether the specified item is a child of the item. + * @param item - The item to check against + */ + isChild(item: Item): boolean; + + /** + * Checks if the item is contained within the specified item. + * @param item - The item to check against + */ + isDescendant(item: Item): boolean; + + /** + * Checks if the item is an ancestor of the specified item. + * @param item - the item to check against + */ + isAncestor(item: Item): boolean; + + /** + * Checks whether the item is grouped with the specified item. + * @param item - + */ + isGroupedWith(item: Item): boolean; + + /** + * Translates (moves) the item by the given offset point. + * @param delta - the offset to translate the item by + */ + translate(delta: number): Point; + + /** + * Rotates the item by a given angle around the given point. + * Angles are oriented clockwise and measured in degrees. + * @param angle - the rotation angle + * @param center [optional] - default: item.position + */ + rotate(angle: number, center?: Point): void; + + /** + * Scales the item by the given value from its center point, or optionally from a supplied point. + * @param scale - the scale factor + * @param center [optional] - default: item.position + */ + scale(scale: number, center?: Point): void; + + /** + * Scales the item by the given values from its center point, or optionally from a supplied point. + * @param hor - the horizontal scale factor + * @param ver - the vertical scale factor + * @param center [optional] - default: item.position + */ + scale(hor: number, ver: number, center?: Point): void; + + /** + * Shears the item by the given value from its center point, or optionally by a supplied point. + * @param shear - the horziontal and vertical shear factors as a point + * @param center [optional] - default: item.position + */ + shear(shear: number, center?: Point): void; + + /** + * Shears the item by the given values from its center point, or optionally by a supplied point. + * @param hor - the horizontal shear factor + * @param ver - the vertical shear factor + * @param center [optional] - default: item.position + */ + shear(hor: number, ver: number, center?: Point): void; + + /** + * Skews the item by the given angles from its center point, or optionally by a supplied point. + * @param skew - the horziontal and vertical skew angles in degrees + * @param center [optional] - default: item.position + */ + skew(skew: Point, center?: Point): void; + + /** + * Skews the item by the given angles from its center point, or optionally by a supplied point. + * @param hor - the horizontal skew angle in degrees + * @param ver - the vertical sskew angle in degrees + * @param center [optional] - default: item.position + */ + skew(hor: number, ver: number, center?: Point): void; + + /** + * Transform the item. + * @param matrix - the matrix by which the item shall be transformed. + */ + transform(matrix: Matrix): void; + + /** + * Converts the specified point from global project coordinate space to the item's own local coordinate space. + * @param point - the point to be transformed + */ + globalToLocal(point: Point): Point; + + /** + * Converts the specified point from the item's own local coordinate space to the global project coordinate space. + * @param point - the point to be transformed + */ + localToGlobal(point: Point): Point; + + /** + * Converts the specified point from the parent's coordinate space to item's own local coordinate space. + * @param point - the point to be transformed + */ + parentToLocal(point: Point): Point; + + /** + * Converts the specified point from the item's own local coordinate space to the parent's coordinate space. + * @param point - the point to be transformed + */ + localToParent(point: Point): Point; + + /** + * Transform the item so that its bounds fit within the specified rectangle, without changing its aspect ratio. + * @param rectangle - + * @param fill [optiona;] - default = false + */ + fitBounds(rectangle: Rectangle, fill?: boolean): void; + + //I cannot use function: Function as it is a reserved keyword + + /** + * Attach an event handler to the tool. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param function - The function to be called when the event occurs + */ + on(type: string, callback: (event: ToolEvent) => void): Tool; + + /** + * Attach one or more event handlers to the tool. + * @param param - an object literal containing one or more of the following properties: mousedown, mouseup, mousedrag, mousemove, keydown, keyup + */ + on(param: any): Tool; + + /** + * Detach an event handler from the tool. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param function - The function to be detached + */ + off(type: string, callback: (event: ToolEvent) => void): Tool; + + /** + * Detach one or more event handlers from the tool. + * @param param - an object literal containing one or more of the following properties: mousedown, mouseup, mousedrag, mousemove, keydown, keyup + */ + off(param: any): Tool; + + /** + * Emit an event on the tool. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param event - an object literal containing properties describing the event. + */ + emit(type: string, event: any): boolean; + + /** + * Check if the tool has one or more event handlers of the specified type. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + */ + responds(type: string): boolean;//I cannot use function: Function as it is a reserved keyword + + /** + * Attaches an event handler to the item. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param function - The function to be called when the event occurs + */ + on(type: string, callback: () => void): Item; + + /** + * Attaches one or more event handlers to the item. + * @param param - an object literal containing one or more of the following properties: mousedown, mouseup, mousedrag, mousemove, keydown, keyup + */ + on(param: any): Item; + + /** + * Detach an event handler from the item. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param function - The function to be detached + */ + off(type: string, callback: (event: ToolEvent) => void): Item; + + /** + * Detach one or more event handlers to the item. + * @param param - an object literal containing one or more of the following properties: mousedown, mouseup, mousedrag, mousemove, keydown, keyup + */ + off(param: any): Item; + + /** + * Emit an event on the item. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param event - an object literal containing properties describing the event. + */ + emit(type: string, event: any): boolean; + + /** + * Check if the item has one or more event handlers of the specified type.. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + */ + responds(type: string): boolean; + + /** + * Removes the item when the events specified in the passed object literal occur. + * @param object - The object literal can contain the following values + * @param object.move - Remove the item when the next tool.onMouseMove event is fired + * @param object.drag - Remove the item when the next tool.onMouseDrag event is fired + * @param object.down - Remove the item when the next tool.onMouseDown event is fired + * @param object.up - Remove the item when the next tool.onMouseUp event is fired + */ + removeOn(object: { move?: boolean; drag?: boolean; down?: boolean; up?: boolean; }): void; + + /** + * Removes the item when the next tool.onMouseMove event is fired. + */ + removeOnMove(): void; + + /** + * Removes the item when the next tool.onMouseDown event is fired. + */ + removeOnDown(): void; + + /** + * Removes the item when the next tool.onMouseDrag event is fired. + */ + removeOnDrag(): void; + + /** + * Removes the item when the next tool.onMouseUp event is fired. + */ + removeOnUp(): void; + + } + /** + * A Group is a collection of items. When you transform a Group, its children are treated as a single unit without changing their relative positions. + */ + export class Group extends Item { + + /** + * Creates a new Group item and places it at the top of the active layer. + * @param children [optional] - An array of Item Objects children that will be added to the newly created group. + */ + constructor(children?: Item[]); + + /** + * Creates a new Group item and places it at the top of the active layer. + * @param object [optional] - an object literal containing the properties to be set on the group. + */ + constructor(object?: any); + + /** + * Specifies whether the group item is to be clipped. + * When setting to true, the first child in the group is automatically defined as the clipping mask. + */ + clipped: boolean; + + } + /** + * The Layer item represents a layer in a Paper.js project. + * The layer which is currently active can be accessed through project.activeLayer. + * An array of all layers in a project can be accessed through project.layers. + */ + export class Layer extends Group { + + /** + * Creates a new Layer item and places it at the end of the project.layers array. The newly created layer will be activated, so all newly created items will be placed within it. + * @param children [optional] - An array of Items that will be added to the newly created layer. + */ + constructor(children?: Item[]); + /** + * Creates a new Layer item and places it at the end of the project.layers array. The newly created layer will be activated, so all newly created items will be placed within it. + * @param object [optional] - an object literal containing the properties to be set on the layer. + */ + constructor(object?: any); + + /** + * Activates the layer. + */ + activate(): void; + + } + export class Shape extends Item { + + /** + * Creates a circular shape item. + * @param center - the center point of the circle + * @param radius - the radius of the circle + */ + static Circle(center: Point, radius: number): Shape; + + /** + * Creates a circular shape item from the properties described by an object literal. + * @param object - an object literal containing properties descriving the shapes attributes + */ + static Circle(object: any): Shape; + + /** + * Creates a rectangular shape item, with optionally rounded corners. + * @param rectangle - the rectangle object describing the geometry of the rectangular shape to be created. + * @param radius [optional] - the size of the rounded corners, default: null + */ + static Rectangle(rectangle: Rectangle, radius?: number): Shape; + + /** + * Creates a rectangular shape item from a point and a size object. + * @param point - the rectangle's top-left corner + * @param size - the rectangle's size. + */ + static Rectangle(point: Point, size: Size): Shape; + + /** + * Creates a rectangular shape item from the passed points. These do not necessarily need to be the top left and bottom right corners, the constructor figures out how to fit a rectangle between them. + * @param from - the first point defining the rectangle + * @param to - the second point defining the rectangle + */ + static Rectangle(from: Point, to: Point): Shape; + + /** + * Creates a rectangular shape item from the properties described by an object literal. + * @param object - an object literal containing properties describing the shape's attributes + */ + static Rectangle(object: any): Shape; + + /** + * Creates an elliptical shape item. + * @param rectangle - the rectangle circumscribing the ellipse + */ + static Ellipse(rectangle: Rectangle): Shape; + + /** + * Creates an elliptical shape item from the properties described by an object literal. + * @param object - an object literal containing properties describing the shape's attributes + */ + static Ellipse(object: any): Shape; + + /** + * The type of shape of the item as a string. + */ + type: string; + + /** + * The size of the shape. + */ + size: Size; + + /** + * The radius of the shape, as a number if it is a circle, or a size object for ellipses and rounded rectangles. + */ + radius: number | Size; + + } + /** + * The Raster item represents an image in a Paper.js project. + */ + export class Raster extends Item { + + /** + * Creates a new raster item from the passed argument, and places it in the active layer. object can either be a DOM Image, a Canvas, or a string describing the URL to load the image from, or the ID of a DOM element to get the image from (either a DOM Image or a Canvas). + * @param source [optional] - the source of the raster + * @param position [optional] - the center position at which the raster item is placed + */ + constructor(source?: HTMLImageElement | HTMLCanvasElement | string, position?: Point); + + /** + * The size of the raster in pixels. + */ + size: Size; + + /** + * The width of the raster in pixels. + */ + width: number; + + /** + * The height of the raster in pixels. + */ + height: number; + + /** + * The resolution of the raster at its current size, in PPI (pixels per inch). + * Read Only. + */ + resolution: Size; + + /** + * The HTMLImageElement of the raster, if one is associated. + */ + image: HTMLImageElement | HTMLCanvasElement; + + /** + * The Canvas object of the raster. If the raster was created from an image, accessing its canvas causes the raster to try and create one and draw the image into it. Depending on security policies, this might fail, in which case null is returned instead. + */ + canvas: HTMLCanvasElement; + + /** + * The Canvas 2D drawing context of the raster. + */ + context: CanvasRenderingContext2D; + + /** + * The source of the raster, which can be set using a DOM Image, a Canvas, a data url, a string describing the URL to load the image from, or the ID of a DOM element to get the image from (either a DOM Image or a Canvas). Reading this property will return the url of the source image or a data-url. + */ + source: HTMLImageElement | HTMLCanvasElement | string; + + /** + * Extracts a part of the Raster's content as a sub image, and returns it as a Canvas object. + * @param rect - the boundaries of the sub image in pixel coordinates + */ + getSubCanvas(rect: Rectangle): HTMLCanvasElement; + + /** + * Extracts a part of the raster item's content as a new raster item, placed in exactly the same place as the original content. + * @param rect - the boundaries of the sub raster in pixel coordinates + */ + getSubRaster(rect: Rectangle): Raster; + + /** + * Returns a Base 64 encoded data: URL representation of the raster. + */ + toDataURL(): string; + + /** + * Draws an image on the raster. + * @param image - the image to draw + * @param point - the offset of the image as a point in pixel coordinates + */ + drawImage(image: HTMLImageElement | HTMLCanvasElement, point: Point): void; + + /** + * Calculates the average color of the image within the given path, rectangle or point. This can be used for creating raster image effects. + * @param object - the path, rectangle or point to get the average image color from + */ + getAverageColor(object: Path | Rectangle | Point): Color; + + /** + * Gets the color of a pixel in the raster. + * @param x - the x offset of the pixel in pixel coordinates + * @param y - the y offset of the pixel in pixel coordinates + */ + getPixel(x: number, y: number): Color; + + /** + * Gets the color of a pixel in the raster. + * @param point - the offset of the pixel as a point in pixel coordinates + */ + getPixel(point: Point): Color; + + /** + * Sets the color of the specified pixel to the specified color + * @param x - the x offset of the pixel in pixel coordinates + * @param y - the y offset of the pixel in pixel coordinates + * @param color - the color that the pixel will be set to + */ + setPixel(x: number, y: number, color: Color): void; + + /** + * Sets the color of the specified pixel to the specified color. + * @param point - the offset of the pixel as a point in pixel coordinates + * @param color - the color that the pixel will be set to + */ + setPixel(point: Point, color: Color): void; + + /** + * + * @param size + */ + createImageData(size: Size): ImageData; + + /** + * + * @param rect + */ + getImageData(rect: Rectangle): ImageData; + + /** + * + * + * @param data + * @param point + */ + getImageData(data: ImageData, point: Point): void; + + } + /** + * A PlacedSymbol represents an instance of a symbol which has been placed in a Paper.js project. + */ + export class PlacedSymbol extends Item { + + /** + * Creates a new PlacedSymbol Item. + * @param symbol - the symbol to place + * @param point [optional] - the center point of the placed symbol + */ + constructor(symbol: Symbol, point?: Point); + + /** + * The symbol that the placed symbol refers to. + */ + symbol: Symbol; + + } + /** + * A HitResult object contains information about the results of a hit test. It is returned by item.hitTest(point) and project.hitTest(point). + */ + export class HitResult { + + /** + * Describes the type of the hit result. For example, if you hit a segment point, the type would be 'segment'. + * type String('segment', 'handle-in', 'handle-out', 'curve', 'stroke', 'fill', 'bounds', 'center', 'pixel') + */ + type: string; + + /** + * If the HitResult has a hitResult.type of 'bounds', this property describes which corner of the bounding rectangle was hit. + * type String('top-left', 'top-right', 'bottom-left', 'bottom-right', 'left-center', 'top-center', 'right-center', 'bottom-center') + */ + name: string; + + /** + * The item that was hit. + */ + item: Item; + + /** + * If the HitResult has a type of 'curve' or 'stroke', this property gives more information about the exact position that was hit on the path. + */ + location: CurveLocation; + + /** + * If the HitResult has a type of 'pixel', this property refers to the color of the pixel on the Raster that was hit. + */ + color: Color; + + /** + * If the HitResult has a type of 'stroke', 'segment', 'handle-in' or 'handle-out', this property refers to the segment that was hit or that is closest to the hitResult.location on the curve. + */ + segment: Segment; + + /** + * Describes the actual coordinates of the segment, handle or bounding box corner that was hit + */ + point: Point; + + } + /** + * The PathItem class is the base for any items that describe paths and offer standardised methods for drawing and path manipulation, such as Path and CompoundPath. + */ + export class PathItem extends Item { + + /** + * The path's geometry, formatted as SVG style path data. + */ + pathData: string; + + /** + * Returns all intersections between two PathItem items as an array of CurveLocation objects. CompoundPath items are also supported. + * @param path - the other item to find the intersections with + * @param sorted [optional] - specifies whether the returned CurveLocation objects should be sorted by path and offset, default: false + */ + getIntersections(path: PathItem, sorted?: boolean): CurveLocation[]; + + /** + * Smooth bezier curves without changing the amount of segments or their points, by only smoothing and adjusting their handle points, for both open ended and closed paths. + */ + smooth(): void; + + /** + * On a normal empty Path, the point is simply added as the path's first segment. If called on a CompoundPath, a new Path is created as a child and the point is added as its first segment. + * @param point - the path's first segment + */ + moveTo(point: Point): void; + + /** + * Draw a line from the current point to the given point + * @param point - the end point of the line + */ + lineTo(point: Point): void; + + /** + * Adds a cubic bezier curve to the path, defined by two handles and a to point. + * @param handle1 - The first control point handle for the curve + * @param handle2 - The second control point handle for the curve + * @param to - The end control point of the curve + */ + cublicCurveTo(handle1: Point, handle2: Point, to: Point): void; + + /** + * Adds a quadratic bezier curve to the path, defined by a handle and a to point. + * @param handle - The control point for the curve + * @param to - The end control point of the curve + */ + quadraticCurveTo(handle: Point, to: Point): void; + + /** + * Draws a curve from the position of the last segment point in the path that goes through the specified through point, to the specified to point by adding one segment to the path. + * @param through - the point through which the curve should go + * @param to - the point where the curve should end + * @param parameter [optional] - default: 0.5 + */ + curveTo(through: Point, to: Point, parameter?: number): void; + + /** + * Draws an arc from the position of the last segment point in the path that goes through the specified through point, to the specified to point by adding one or more segments to the path. + * @param through - the point where the arc should pass through + * @param to - the point where the arc should end + */ + arcTo(through: Point, to: Point): void; + + /** + * Draws an arc from the position of the last segment point in the path to the specified point by adding one or more segments to the path. + * @param to - the point where the arc should end + * @param closewise [optional] - specifies whether the arc should be drawn in clockwise direction. optional, default: true + */ + arcTo(to: Point, clockwise?: boolean): void; + + /** + * Closes the path. When closed, Paper.js connects the first and last segment of the path with an additional curve. + * @param join - controls whether the method should attempt to merge the first segment with the last if they lie in the same location. + */ + closePath(join: boolean): void; + + /** + * If called on a CompoundPath, a new Path is created as a child and a point is added as its first segment relative to the position of the last segment of the current path. + * @param to - + */ + moveBy(to: Point): void; + + /** + * Adds a segment relative to the last segment point of the path. + * @param to - the vector which is added to the position of the last segment of the path, to get to the position of the new segment. + */ + lineBy(to: Point): void; + + /** + * + * @param through - + * @param to - + * @param parameter [optional] - default 0.5 + */ + curveBy(through: Point, to: Point, parameter?: number): void; + + /** + * + * @param handle1 - + * @param handle2 - + * @param to - + */ + cublicCurveBy(handle1: Point, handle2: Point, to: Point): void; + + /** + * + * @param handle - + * @param to - + */ + quadraticCurveBy(handle: Point, to: Point): void; + + /** + * + * @param through - + * @param to - + */ + arcBy(through: Point, to: Point): void; + + /** + * + * @param to - + * @param clockwise [optional] - default: true + */ + arcBy(to: Point, clockwise?: boolean): void; + + /** + * Merges the geometry of the specified path from this path's geometry and returns the result as a new path item. + * @param path - the path to unite with + */ + unite(path: PathItem): PathItem; + + /** + * Intersects the geometry of the specified path with this path's geometry and returns the result as a new path item. + * @param path - the path to intersect with + */ + intersect(path: PathItem): PathItem; + + /** + * Subtracts the geometry of the specified path from this path's geometry and returns the result as a new path item. + * @param - the path to subtract + */ + subtract(path: PathItem): PathItem; + + /** + * Excludes the intersection of the geometry of the specified path with this path's geometry and returns the result as a new group item. + * @param - the path to exclude the intersection of + */ + exclude(path: PathItem): PathItem; + + /** + * Splits the geometry of this path along the geometry of the specified path returns the result as a new group item. + * @param - the path to divide by + */ + divide(path: PathItem): PathItem; + + } + /** + * The path item represents a path in a Paper.js project. + */ + export class Path extends PathItem { + + /** + * Creates a linear path item from two points describing a line. + * @param from - the line's starting point + * @param to - the line's ending point + */ + static Line(from: Point, to: Point): Path; + + /** + * Creates a linear path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static Line(object: any): Path; + + /** + * Creates a circular path item. + * @param center - the center point of the circle + * @param radius - the radius of the circle + */ + static Circle(center: Point, radius: number): Path; + + /** + * Creates a circular path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static Circle(object: any): Path; + + /** + * Creates a rectangular path item, with optionally rounded corners. + * @param rectangle - the rectangle object describing the geometry of the rectangular path to be created. + * @param radius [optional] - the size of the rounded corners default: null + */ + static Rectangle(rectangle: Rectangle, radius?: number): Path; + + /** + * Creates a rectangular path item from a point and a size object. + * @param point - the rectangle's top-left corner. + * @param size - the rectangle's size. + */ + static Rectangle(point: Point, size: Size): Path; + + /** + * Creates a rectangular path item from the passed points. These do not necessarily need to be the top left and bottom right corners, the constructor figures out how to fit a rectangle between them. + * @param from - the first point defining the rectangle + * @param to - the second point defining the rectangle + */ + static Rectangle(from: Point, to: Point): Path; + + /** + * Creates a rectangular path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static Rectangle(object: any): Path; + + /** + * Creates an elliptical path item. + * @param rectangle - the rectangle circumscribing the ellipse + */ + static Ellipse(rectangle: Rectangle): Path; + + /** + * Creates an elliptical path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static Ellipse(object: any): Path; + /** + * Creates a circular arc path item + * @param from - the starting point of the circular arc + * @param through - the point the arc passes through + * @param to - the end point of the arc + */ + static Arc(from: Point, through: Point, to: Point): Path; + + /** + * Creates an circular arc path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static Arc(object: any): Path; + + /** + * Creates a regular polygon shaped path item. + * @param center - the center point of the polygon + * @param sides - the number of sides of the polygon + * @param radius - the radius of the polygon + */ + static RegularPolygon(center: Point, sides: number, radius: number): Path; + + /** + * Creates a regular polygon shaped path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static RegularPolygon(object: any): Path; + + /** + * Creates a star shaped path item. The largest of radius1 and radius2 will be the outer radius of the star. The smallest of radius1 and radius2 will be the inner radius. + * @param center - the center point of the star + * @param points - the number of points of the star + * @param radius1 + * @param radius2 + */ + static Star(center: Point, points: number, radius1: number, radius2: number): Path; + + /** + * Creates a star shaped path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + static Star(object: any): Path; + + /** + * Creates a new path item and places it at the top of the active layer. + * @param segments [optional] - An array of segments (or points to be converted to segments) that will be added to the path + */ + constructor(segments?: Segment[]| Point[]); + + /** + * Creates a new path item from an object description and places it at the top of the active layer. + * @param object - an object literal containing properties describing the path's attributes + */ + constructor(object?: any); + + /** + * Creates a new path item from SVG path-data and places it at the top of the active layer. + * @param pathData - the SVG path-data that describes the geometry of this path. + */ + constructor(pathData?: string); + + /** + * The segments contained within the path. + * Array of Segment objects + */ + segments: Segment[]; + + /** + * The first Segment contained within the path. + * Read only. + */ + firstSegment: Segment; + + /** + * The last Segment contained within the path + * Read only. + */ + lastSegment: Segment; + + /** + * The curves contained within the path. + * Array of Curve objects + */ + curves: Curve[]; + + /** + * The first Curve contained within the path. + * Read only. + */ + firstCurve: Curve; + + /** + * The last Curve contained within the path. + * Read only. + */ + lastCurve: Curve; + + /** + * Specifies whether the path is closed. If it is closed, Paper.js connects the first and last segments. + */ + closed: boolean; + + /** + * The approximate length of the path in points. + * Read only. + */ + length: number; + + /** + * The area of the path in square points. Self-intersecting paths can contain sub-areas that cancel each other out. + * Read only. + */ + area: number; + + /** + * Specifies whether the path and all its segments are selected. Cannot be true on an empty path. + */ + fullySelected: boolean; + + /** + * Specifies whether the path is oriented clock-wise. + */ + clockwise: boolean; + + /** + * Returns a point that is guaranteed to be inside the path. + * Read only. + */ + interiorPoint: Point; + + /** + * Adds one or more segments to the end of the segments array of this path. + * @param segment - the segment or point to be added. + * Returns the added segment. This is not necessarily the same object, e.g. if the segment to be added already belongs to another path. + */ + add(segment: Segment | Point): Segment; + + /** + * Inserts one or more segments at a given index in the list of this path's segments. + * @param index - the index at which to insert the segment. + * @param segment - the segment or point to be inserted. + * Returns the added segment. This is not necessarily the same object, e.g. if the segment to be added already belongs to another path. + */ + insert(index: number, segment: Segment | Point): Segment; + + /** + * Adds an array of segments (or types that can be converted to segments) to the end of the segments array. + * @param segments - Array of Segment objects + * Returns an array of the added segments. These segments are not necessarily the same objects, e.g. if the segment to be added already belongs to another path. + */ + addSegments(segments: Segment[]): Segment[]; + + /** + * Inserts an array of segments at a given index in the path's segments array. + * @param index - the index at which to insert the segments. + * @param segments - the segments to be inserted. + * Returns an array of the added segments. These segments are not necessarily the same objects, e.g. if the segment to be added already belongs to another path. + */ + insertSegments(index: number, segments: Segment[]): Segment[]; + + /** + * Removes the segment at the specified index of the path's segments array. + * @param index - the index of the segment to be removed + * Returns the removed segment + */ + removeSegment(index: number): Segment; + + /** + * Removes all segments from the path's segments array. + * Returns an array containing the removed segments + */ + removeSegments(): Segment[]; + + /** + * Removes the segments from the specified from index to the to index from the path's segments array. + * @param from - the beginning index, inclusive + * @param to [optional = segments.length] - the ending index + * Returns an array containing the removed segments + */ + removeSegments(from: number, to?: number): Segment[]; + + /** + * Converts the curves in a path to straight lines with an even distribution of points. The distance between the produced segments is as close as possible to the value specified by the maxDistance parameter. + * @param maxDistance - the maximum distance between the points + */ + flatten(maxDistance: number): void; + + /** + * Smooths a path by simplifying it. The path.segments array is analyzed and replaced by a more optimal set of segments, reducing memory usage and speeding up drawing. + * @param tolerance [optional = 2.5] - + */ + simplify(tolerance?: number): void; + + /** + * Splits the path at the given offset. After splitting, the path will be open. If the path was open already, splitting will result in two paths. + * @param offset - the offset at which to split the path as a number between 0 and path.length + * Returns the newly created path after splitting, if any + */ + split(offset: number): Path; + + /** + * Splits the path at the given curve location. After splitting, the path will be open. If the path was open already, splitting will result in two paths. + * @param location - the curve location at which to split the path + * Returns the newly created path after splitting, if any + */ + split(location: CurveLocation): Path; + + /** + * Splits the path at the given curve index and parameter. After splitting, the path will be open. If the path was open already, splitting will result in two paths. + * @param index - the index of the curve in the path.curves array at which to split + * @param parameter - the parameter at which the curve will be split + * Returns the newly created path after splitting, if any + */ + split(index: number, parameter: number): Path; + + /** + * Reverses the orientation of the path, by reversing all its segments. + */ + reverse(): void; + + /** + * Joins the path with the specified path, which will be removed in the process. + * @param path - the path to join this path with + * Returns the joined path + */ + join(path: Path): Path; + + /** + * Returns the curve location of the specified point if it lies on the path, null otherwise. + * @param point - the point on the path. + */ + getLocationOf(point: Point): CurveLocation; + + /** + * Returns the length of the path from its beginning up to up to the specified point if it lies on the path, null otherwise. + * @param point - the point on the path. + */ + getOffsetOf(point: Point): number; + + /** + * Returns the curve location of the specified offset on the path. + * @param offset - the offset on the path, where 0 is at the beginning of the path and path.length at the end. + * @param isParameter [optional=false] - + */ + getLocationAt(offset: number, isParameter?: boolean): CurveLocation; + + /** + * Calculates the point on the path at the given offset. Returns the point at the given offset + * @param offset - the offset on the path, where 0 is at the beginning of the path and path.length at the end. + * @param isParameter [optional=false] - + */ + getPointAt(offset: number, isPatameter?: boolean): Point; + + /** + * Calculates the tangent vector of the path at the given offset. Returns the tangent vector at the given offset + * @param offset - the offset on the path, where 0 is at the beginning of the path and path.length at the end. + * @param isParameter [optional=false] - + */ + getTangentAt(offset: number, isPatameter?: boolean): Point; + + /** + * Calculates the normal vector of the path at the given offset. Returns the normal vector at the given offset + * @param offset - the offset on the path, where 0 is at the beginning of the path and path.length at the end. + * @param isParameter [optional=false] - + */ + getNormalAt(offset: number, isParameter?: boolean): Point; + + /** + * Calculates the curvature of the path at the given offset. Curvatures indicate how sharply a path changes direction. A straight line has zero curvature, where as a circle has a constant curvature. The path's radius at the given offset is the reciprocal value of its curvature. + * @param offset - the offset on the path, where 0 is at the beginning of the path and path.length at the end. + * @param isParameter [optional=false] - + * @param point - the point for which we search the nearest location + */ + getCurvatureAt(offset: number, isParameter?: boolean, point?: Point): number; + + /** + * Returns the nearest point on the path to the specified point. + * @param point - the point for which we search the nearest point + */ + getNearestPoint(point: Point): Point; + + + } + /** + * A compound path contains two or more paths, holes are drawn where the paths overlap. All the paths in a compound path take on the style of the backmost path and can be accessed through its item.children list. + */ + export class CompoundPath extends PathItem { + + /** + * Creates a new compound path item from an object description and places it at the top of the active layer. + * @param object - an object literal containing properties to be set on the path + */ + constructor(object: any); + + /** + * Creates a new compound path item from SVG path-data and places it at the top of the active layer. + * @param pathData - the SVG path-data that describes the geometry of this path. + */ + constructor(pathData: string); + + /** + * Specifies whether the compound path is oriented clock-wise. + */ + clockwise: boolean; + + /** + * The first Segment contained within the path. + * Read Only + */ + firstSegment: Segment; + + /** + * The last Segment contained within the path. + * Read Only + */ + lastSegment: Segment; + + /** + * All the curves contained within the compound-path, from all its child Path items. + * Read Only + */ + curves: Curve[]; + + /** + * The first Curve contained within the path. + * Read Only + */ + firstCurve: Curve; + + /** + * The last Curve contained within the path. + * Read only. + */ + lastCurve: Curve; + + /** + * The area of the path in square points. Self-intersecting paths can contain sub-areas that cancel each other out. + * Read Only. + */ + area: number; + + /** + * Reverses the orientation of all nested paths. + */ + reverse(): void; + + } + /** + * The Segment object represents the points of a path through which its Curve objects pass. The segments of a path can be accessed through its path.segments array. + * Each segment consists of an anchor point (segment.point) and optionaly an incoming and an outgoing handle (segment.handleIn and segment.handleOut), describing the tangents of the two Curve objects that are connected by this segment. + */ + export class Segment { + + /** + * Creates a new Segment object. + * @param point [optional] - the anchor point of the segment default: {x: 0, y: 0} + * @param handleIn [optional] - the handle point relative to the anchor point of the segment that describes the in tangent of the segment default: {x: 0, y: 0} + * @param handleOut [optional] - the handle point relative to the anchor point of the segment that describes the out tangent of the segment default: {x: 0, y: 0} + */ + constructor(point?: Point, handleIn?: Point, handleOut?: Point); + + /** + * Creates a new Segment object. + * @param object - an object literal containing properties to be set on the segment. + */ + constructor(object?: any); + + /** + * The anchor point of the segment. + */ + point: Point; + + /** + * The handle point relative to the anchor point of the segment that describes the in tangent of the segment. + */ + handleIn: Point; + + /** + * The handle point relative to the anchor point of the segment that describes the out tangent of the segment. + */ + handleOut: Point; + + /** + * Specifies whether the segment has no handles defined, meaning it connects two straight lines. + */ + linear: boolean; + + /** + * Specifies whether the point of the segment is selected. + */ + selected: boolean; + + /** + * The index of the segment in the path.segments array that the segment belongs to. + * Read Only + */ + index: number; + + /** + * The path that the segment belongs to. + * Read Only + */ + path: Path; + + /** + * The curve that the segment belongs to. For the last segment of an open path, the previous segment is returned. + * Read only. + */ + curve: Curve; + + /** + * The curve location that describes this segment's position ont the path. + * Read Only. + */ + location: CurveLocation; + + /** + * The next segment in the path.segments array that the segment belongs to. If the segments belongs to a closed path, the first segment is returned for the last segment of the path. + * Read Only. + */ + next: Segment; + + /** + * The previous segment in the path.segments array that the segment belongs to. If the segments belongs to a closed path, the last segment is returned for the first segment of the path. + * Read Only. + */ + previous: Segment; + + /** + * Returns true if the the two segments are the beginning of two lines and if these two lines are running parallel. + * @param segment + */ + isColinear(segment: Segment): boolean; + + /** + * Returns true if the segment at the given index is the beginning of an orthogonal arc segment. The code looks at the length of the handles and their relation to the distance to the imaginary corner point. If the relation is kappa, then it's an arc. + */ + isArc(): boolean; + + /** + * Returns the reversed the segment, without modifying the segment itself. + */ + reverse(): Segment; + + /** + * Removes the segment from the path that it belongs to. + */ + remove(): boolean; + + /** + * A string representation of the segment + */ + toString(): string; + + /** + * Transform the segment by the specified matrix. + * @param matrix - the matrix to transform the segment by + */ + transform(matrix: Matrix): void; + + } + /** + * The Curve object represents the parts of a path that are connected by two following Segment objects. The curves of a path can be accessed through its path.curves array. + * While a segment describe the anchor point and its incoming and outgoing handles, a Curve object describes the curve passing between two such segments. Curves and segments represent two different ways of looking at the same thing, but focusing on different aspects. Curves for example offer many convenient ways to work with parts of the path, finding lengths, positions or tangents at given offsets. + */ + export class Curve { + + /** + * Creates a new curve object. + * @param segment1 - + * @param segment2 - + */ + constructor(segment1: Segment, segment2: Segment); + + /** + * Creates a new curve object. + * @param point1: Point + * @param handle1: Point + * @param handle2: Point + * @param point2: Point + */ + constructor(point1: Point, handle1: Point, handle2: Point, point2: Point); + + /** + * The first anchor point of the curve. + */ + point1: Point; + + /** + * The second anchor point of the curve. + */ + point2: Point; + + /** + * The handle point that describes the tangent in the first anchor point. + */ + handle1: Point; + + /** + * The handle point that describes the tangent in the second anchor point. + */ + handle2: Point; + + /** + * The first segment of the curve. + * Read Only. + */ + segment1: Segment; + + /** + * The second segment of the curve. + * Read only. + */ + segment2: Segment; + + /** + * The path that the curve belongs to. + * Read only. + */ + path: Path; + + /** + * The index of the curve in the path.curves array. + * Read Only. + */ + index: number; + + /** + * The next curve in the path.curves array that the curve belongs to. + * Read Only + */ + next: Curve; + + /** + * The previous curve in the path.curves array that the curve belongs to. + * Read Only. + */ + previous: Curve; + + /** + * Specifies whether the points and handles of the curve are selected. + */ + selected: boolean; + + /** + * The approximated length of the curve in points. + * Read Only. + */ + length: number; + + /** + * The bounding rectangle of the curve excluding stroke width. + */ + bounds: Rectangle; + + /** + * The bounding rectangle of the curve including stroke width. + */ + strokeBounds: Rectangle; + + /** + * The bounding rectangle of the curve including handles. + */ + handleBounds: Rectangle; + + /** + * Checks if this curve is linear, meaning it does not define any curve handle. + */ + isLinear(): boolean; + + /** + * TODO? + */ + //isHorizontal(): boolean; + + /** + * Divides the curve into two curves at the given offset. The curve itself is modified and becomes the first part, the second part is returned as a new curve. If the modified curve belongs to a path item, the second part is also added to the path. + * @param offset [optional] - the offset on the curve at which to split, or the curve time parameter if isParameter is true default: 0.5 + * @param isParameter [optional] - pass true if offset is a curve time parameter. default: false + */ + divide(offset?: number, isParameter?: boolean): Curve; + + /** + * Splits the path this curve belongs to at the given offset. After splitting, the path will be open. If the path was open already, splitting will result in two paths. + * @param offset [optional] - the offset on the curve at which to split, or the curve time parameter if isParameter is true default: 0.5 + * @param isParameter [optional] - pass true if offset is a curve time parameter. default: false + */ + split(offset?: number, isParameter?: boolean): Path; + + /** + * Returns a reversed version of the curve, without modifying the curve itself. + */ + reverse(): Curve; + + /** + * Removes the curve from the path that it belongs to, by merging its two path segments. + * returns true if the curve was removed, false otherwise + */ + remove(): boolean; + + /** + * Returns a copy of the curve. + */ + clone(): Curve; + + /** + * returns a string representation of the curve + */ + toString(): string; + + /** + * Calculates the curve time parameter of the specified offset on the path, relative to the provided start parameter. If offset is a negative value, the parameter is searched to the left of the start parameter. If no start parameter is provided, a default of 0 for positive values of offset and 1 for negative values of offset. + * @param offset - + * @param start [optional] - + */ + getParameterAt(offset: Point, start?: number): number; + + /** + * Returns the curve time parameter of the specified point if it lies on the curve, null otherwise. + * @param point - the point on the curve. + */ + getParameterOf(point: Point): number; + + /** + * Calculates the curve location at the specified offset or curve time parameter. + * @param offset - the offset on the curve, or the curve time parameter if isParameter is true + * @param isParameter [optional] - pass true if offset is a curve time parameter. default: false + */ + getLocationAt(offset: Point, isParameter?: boolean): CurveLocation; + + /** + * Returns the curve location of the specified point if it lies on the curve, null otherwise. + * @param point - the point on the curve + */ + getLocationOf(point: Point): CurveLocation; + + /** + * Returns the length of the path from its beginning up to up to the specified point if it lies on the path, null otherwise. + * @param point - the point on the path. + */ + getOffsetOf(point: Point): number; + + /** + * Calculates the point on the curve at the given offset. + * @param offset - the offset on the curve, or the curve time parameter if isParameter is true + * @param isParameter [optional] - pass true if offset is a curve time parameter. default: false + */ + getPointAt(offset: number, isParameter?: boolean): Point; + + /** + * Calculates the tangent vector of the curve at the given offset. + * @param offset - the offset on the curve, or the curve time parameter if isParameter is true + * @param isParameter [optional] - pass true if offset is a curve time parameter. default: false + */ + getTangentAt(offset: number, isParameter?: boolean): Point; + + /** + * Calculates the normal vector of the curve at the given offset. + * @param offset - the offset on the curve, or the curve time parameter if isParameter is true + * @param isParameter [optional] - pass true if offset is a curve time parameter. default: false + */ + getNormalAt(offset: number, isParameter?: boolean): Point; + + /** + * Calculates the curvature of the curve at the given offset. Curvatures indicate how sharply a curve changes direction. A straight line has zero curvature, where as a circle has a constant curvature. The curve's radius at the given offset is the reciprocal value of its curvature. + * @param offset - the offset on the curve, or the curve time parameter if isParameter is true + * @param isParameter - pass true if offset is a curve time parameter. default: false + */ + getCurvatureAt(offset: number, isParameter?: boolean): Point; + + } + /** + * CurveLocation objects describe a location on Curve objects, as defined by the curve parameter, a value between 0 (beginning of the curve) and 1 (end of the curve). If the curve is part of a Path item, its index inside the path.curves array is also provided. + * The class is in use in many places, such as path.getLocationAt(offset, isParameter), path.getLocationOf(point), Path#getNearestLocation(point),{@linkPathItem#getIntersections(path), etc. + */ + export class CurveLocation { + + /** + * Creates a new CurveLocation object. + * @param curve - + * @param parameter - + * @param point - + */ + constructor(curve: Curve, parameter: number, point: Point); + + /** + * The segment of the curve which is closer to the described location. + * Read Only + */ + segment: Segment; + + /** + * The curve that this location belongs to. + * Read Only + */ + curve: Curve; + + /** + * The curve location on the intersecting curve, if this location is the result of a call to pathItem.getIntersections(path) / Curve#getIntersections(curve). + * Read Only + */ + intersection: CurveLocation; + + /** + * The path this curve belongs to, if any. + * Read Only + */ + path: Path; + + /** + * The index of the curve within the path.curves list, if the curve is part of a Path item. + * Read Only. + */ + index: number; + + /** + * The length of the path from its beginning up to the location described by this object. If the curve is not part of a path, then the length within the curve is returned instead. + * Read only. + */ + offset: number; + + /** + * The length of the curve from its beginning up to the location described by this object. + * Read Only. + */ + curveOffset: number; + + /** + * The curve parameter, as used by various bezier curve calculations. It is value between 0 (beginning of the curve) and 1 (end of the curve). + * Read only. + */ + parameter: number; + + /** + * The point which is defined by the curve and parameter. + * Read only. + */ + point: Point; + + /** + * The distance from the queried point to the returned location. + * Read Only. + */ + distance: number; + + /** + * Checks whether tow CurveLocation objects are describing the same location on a path, by applying the same tolerances as elsewhere when dealing with curve time parameters. + * @param location CurveLocation + */ + equals(location: CurveLocation): boolean; + + /** + * Returns a string representation of the curve location + */ + toString(): string; + + } + /** + * A Project object in Paper.js is what usually is referred to as the document: The top level object that holds all the items contained in the scene graph. As the term document is already taken in the browser context, it is called Project. + * Projects allow the manipulation of the styles that are applied to all newly created items, give access to the selected items, and will in future versions offer ways to query for items in the scene graph defining specific requirements, and means to persist and load from different formats, such as SVG and PDF. + * The currently active project can be accessed through the paperScope.project variable. + * An array of all open projects is accessible through the paperScope.projects variable. + */ + export class Project { + + /** + * Creates a Paper.js project containing one empty Layer, referenced by project.activeLayer. + * @param element - the HTML canvas element that should be used as the element for the view, or an ID string by which to find the element. + */ + constructor(element: HTMLCanvasElement | string); + + /** + * The reference to the project's view. + * Read only. + */ + view: View; + + /** + * The currently active path style. All selected items and newly created items will be styled with this style. + */ + currentStyle: Style; + + /** + * The index of the project in the paperScope.projects list. + * Read Only + */ + index: number; + + /** + * The layers contained within the project. + */ + layers: Layer[]; + + /** + * The layer which is currently active. New items will be created on this layer by default. + * Read Only. + */ + activeLayer: Layer; + + /** + * The symbols contained within the project. + */ + symbols: Symbol[]; + + /** + * Activates this project, so all newly created items will be placed in it. + */ + activate(): void; + + /** + * Clears the project by removing all project.layers and project.symbols. + */ + clear(): void; + + /** + * Checks whether the project has any content or not. + */ + isEmpty(): boolean; + + /** + * Removes this project from the paperScope.projects list, and also removes its view, if one was defined. + */ + remove(): void; + + /** + * Selects all items in the project. + */ + selectAll(): void; + + /** + * Deselects all selected items in the project. + */ + deselectAll(): void; + + /** + * Perform a hit-test on the items contained within the project at the location of the specified point. + * The options object allows you to control the specifics of the hit-test and may contain a combination of the following values: + * @param point - the point where the hit-test should be performed + * @param options.tolerance -the tolerance of the hit-test in points. Can also be controlled through paperScope.settings.hitTolerance + * @param options.class - only hit-test again a certain item class and its sub-classes: Group, Layer, Path, CompoundPath, Shape, Raster, PlacedSymbol, PointText, etc. + * @param options.fill - hit-test the fill of items. + * @param options.stroke - hit-test the stroke of path items, taking into account the setting of stroke color and width. + * @param options.segments - hit-test for segment.point of Path items. + * @param options.curves - hit-test the curves of path items, without taking the stroke color or width into account. + * @param options.handles - hit-test for the handles. (segment.handleIn / segment.handleOut) of path segments. + * @param options.ends - only hit-test for the first or last segment points of open path items. + * @param options.bounds - hit-test the corners and side-centers of the bounding rectangle of items (item.bounds). + * @param options.center - hit-test the rectangle.center of the bounding rectangle of items (item.bounds). + * @param options.guides - hit-test items that have Item#guide set to true. + * @param options.selected - only hit selected items. + */ + hitTest(point: Point, options?: { tolerance?: number; class?: string; fill?: boolean; stroke?: boolean; segments?: boolean; curves?: boolean; handles?: boolean; ends?: boolean; bounds?: boolean; center?: boolean; guides?: boolean; selected?: boolean; }): HitResult; + + /** + * Fetch items contained within the project whose properties match the criteria in the specified object. + * Extended matching is possible by providing a compare function or regular expression. Matching points, colors only work as a comparison of the full object, not partial matching (e.g. only providing the x- coordinate to match all points with that x-value). Partial matching does work for item.data. + * Matching items against a rectangular area is also possible, by setting either match.inside or match.overlapping to a rectangle describing the area in which the items either have to be fully or partly contained. + */ + getItems(match: any): Item[]; + + /** + * Fetch the first item contained within the project whose properties match the criteria in the specified object. + * Extended matching is possible by providing a compare function or regular expression. Matching points, colors only work as a comparison of the full object, not partial matching (e.g. only providing the x- coordinate to match all points with that x-value). Partial matching does work for item.data. + */ + getItem(match: any): Item; + + /** + * Exports (serializes) the project with all its layers and child items to a JSON data string. + * @param options [optional] - default {asString: true, precision: 5} + * @param options.asString - whether the JSON is returned as a Object or a String. + * @param options.precision - the amount of fractional digits in numbers used in JSON data. + */ + exportJSON(options?: { asString?: boolean; precision?: number }): string; + + /** + * Imports (deserializes) the stored JSON data into the project. + * Note that the project is not cleared first. You can call project.clear() to do so. + */ + importJSON(json: string): void; + + /** + * Exports the project with all its layers and child items as an SVG DOM, all contained in one top level SVG group node. + * @param options [optional] the export options, default: { asString: false, precision: 5, matchShapes: false } + * @param options.asString - whether a SVG node or a String is to be returned. + * @param options.precision - the amount of fractional digits in numbers used in SVG data. + * @param options.matchShapes - whether path items should tried to be converted to shape items, if their geometries can be made to match + */ + exportSVG(options?: { asString?: boolean; precision?: number; matchShapes?: boolean }): SVGElement; + + /** + * Converts the provided SVG content into Paper.js items and adds them to the active layer of this project. + * Note that the project is not cleared first. You can call project.clear() to do so. + * @param svg - the SVG content to import + * @param options [optional] - the import options, default: { expandShapes: false } + * @param options.expandShapes - whether imported shape items should be expanded to path items. + */ + importSVG(svg: SVGElement | string, options?: any): Item; + + } + /** + * Symbols allow you to place multiple instances of an item in your project. This can save memory, since all instances of a symbol simply refer to the original item and it can speed up moving around complex objects, since internal properties such as segment lists and gradient positions don't need to be updated with every transformation. + */ + export class Symbol { + + /** + * Creates a Symbol item. + * @param item - the source item which is copied as the definition of the symbol + * @param dontCenter [optional] - default: false + */ + constructor(item: Item, dontCenter?: boolean); + + /** + * The project that this symbol belongs to. + * Read Only. + */ + project: Project; + + /** + * The symbol definition. + */ + definition: Item; + + /** + * Places in instance of the symbol in the project. + * @param position [optional] - The position of the placed symbol. + */ + place(position?: Point): PlacedSymbol; + + /** + * Returns a copy of the symbol. + */ + clone(): Symbol; + + } + /** + * Style is used for changing the visual styles of items contained within a Paper.js project and is returned by item.style and project.currentStyle. + * All properties of Style are also reflected directly in Item, i.e.: item.fillColor. + * To set multiple style properties in one go, you can pass an object to item.style. This is a convenient way to define a style once and apply it to a series of items: + */ + export class Style { + + /** + * The view that this style belongs to. + * Read only. + */ + view: View; + + /** + * The color of the stroke. + */ + strokeColor: Color | string; + + /** + * The width of the stroke. + */ + strokeWidth: number; + + /** + * The shape to be used at the beginning and end of open Path items, when they have a stroke. + * String('round', 'square', 'butt' + */ + strokeCap: string; + + /** + * The shape to be used at the segments and corners of Path items when they have a stroke. + * String('miter', 'round', 'bevel') + */ + strokeJoin: string; + + /** + * Specifies whether the stroke is to be drawn taking the current affine transformation into account (the default behavior), or whether it should appear as a non-scaling stroke. + */ + strokeScaling: boolean; + + /** + * The dash offset of the stroke. + */ + dashOffset: number; + + /** + * Specifies an array containing the dash and gap lengths of the stroke. + */ + dashArray: number[]; + + /** + * The miter limit of the stroke. When two line segments meet at a sharp angle and miter joins have been specified for strokeJoin, it is possible for the miter to extend far beyond the strokeWidth of the path. The miterLimit imposes a limit on the ratio of the miter length to the strokeWidth. + */ + miterLimit: number; + + /** + * The fill color. + */ + fillColor: Color | string; + + /** + * The shadow color. + */ + shadowColor: Color | string; + + /** + * The shadow's blur radius. + */ + shadowBlur: number; + + /** + * The shadow's offset. + */ + shadowOffset: Point; + + /** + * The color the item is highlighted with when selected. If the item does not specify its own color, the color defined by its layer is used instead. + */ + selectedColor: Color | string; + + /** + * The font-family to be used in text content. default 'sans-serif' + */ + fontFamily: string; + + /** + * The font-weight to be used in text content. + */ + fontWeight: string | number; + + /** + * The font size of text content, as {@Number} in pixels, or as {@String} with optional units 'px', 'pt' and 'em'. + */ + fontSize: string | number; + + /** + * The text leading of text content. + */ + leading: number | string; + + /** + * The justification of text paragraphs. default "left" + */ + justification: string; + + } + export interface IHSBColor { + + /** + * the hue of the color as a value in degrees between 0 and 360 + */ + hue?: number; + /** + * the saturation of the color as a value between 0 and 1 + */ + saturation?: number; + /** + * the brightness of the color as a value between 0 and 1 + */ + brightness?: number; + /** + * the alpha of the color as a value between 0 and 1 + */ + alpha?: number; + + } + export interface IHSLColor { + + /** + * the hue of the color as a value in degrees between 0 and 360 + */ + hue?: number; + /** + * the saturation of the color as a value between 0 and 1 + */ + saturation?: number; + /** + * the brightness of the color as a value between 0 and 1 + */ + lightness?: number; + /** + * the alpha of the color as a value between 0 and 1 + */ + alpha?: number; + + } + export interface IGradientColor { + /** + * the gradient object that describes the color stops and type of gradient to be used. + */ + gradient?: Gradient; + /** + * the origin point of the gradient + */ + origin?: Point; + /** + * the destination point of the gradient stops: Array of GradientStop - the gradient stops describing the gradient, as an alternative to providing a gradient object + */ + destination?: Point; + /** + * controls whether the gradient is radial, as an alternative to providing a gradient object + */ + radial?: boolean; + } + /** + * All properties and functions that expect color values in the form of instances of Color objects, also accept named colors and hex values as strings which are then converted to instances of Color internally. + */ + export class Color { + + /** + * Creates a RGB Color object. + * @param red - the amount of red in the color as a value between 0 and 1 + * @param green - the amount of green in the color as a value between 0 and 1 + * @param blue - the amount of blue in the color as a value between 0 and 1 + * @param alpha [optional] - the alpha of the color as a value between 0 and 1 + */ + constructor(red: number, green: number, blue: number, alpha?: number); + + /** + * Creates a gray Color object. + * @param gray - the amount of gray in the color as a value between 0 and 1 + * @param alpha [optional] - the alpha of the color as a value between 0 and 1 + */ + constructor(gray: number, alpha?: number); + + /** + * Creates a HSB, HSL or gradient Color object from the properties of the provided object: + * @param object - an object describing the components and properties of the color. + */ + constructor(object: IHSBColor | IHSLColor | IGradientColor); + + /** + * Creates a gradient Color object. + * @param gradient - + * @param origin - + * @param destination - + * @param highlight [optional] - + */ + constructor(color: Gradient, origin: Point, destination: Point, highlight?: Point); + + /** + * The type of the color as a string. + * String('rgb', 'gray', 'hsb', 'hsl') + */ + type: string; + + /** + * The color components that define the color, including the alpha value if defined. + * Read Only. + */ + components: number; + + /** + * The color's alpha value as a number between 0 and 1. + * All colors of the different subclasses support alpha values. + */ + alpha: number; + + /** + * The amount of red in the color as a value between 0 and 1. + */ + red: number; + + /** + * The amount of green in the color as a value between 0 and 1. + */ + green: number; + + /** + * The amount of blue in the color as a value between 0 and 1. + */ + blue: number; + + /** + * The amount of gray in the color as a value between 0 and 1. + */ + gray: number; + + /** + * The hue of the color as a value in degrees between 0 and 360. + */ + hue: number; + + /** + * The saturation of the color as a value between 0 and 1. + */ + saturation: number; + + /** + * The brightness of the color as a value between 0 and 1. + */ + brightness: number; + + /** + * The lightness of the color as a value between 0 and 1. + * Note that all other components are shared with HSB. + */ + lightness: number; + + /** + * The gradient object describing the type of gradient and the stops. + */ + gradient: Gradient; + + /** + * The highlight point of the gradient. + */ + highlight: Point; + + /** + * Converts the color another type. + * @param type - String('rgb'|'gray'|'hsb'|'hsl') the color type to convert to. + */ + convert(type: string): Color; + + /** + * Checks if the color has an alpha value. + */ + hasAlpha(): boolean; + + /** + * Checks if the component color values of the color are the same as those of the supplied one. + * @param color - the color to compare with + */ + equals(color: Color): boolean; + + /** + * a copy of the color object + */ + clone(): Color; + + /** + * a string representation of the color + */ + toString(): string; + + /** + * Returns the color as a CSS string. + * @param hex - whether to return the color in hexadecial representation or as a CSS RGB / RGBA string. + */ + toCSS(hex: boolean): string; + + /** + * Transform the gradient color by the specified matrix. + * @param matrix - the matrix to transform the gradient color by + */ + transform(matrix: Matrix): void; + + } + /** + * The Gradient object. + */ + export class Gradient { + + /** + * The gradient stops on the gradient ramp. + */ + stops: GradientStop[]; + + /** + * Specifies whether the gradient is radial or linear. + */ + radial: boolean; + + /** + * a copy of the gradient + */ + clone(): Gradient; + + /** + * Checks whether the gradient is equal to the supplied gradient. + * @param gradient - the gradient to check against + */ + equals(gradient: Gradient): boolean; + + } + /** + * The GradientStop object. + */ + export class GradientStop { + + /** + * Creates a GradientStop object. + * @param color [optional] - the color of the stop, default: new Color(0, 0, 0) + * @param rampPoint [optional] - the position of the stop on the gradient ramp as a value between 0 and 1, default: 0 + */ + constructor(color?: Color, rampPoint?: number); + + /** + * The ramp-point of the gradient stop as a value between 0 and 1. + */ + rampPoint: number; + + /** + * The color of the gradient stop. + */ + color: Color; + + /** + * Returns a copy of the gradient-stop + */ + clone(): GradientStop; + + } + /** + * The View object wraps an HTML element and handles drawing and user interaction through mouse and keyboard for it. It offer means to scroll the view, find the currently visible bounds in project coordinates, or the center, both useful for constructing artwork that should appear centered on screen. + */ + export class View { + + /** + * The underlying native element. + * Read Only. + */ + element: HTMLCanvasElement; + + /** + * The ratio between physical pixels and device-independent pixels (DIPs) of the underlying canvas / device. + * It is 1 for normal displays, and 2 or more for high-resolution displays. + * Read only. + */ + pixelRatio: number; + + /** + * The resoltuion of the underlying canvas / device in pixel per inch (DPI). + * It is 72 for normal displays, and 144 for high-resolution displays with a pixel-ratio of 2. + * Read only. + */ + resolution: number; + + /** + * The size of the view. Changing the view's size will resize it's underlying element. + */ + viewSize: Size; + + /** + * The bounds of the currently visible area in project coordinates. + * Read only. + */ + bounds: Rectangle; + + /** + * The size of the visible area in project coordinates. + * Read only. + */ + size: Size; + + /** + * The center of the visible area in project coordinates. + */ + center: Point; + + /** + * The zoom factor by which the project coordinates are magnified. + */ + zoom: number; + + /** + * Handler function to be called on each frame of an animation. + * The function receives an event object which contains information about the frame event: + */ + onFrame: (event: IFrameEvent) => void; + + /** + * Handler function that is called whenever a view is resized. + */ + onResize: (event: Event) => void; + + /** + * Removes this view from the project and frees the associated element. + */ + remove(): void; + + /** + * Checks whether the view is currently visible within the current browser viewport. + */ + isVisible(): boolean; + + /** + * Scrolls the view by the given vector. + * @param point - the vector to scroll by + */ + scrollBy(point: Point): void; + + /** + * Makes all animation play by adding the view to the request animation loop. + */ + play(): void; + + /** + * Makes all animation pause by removing the view to the request animation loop. + */ + pause(): void; + + /** + * Updates the view if there are changes. Note that when using built-in event hanlders for interaction, animation and load events, this method is invoked for you automatically at the end. + */ + update(): void; + + /** + * + * @param point - + */ + projectToView(point: Point): Point; + + /** + * + * @param point - + */ + viewToProject(point: Point): Point; + + //I cannot use function: Function as it is a reserved keyword + + /** + * Attach an event handler to the view. + * @param type - String('frame'|'resize') the event type + * @param function - The function to be called when the event occurs + */ + on(type: string, callback: (event: Event) => void): Item; + + /** + * Attach one or more event handlers to the view. + */ + on(param: any): Item; + + /** + * Detach an event handler from the view. + * @param type - String('frame'|'resize') the event type + * @param function - The function to be detached + */ + off(type: string, callback: (event: Event) => void): Item; + + /** + * Detach one or more event handlers from the view. + * @param param - an object literal containing one or more of the following properties: frame, resize + */ + off(param: any): Item; + + /** + * Emit an event on the view. + * @param type - String('frame'|'resize') the event type + * @param event - an object literal containing properties describing the event. + */ + emit(type: string, event: any): boolean; + + /** + * Check if the view has one or more event handlers of the specified type. + * @param type - String('frame'|'resize') the event type + */ + responds(type: string): boolean; + + /** + * Draws the view when using paper.js directly in JavaScript + */ + draw(): void; + + } + /** + * The Tool object refers to a script that the user can interact with by using the mouse and keyboard and can be accessed through the global tool variable. All its properties are also available in the paper scope. + * The global tool variable only exists in scripts that contain mouse handler functions (onMouseMove, onMouseDown, onMouseDrag, onMouseUp) or a keyboard handler function (onKeyDown, onKeyUp). + */ + export class Tool { + + /** + * The minimum distance the mouse has to drag before firing the onMouseDrag event, since the last onMouseDrag event. + */ + minDistance: number; + + /** + * The maximum distance the mouse has to drag before firing the onMouseDrag event, since the last onMouseDrag event. + */ + maxDistance: number; + + /** + * + */ + fixedDistance: number; + + /** + * The function to be called when the mouse button is pushed down. The function receives a ToolEvent object which contains information about the mouse event. + */ + onMouseDown: (event: ToolEvent) => void; + + /** + * The function to be called when the mouse position changes while the mouse is being dragged. The function receives a ToolEvent object which contains information about the mouse event. + */ + onMouseDrag: (event: ToolEvent) => void; + + /** + * The function to be called the mouse moves within the project view. The function receives a ToolEvent object which contains information about the mouse event. + */ + onMouseMove: (event: ToolEvent) => void; + + /** + * The function to be called when the mouse button is released. The function receives a ToolEvent object which contains information about the mouse event. + */ + onMouseUp: (event: ToolEvent) => void; + + /** + * The function to be called when the user presses a key on the keyboard. + * The function receives a KeyEvent object which contains information about the keyboard event. + * If the function returns false, the keyboard event will be prevented from bubbling up. This can be used for example to stop the window from scrolling, when you need the user to interact with arrow keys. + */ + onKeyDown: (event: KeyEvent) => void; + + /** + * The function to be called when the user releases a key on the keyboard. + * The function receives a KeyEvent object which contains information about the keyboard event. + * If the function returns false, the keyboard event will be prevented from bubbling up. This can be used for example to stop the window from scrolling, when you need the user to interact with arrow keys. + */ + onKeyUp: (event: KeyEvent) => void; + + /** + * Activates this tool, meaning paperScope.tool will point to it and it will be the one that recieves mouse events. + */ + activate(): void; + + /** + * Removes this tool from the paperScope.tools list. + */ + remove(): void; + + //I cannot use function: Function as it is a reserved keyword + + /** + * Attach an event handler to the tool. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param function - The function to be called when the event occurs + */ + on(type: string, callback: (event: ToolEvent) => void): Tool; + + /** + * Attach one or more event handlers to the tool. + * @param param - an object literal containing one or more of the following properties: mousedown, mouseup, mousedrag, mousemove, keydown, keyup + */ + on(param: any): Tool; + + /** + * Detach an event handler from the tool. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param function - The function to be detached + */ + off(type: string, callback: (event: ToolEvent) => void): Tool; + + /** + * Detach one or more event handlers from the tool. + * @param param - an object literal containing one or more of the following properties: mousedown, mouseup, mousedrag, mousemove, keydown, keyup + */ + off(param: any): Tool; + + /** + * Emit an event on the tool. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + * @param event - an object literal containing properties describing the event. + */ + emit(type: string, event: any): boolean; + + /** + * Check if the tool has one or more event handlers of the specified type. + * @param type - String('mousedown'|'mouseup'|'mousedrag'|'mousemove'|'keydown'|'keyup') the event type + */ + responds(type: string): boolean; + + } + export class Event { + + /** + * Read Only + */ + modifiers: any; + + } + /** + * ToolEvent The ToolEvent object is received by the Tool's mouse event handlers tool.onMouseDown, tool.onMouseDrag, tool.onMouseMove and tool.onMouseUp. The ToolEvent object is the only parameter passed to these functions and contains information about the mouse event. + */ + export class ToolEvent extends Event { + + /** + * The type of tool event. + * String('mousedown', 'mouseup', 'mousemove', 'mousedrag') + */ + type: string; + + /** + * The position of the mouse in project coordinates when the event was fired. + */ + point: Point; + + /** + * The position of the mouse in project coordinates when the previous event was fired. + */ + lastPoint: Point; + + /** + * The position of the mouse in project coordinates when the mouse button was last clicked. + */ + downPoint: Point; + + /** + * The point in the middle between lastPoint and point. This is a useful position to use when creating artwork based on the moving direction of the mouse, as returned by delta. + */ + middlePoint: Point; + + /** + * The difference between the current position and the last position of the mouse when the event was fired. In case of the mouseup event, the difference to the mousedown position is returned. + */ + delta: Point; + + /** + * The number of times the mouse event was fired. + */ + count: number; + + /** + * The item at the position of the mouse (if any). If the item is contained within one or more Group or CompoundPath items, the most top level group or compound path that it is contained within is returned. + */ + item: Item; + + /** + * a string representation of the tool event + */ + toString(): string; + + } + export class Key { + + /** + * Checks whether the specified key is pressed. + * @param key - One of: 'backspace', 'enter', 'shift', 'control', 'option', 'pause', 'caps-lock', 'escape', 'space', 'end', 'home', 'left', 'up', 'right', 'down', 'delete', 'command' + */ + static isDown(key: string): boolean; + + } + /** + * The KeyEvent object is received by the Tool's keyboard handlers tool.onKeyDown, tool.onKeyUp. The KeyEvent object is the only parameter passed to these functions and contains information about the keyboard event. + */ + export class KeyEvent extends Event { + + /** + * The type of key event. + * String('keydown', 'keyup') + */ + type: string; + + /** + * The string character of the key that caused this key event. + */ + character: string; + + /** + * The key that caused this key event. + */ + key: string; + + /** + * a string representation of the key event + */ + toString(): string; + + } + /** + * The TextItem type allows you to create typography. Its functionality is inherited by different text item types such as PointText, and AreaText (coming soon). They each add a layer of functionality that is unique to their type, but share the underlying properties and functions that they inherit from TextItem. + */ + export class TextItem extends Item { + + /** + * The text contents of the text item. + */ + content: string; + + /** + * The font-family to be used in text content. + */ + fontFamily: string; + + /** + * The font-weight to be used in text content. + */ + fontWeight: string | number; + + /** + * The font size of text content, as {@Number} in pixels, or as {@String} with optional units 'px', 'pt' and 'em'. + */ + fontSize: string | number; + + /** + * The text leading of text content. + */ + leading: string | number; + + /** + * The justification of text paragraphs. + * String('left', 'right', 'center') + */ + justification: string; + + } + /** + * A PointText item represents a piece of typography in your Paper.js project which starts from a certain point and extends by the amount of characters contained in it. + */ + export class PointText extends TextItem { + + /** + * Creates a point text item + * @param point - the position where the text will start + */ + constructor(point: Point); + + /** + * Creates a point text item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + constructor(object: any); + + /** + * The PointText's anchor point + */ + point: Point; + + } + +} From fee5da4cdccf6fc0abbbd0859be3c1713cbd9053 Mon Sep 17 00:00:00 2001 From: sqwk Date: Thu, 18 Aug 2016 11:52:56 +0200 Subject: [PATCH 002/554] Fix Header --- paper/paper.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/paper/paper.d.ts b/paper/paper.d.ts index 9fc0c154a1..daf7e56827 100644 --- a/paper/paper.d.ts +++ b/paper/paper.d.ts @@ -1,7 +1,7 @@ // Type definitions for Paper.js v0.9.22 // Project: http://paperjs.org/ // Definitions by: Clark Stevenson -// forked from https://github.com/clark-stevenson/paper.d.ts +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'paper' { From 044bac98a20880c27be9dba1eff863a1b5fde482 Mon Sep 17 00:00:00 2001 From: sqwk Date: Thu, 18 Aug 2016 11:53:09 +0200 Subject: [PATCH 003/554] Add Provisional Tests File --- paper/paper-tests.ts | 1 + 1 file changed, 1 insertion(+) create mode 100644 paper/paper-tests.ts diff --git a/paper/paper-tests.ts b/paper/paper-tests.ts new file mode 100644 index 0000000000..8e011255a2 --- /dev/null +++ b/paper/paper-tests.ts @@ -0,0 +1 @@ +/// From b09a00f0229752958811e43cceeab60721aaabc6 Mon Sep 17 00:00:00 2001 From: sqwk Date: Thu, 18 Aug 2016 11:58:03 +0200 Subject: [PATCH 004/554] Remove Space --- paper/paper.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/paper/paper.d.ts b/paper/paper.d.ts index daf7e56827..e463d730c0 100644 --- a/paper/paper.d.ts +++ b/paper/paper.d.ts @@ -1,6 +1,6 @@ // Type definitions for Paper.js v0.9.22 // Project: http://paperjs.org/ -// Definitions by: Clark Stevenson +// Definitions by: Clark Stevenson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'paper' { From bef3b8072e56bc74e4619336e0a5f9a99a399844 Mon Sep 17 00:00:00 2001 From: Boriss Nazarovs Date: Sat, 27 Aug 2016 19:00:50 +0300 Subject: [PATCH 005/554] Added type definition for eventemitter3-1.2.0 --- eventemitter3/eventemitter3-1.2.0-tests.ts | 113 ++++++++++++++++++ .../eventemitter3-1.2.0-tests.ts.tscparams | 1 + eventemitter3/eventemitter3-1.2.0.d.ts | 107 +++++++++++++++++ 3 files changed, 221 insertions(+) create mode 100644 eventemitter3/eventemitter3-1.2.0-tests.ts create mode 100644 eventemitter3/eventemitter3-1.2.0-tests.ts.tscparams create mode 100644 eventemitter3/eventemitter3-1.2.0.d.ts diff --git a/eventemitter3/eventemitter3-1.2.0-tests.ts b/eventemitter3/eventemitter3-1.2.0-tests.ts new file mode 100644 index 0000000000..517b8afd72 --- /dev/null +++ b/eventemitter3/eventemitter3-1.2.0-tests.ts @@ -0,0 +1,113 @@ +/// +'use strict'; + +import EventEmitter from 'eventemitter3'; + +const eventName = 'test'; +const eventSymbol: symbol = Symbol('test'); +const fn = () => console.log(1); + +// Extending EventEmitter +class TestEmitter extends EventEmitter { + constructor() { + super(); + } +} + +const ee: TestEmitter = new TestEmitter(); + +// EventEmitter.prefixed +// should be boolean or string static property +const prefix = EventEmitter.prefixed; +if (typeof prefix === 'boolean') { + console.log(prefix.valueOf()); +} else { + console.log(prefix.length); +} + +// EventEmitter.eventNames() +// should return array of strings or symbols +ee.eventNames().every((event) => { + if (typeof event === 'symbol') { + return false; + } else { + return event.length > 0; + } +}); + +// EventEmitter.listeners() +// should return array of functions +ee.listeners(eventName).map((listener) => { + return listener.bind(this); +}); +// should accept symbol as event name +ee.listeners(eventSymbol).map((listener) => { + return listener.bind(this); +}); +// should return boolean with 'exists' flag +const hasListeners: boolean = ee.listeners(eventName, true); + +// EventEmitter.emit() +// should support any number of arguments +ee.emit(eventName, 1, true, {}, [], 'test', Symbol(), null); +// should accept symbol as event name +ee.emit(eventSymbol); + +// EventEmitter.addListener() and EventEmitter.on() +// should accept function +ee.on(eventName, fn); +ee.addListener(eventName, fn); +// should accept optional context argument +ee.on(eventName, fn, this); +ee.addListener(eventName, fn, this); +// should accept symbol as event name +ee.on(eventSymbol, fn); +ee.addListener(eventSymbol, fn); +// should support fluent interface +ee.on(eventSymbol, fn).on(eventName, fn); +ee.addListener(eventSymbol, fn).addListener(eventName, fn); + +// EventEmitter.once() +// should accept event name and function +ee.once(eventName, fn); +// should accept optional context argument +ee.once(eventName, fn, this); +ee.once(eventName, fn, {}); +// should accept symbol as event name +ee.once(eventSymbol, fn); +// should support fluent interface +ee.once(eventSymbol, fn).once(eventName, fn); + +// EventEmitter.removeListener() and EventEmitter.off() +// should accept event name +ee.removeListener(eventName); +ee.off(eventName); +// should accept optional function +ee.removeListener(eventName, fn); +ee.off(eventName, fn); +// should accept optional context argument +ee.removeListener(eventName, fn, {}); +ee.off(eventName, fn, {}); +// should accept optional boolean flag for removing listeners added with `EventEmitter.once()` +ee.removeListener(eventName, fn, null, true); +ee.off(eventName, fn, null, true); +// should accept symbol as event name +ee.removeListener(eventSymbol); +ee.off(eventSymbol); +// should support fluent interface +ee.removeListener(eventName).removeListener(eventSymbol); +ee.off(eventName).off(eventSymbol); + +// EventEmitter.removeAllListeners() +// should not require any arguments +ee.removeAllListeners(); +// should accept optional event name +ee.removeAllListeners(eventName); +// should accept symbol as event name +ee.removeAllListeners(eventSymbol); +// should support fluent interface +ee.removeAllListeners(eventName).removeAllListeners(eventSymbol); + +// EventEmitter.setMaxListeners() +// should support fluent interface +ee.setMaxListeners().setMaxListeners(); diff --git a/eventemitter3/eventemitter3-1.2.0-tests.ts.tscparams b/eventemitter3/eventemitter3-1.2.0-tests.ts.tscparams new file mode 100644 index 0000000000..a0aefcf79a --- /dev/null +++ b/eventemitter3/eventemitter3-1.2.0-tests.ts.tscparams @@ -0,0 +1 @@ +--target es6 --allowSyntheticDefaultImports --noImplicitAny diff --git a/eventemitter3/eventemitter3-1.2.0.d.ts b/eventemitter3/eventemitter3-1.2.0.d.ts new file mode 100644 index 0000000000..ca43aa6c95 --- /dev/null +++ b/eventemitter3/eventemitter3-1.2.0.d.ts @@ -0,0 +1,107 @@ +// Type definitions for EventEmitter3 1.2.0 +// Project: https://github.com/primus/eventemitter3 +// Definitions by: Boriss Nazarovs +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'eventemitter3' { + /** + * Minimal EventEmitter interface that is molded against the Node.js + * EventEmitter interface. + */ + class EventEmitter { + constructor(); + + /** + * Return an array listing the events for which the emitter has registered listeners. + * + * @returns {(string|symbol)[]} + */ + eventNames(): (string|symbol)[]; + + /** + * Return the listeners registered for a given event. + * + * @param {(string|symbol)} event The event name. + * @returns {Function[]} + */ + listeners(event: string|symbol): Function[]; + + /** + * Check if there listeners for a given event. + * If `exists` argument is not `true` lists listeners. + * + * @param {(string|symbol)} event The event name. + * @param {boolean} exists Only check if there are listeners. + * @returns {boolean} + */ + listeners(event: string|symbol, exists: boolean): boolean; + + /** + * Calls each of the listeners registered for a given event. + * + * @param {(string|symbol)} event The event name. + * @param {...*} args Arguments that are passed to registered listeners + * @returns {boolean} `true` if the event had listeners, else `false`. + */ + emit(event: string|symbol, ...args: any[]): boolean; + + /** + * Add a listener for a given event. + * + * @param {(string|symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + */ + on(event: string|symbol, fn: Function, context?: any): EventEmitter; + + /** + * Add a one-time listener for a given event. + * + * @param {(string|symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + */ + once(event: string|symbol, fn: Function, context?: any): EventEmitter; + + /** + * Remove the listeners of a given event. + * + * @param {(string|symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + */ + removeListener(event: string|symbol, fn?: Function, context?: any, once?: boolean): EventEmitter; + + /** + * Remove all listeners, or those of the specified event. + * + * @param {(string|symbol)} event The event name. + * @returns {EventEmitter} `this`. + */ + removeAllListeners(event?: string|symbol): EventEmitter; + + /** + * Alias method for `removeListener` + */ + off(event: string|symbol, fn?: Function, context?: any, once?: boolean): EventEmitter; + + /** + * Alias method for `on` + */ + addListener(event: string|symbol, fn: Function, context?: any): EventEmitter; + + /** + * This function doesn't apply anymore. + * @deprecated + */ + setMaxListeners(): EventEmitter; + + static prefixed: string|boolean; + } + + export = EventEmitter; +} From 6ed248d516f1c83b05806be67ece4853b69be792 Mon Sep 17 00:00:00 2001 From: Boriss Nazarovs Date: Thu, 1 Sep 2016 23:52:01 +0300 Subject: [PATCH 006/554] Merged eventemitter3-1.2.0 typings with main typing file --- eventemitter3/eventemitter3-1.2.0-tests.ts | 113 --- eventemitter3/eventemitter3-1.2.0.d.ts | 107 --- eventemitter3/eventemitter3-tests.ts | 673 +++--------------- ...arams => eventemitter3-tests.ts.tscparams} | 0 eventemitter3/eventemitter3.d.ts | 128 ++-- 5 files changed, 157 insertions(+), 864 deletions(-) delete mode 100644 eventemitter3/eventemitter3-1.2.0-tests.ts delete mode 100644 eventemitter3/eventemitter3-1.2.0.d.ts rename eventemitter3/{eventemitter3-1.2.0-tests.ts.tscparams => eventemitter3-tests.ts.tscparams} (100%) diff --git a/eventemitter3/eventemitter3-1.2.0-tests.ts b/eventemitter3/eventemitter3-1.2.0-tests.ts deleted file mode 100644 index 517b8afd72..0000000000 --- a/eventemitter3/eventemitter3-1.2.0-tests.ts +++ /dev/null @@ -1,113 +0,0 @@ -/// -'use strict'; - -import EventEmitter from 'eventemitter3'; - -const eventName = 'test'; -const eventSymbol: symbol = Symbol('test'); -const fn = () => console.log(1); - -// Extending EventEmitter -class TestEmitter extends EventEmitter { - constructor() { - super(); - } -} - -const ee: TestEmitter = new TestEmitter(); - -// EventEmitter.prefixed -// should be boolean or string static property -const prefix = EventEmitter.prefixed; -if (typeof prefix === 'boolean') { - console.log(prefix.valueOf()); -} else { - console.log(prefix.length); -} - -// EventEmitter.eventNames() -// should return array of strings or symbols -ee.eventNames().every((event) => { - if (typeof event === 'symbol') { - return false; - } else { - return event.length > 0; - } -}); - -// EventEmitter.listeners() -// should return array of functions -ee.listeners(eventName).map((listener) => { - return listener.bind(this); -}); -// should accept symbol as event name -ee.listeners(eventSymbol).map((listener) => { - return listener.bind(this); -}); -// should return boolean with 'exists' flag -const hasListeners: boolean = ee.listeners(eventName, true); - -// EventEmitter.emit() -// should support any number of arguments -ee.emit(eventName, 1, true, {}, [], 'test', Symbol(), null); -// should accept symbol as event name -ee.emit(eventSymbol); - -// EventEmitter.addListener() and EventEmitter.on() -// should accept function -ee.on(eventName, fn); -ee.addListener(eventName, fn); -// should accept optional context argument -ee.on(eventName, fn, this); -ee.addListener(eventName, fn, this); -// should accept symbol as event name -ee.on(eventSymbol, fn); -ee.addListener(eventSymbol, fn); -// should support fluent interface -ee.on(eventSymbol, fn).on(eventName, fn); -ee.addListener(eventSymbol, fn).addListener(eventName, fn); - -// EventEmitter.once() -// should accept event name and function -ee.once(eventName, fn); -// should accept optional context argument -ee.once(eventName, fn, this); -ee.once(eventName, fn, {}); -// should accept symbol as event name -ee.once(eventSymbol, fn); -// should support fluent interface -ee.once(eventSymbol, fn).once(eventName, fn); - -// EventEmitter.removeListener() and EventEmitter.off() -// should accept event name -ee.removeListener(eventName); -ee.off(eventName); -// should accept optional function -ee.removeListener(eventName, fn); -ee.off(eventName, fn); -// should accept optional context argument -ee.removeListener(eventName, fn, {}); -ee.off(eventName, fn, {}); -// should accept optional boolean flag for removing listeners added with `EventEmitter.once()` -ee.removeListener(eventName, fn, null, true); -ee.off(eventName, fn, null, true); -// should accept symbol as event name -ee.removeListener(eventSymbol); -ee.off(eventSymbol); -// should support fluent interface -ee.removeListener(eventName).removeListener(eventSymbol); -ee.off(eventName).off(eventSymbol); - -// EventEmitter.removeAllListeners() -// should not require any arguments -ee.removeAllListeners(); -// should accept optional event name -ee.removeAllListeners(eventName); -// should accept symbol as event name -ee.removeAllListeners(eventSymbol); -// should support fluent interface -ee.removeAllListeners(eventName).removeAllListeners(eventSymbol); - -// EventEmitter.setMaxListeners() -// should support fluent interface -ee.setMaxListeners().setMaxListeners(); diff --git a/eventemitter3/eventemitter3-1.2.0.d.ts b/eventemitter3/eventemitter3-1.2.0.d.ts deleted file mode 100644 index ca43aa6c95..0000000000 --- a/eventemitter3/eventemitter3-1.2.0.d.ts +++ /dev/null @@ -1,107 +0,0 @@ -// Type definitions for EventEmitter3 1.2.0 -// Project: https://github.com/primus/eventemitter3 -// Definitions by: Boriss Nazarovs -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module 'eventemitter3' { - /** - * Minimal EventEmitter interface that is molded against the Node.js - * EventEmitter interface. - */ - class EventEmitter { - constructor(); - - /** - * Return an array listing the events for which the emitter has registered listeners. - * - * @returns {(string|symbol)[]} - */ - eventNames(): (string|symbol)[]; - - /** - * Return the listeners registered for a given event. - * - * @param {(string|symbol)} event The event name. - * @returns {Function[]} - */ - listeners(event: string|symbol): Function[]; - - /** - * Check if there listeners for a given event. - * If `exists` argument is not `true` lists listeners. - * - * @param {(string|symbol)} event The event name. - * @param {boolean} exists Only check if there are listeners. - * @returns {boolean} - */ - listeners(event: string|symbol, exists: boolean): boolean; - - /** - * Calls each of the listeners registered for a given event. - * - * @param {(string|symbol)} event The event name. - * @param {...*} args Arguments that are passed to registered listeners - * @returns {boolean} `true` if the event had listeners, else `false`. - */ - emit(event: string|symbol, ...args: any[]): boolean; - - /** - * Add a listener for a given event. - * - * @param {(string|symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - */ - on(event: string|symbol, fn: Function, context?: any): EventEmitter; - - /** - * Add a one-time listener for a given event. - * - * @param {(string|symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - */ - once(event: string|symbol, fn: Function, context?: any): EventEmitter; - - /** - * Remove the listeners of a given event. - * - * @param {(string|symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - */ - removeListener(event: string|symbol, fn?: Function, context?: any, once?: boolean): EventEmitter; - - /** - * Remove all listeners, or those of the specified event. - * - * @param {(string|symbol)} event The event name. - * @returns {EventEmitter} `this`. - */ - removeAllListeners(event?: string|symbol): EventEmitter; - - /** - * Alias method for `removeListener` - */ - off(event: string|symbol, fn?: Function, context?: any, once?: boolean): EventEmitter; - - /** - * Alias method for `on` - */ - addListener(event: string|symbol, fn: Function, context?: any): EventEmitter; - - /** - * This function doesn't apply anymore. - * @deprecated - */ - setMaxListeners(): EventEmitter; - - static prefixed: string|boolean; - } - - export = EventEmitter; -} diff --git a/eventemitter3/eventemitter3-tests.ts b/eventemitter3/eventemitter3-tests.ts index 6c5733bec7..895dc7f54b 100644 --- a/eventemitter3/eventemitter3-tests.ts +++ b/eventemitter3/eventemitter3-tests.ts @@ -1,586 +1,113 @@ /// -/// -/// 'use strict'; -import EventEmitter = require('eventemitter3'); -import util = require('util'); -import * as EventEmitter3ImportedAsES6Module from 'eventemitter3'; +import EventEmitter from 'eventemitter3'; -declare namespace Assume { - interface Class { - new(...args: any[]): T; - } - - interface Assume { - equals(compare: T): Assume; - equal(compare: T): Assume; - eqls(compare: T): Assume; - is: Assume; - deep: Assume; - to: Assume; - either(arr: T[]): Assume; - instanceOf(clazz: Class): Assume; - a(typeofString: string): Assume; - } - - export function assume(input: T): Assume; -} - -let assume = Assume.assume; - -class EventEmitterTest { - v: EventEmitter3.EventEmitter; +const eventName = 'test'; +const eventSymbol: symbol = Symbol('test'); +const fn = () => console.log(1); +// Extending EventEmitter +class TestEmitter extends EventEmitter { constructor() { - this.v = new EventEmitter(); - this.v = new EventEmitter3ImportedAsES6Module(); - - // Some methods are missing or incompatible with current implementation (v4.2.x) of NodeJS.EventEmitter - // (e.g. getMaxListenters or listeners) - // var n: NodeJS.EventEmitter = this.v; - } - - listeners() { - var v1: Function[] = this.v.listeners('click'); - } - - emit() { - var v1: boolean = this.v.emit('click'); - var v2: boolean = this.v.emit('click', 1); - var v3: boolean = this.v.emit('click', 1, '1'); - var v4: boolean = this.v.emit('click', 1, '1', true); - var v5: boolean = this.v.emit('click', 1, '1', true, new Date()); - } - - on() { - var fn = () => console.log(1); - var v1: EventEmitter3.EventEmitter = this.v.on('click', fn); - var v2: EventEmitter3.EventEmitter = this.v.on('click', fn, this); - } - - once() { - var fn = () => console.log(1); - var v1: EventEmitter3.EventEmitter = this.v.once('click', fn); - var v2: EventEmitter3.EventEmitter = this.v.once('click', fn, this); - } - - removeListener() { - var fn = () => console.log(1); - var v1: EventEmitter3.EventEmitter = this.v.removeListener('click', fn); - var v2: EventEmitter3.EventEmitter = this.v.removeListener('click', fn, true); - } - - removeAllListeners() { - var v1: EventEmitter3.EventEmitter = this.v.removeAllListeners('click'); - } - - off() { - var fn = () => console.log(1); - var v1: EventEmitter3.EventEmitter = this.v.off('click', fn); - var v2: EventEmitter3.EventEmitter = this.v.off('click', fn, true); - } - - addListener() { - var fn = () => console.log(1); - var v1: EventEmitter3.EventEmitter = this.v.addListener('click', fn); - var v2: EventEmitter3.EventEmitter = this.v.addListener('click', fn, this); - } - - setMaxListeners() { - var v1: EventEmitter3.EventEmitter = this.v.setMaxListeners(); + super(); } } +const ee: TestEmitter = new TestEmitter(); -describe('EventEmitter', function tests() { - 'use strict'; +// EventEmitter.prefixed +// should be boolean or string static property +const prefix = EventEmitter.prefixed; +if (typeof prefix === 'boolean') { + console.log(prefix.valueOf()); +} else { + console.log(prefix.length); +} - it('exposes a `prefixed` property', function () { - assume(EventEmitter.prefixed).is.either([false, '~']); - }); - - it('inherits when used with require(util).inherits', function () { - class Beast extends EventEmitter { - /* rawr, i'm a beast */ +// EventEmitter.eventNames() +// should return array of strings or symbols +ee.eventNames().every((event) => { + if (typeof event === 'symbol') { + return false; + } else { + return event.length > 0; } - - class BeastES6 extends EventEmitter3ImportedAsES6Module { - /* rawr, i'm a beast */ - } - - util.inherits(Beast, EventEmitter); - - var moop = new Beast() - , meap = new Beast(); - - assume(moop).is.instanceOf(Beast); - assume(moop).is.instanceOf(EventEmitter); - - moop.listeners(); - meap.listeners(); - - moop.on('data', function () { - throw new Error('I should not emit'); - }); - - meap.emit('data', 'rawr'); - meap.removeListener('foo'); - meap.removeAllListeners(); - }); - - describe('EventEmitter#emit', function () { - it('should return false when there are not events to emit', function () { - var e = new EventEmitter(); - - assume(e.emit('foo')).equals(false); - assume(e.emit('bar')).equals(false); - }); - - it('emits with context', function (done) { - var context = { bar: 'baz' } - , e = new EventEmitter(); - - e.on('foo', function (bar: string) { - assume(bar).equals('bar'); - assume(this).equals(context); - - done(); - }, context).emit('foo', 'bar'); - }); - - it('emits with context, multiple arguments (force apply)', function (done) { - var context = { bar: 'baz' } - , e = new EventEmitter(); - - e.on('foo', function (bar: string) { - assume(bar).equals('bar'); - assume(this).equals(context); - - done(); - }, context).emit('foo', 'bar', 1,2,3,4,5,6,7,8,9,0); - }); - - it('can emit the function with multiple arguments', function () { - var e = new EventEmitter(); - - for(var i = 0; i < 100; i++) { - (function (j: number) { - for (var i = 0, args: number[] = []; i < j; i++) { - args.push(j); - } - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.emit.apply(e, (['args'] as any[]).concat(args)); - })(i); - } - }); - - it('can emit the function with multiple arguments, multiple listeners', function () { - var e = new EventEmitter(); - - for(var i = 0; i < 100; i++) { - (function (j: number) { - for (var i = 0, args: number[] = []; i < j; i++) { - args.push(j); - } - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.emit.apply(e, (['args'] as any[]).concat(args)); - })(i); - } - }); - - it('emits with context, multiple listeners (force loop)', function () { - var e = new EventEmitter(); - - e.on('foo', function (bar: string) { - assume(this).eqls({ foo: 'bar' }); - assume(bar).equals('bar'); - }, { foo: 'bar' }); - - e.on('foo', function (bar: string) { - assume(this).eqls({ bar: 'baz' }); - assume(bar).equals('bar'); - }, { bar: 'baz' }); - - e.emit('foo', 'bar'); - }); - - it('emits with different contexts', function () { - var e = new EventEmitter() - , pattern = ''; - - function writer() { - pattern += this; - } - - e.on('write', writer, 'foo'); - e.on('write', writer, 'baz'); - e.once('write', writer, 'bar'); - e.once('write', writer, 'banana'); - - e.emit('write'); - assume(pattern).equals('foobazbarbanana'); - }); - - it('should return true when there are events to emit', function (done) { - var e = new EventEmitter(); - - e.on('foo', function () { - process.nextTick(done); - }); - - assume(e.emit('foo')).equals(true); - assume(e.emit('foob')).equals(false); - }); - - it('receives the emitted events', function (done) { - var e = new EventEmitter(); - - e.on('data', function (a: string, b: EventEmitter3.EventEmitter, c: Date, d: void, undef: void) { - assume(a).equals('foo'); - assume(b).equals(e); - assume(c).is.instanceOf(Date); - assume(undef).equals(undefined); - assume(arguments.length).equals(3); - - done(); - }); - - e.emit('data', 'foo', e, new Date()); - }); - - it('emits to all event listeners', function () { - var e = new EventEmitter() - , pattern: string[] = []; - - e.on('foo', function () { - pattern.push('foo1'); - }); - - e.on('foo', function () { - pattern.push('foo2'); - }); - - e.emit('foo'); - - assume(pattern.join(';')).equals('foo1;foo2'); - }); - - (function each(keys: string[]) { - var key = keys.shift(); - - if (!key) return; - - it('can store event which is a known property: '+ key, function (next) { - var e = new EventEmitter(); - - e.on(key, function (key: string) { - assume(key).equals(key); - next(); - }).emit(key, key); - }); - - each(keys); - })([ - 'hasOwnProperty', - 'constructor', - '__proto__', - 'toString', - 'toValue', - 'unwatch', - 'watch' - ]); - }); - - describe('EventEmitter#listeners', function () { - it('returns an empty array if no listeners are specified', function () { - var e = new EventEmitter(); - - assume(e.listeners('foo')).is.a('array'); - assume(e.listeners('foo').length).equals(0); - }); - - it('returns an array of function', function () { - var e = new EventEmitter(); - - function foo() {} - - e.on('foo', foo); - assume(e.listeners('foo')).is.a('array'); - assume(e.listeners('foo').length).equals(1); - assume(e.listeners('foo')).deep.equals([foo]); - }); - - it('is not vulnerable to modifications', function () { - var e = new EventEmitter(); - - function foo() {} - - e.on('foo', foo); - - assume(e.listeners('foo')).deep.equals([foo]); - - e.listeners('foo').length = 0; - assume(e.listeners('foo')).deep.equals([foo]); - }); - - it('can return a boolean as indication if listeners exist', function () { - var e = new EventEmitter(); - - function foo() {} - - e.once('once', foo); - e.once('multiple', foo); - e.once('multiple', foo); - e.on('on', foo); - e.on('multi', foo); - e.on('multi', foo); - - assume(e.listeners('foo', true)).equals(false); - assume(e.listeners('multiple', true)).equals(true); - assume(e.listeners('on', true)).equals(true); - assume(e.listeners('multi', true)).equals(true); - - e.removeAllListeners(); - - assume(e.listeners('multiple', true)).equals(false); - assume(e.listeners('on', true)).equals(false); - assume(e.listeners('multi', true)).equals(false); - }); - }); - - describe('EventEmitter#once', function () { - it('only emits it once', function () { - var e = new EventEmitter() - , calls = 0; - - e.once('foo', function () { - calls++; - }); - - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - - assume(e.listeners('foo').length).equals(0); - assume(calls).equals(1); - }); - - it('only emits once if emits are nested inside the listener', function () { - var e = new EventEmitter() - , calls = 0; - - e.once('foo', function () { - calls++; - e.emit('foo'); - }); - - e.emit('foo'); - assume(e.listeners('foo').length).equals(0); - assume(calls).equals(1); - }); - - it('only emits once for multiple events', function () { - var e = new EventEmitter() - , multi = 0 - , foo = 0 - , bar = 0; - - e.once('foo', function () { - foo++; - }); - - e.once('foo', function () { - bar++; - }); - - e.on('foo', function () { - multi++; - }); - - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - - assume(e.listeners('foo').length).equals(1); - assume(multi).equals(5); - assume(foo).equals(1); - assume(bar).equals(1); - }); - - it('only emits once with context', function (done) { - var context = { foo: 'bar' } - , e = new EventEmitter(); - - e.once('foo', function (bar: string) { - assume(this).equals(context); - assume(bar).equals('bar'); - - done(); - }, context).emit('foo', 'bar'); - }); - }); - - describe('EventEmitter#removeListener', function () { - it('should only remove the event with the specified function', function () { - var e = new EventEmitter(); - - function bar() {} - e.on('foo', function () {}); - e.on('bar', function () {}); - e.on('bar', bar); - - assume(e.removeListener('foo', bar)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.listeners('bar').length).equals(2); - - assume(e.removeListener('foo')).equals(e); - assume(e.listeners('foo').length).equals(0); - assume(e.listeners('bar').length).equals(2); - - assume(e.removeListener('bar', bar)).equals(e); - assume(e.listeners('bar').length).equals(1); - assume(e.removeListener('bar')).equals(e); - assume(e.listeners('bar').length).equals(0); - }); - - it('should only remove once events when using the once flag', function () { - var e = new EventEmitter(); - - function foo() {} - e.on('foo', foo); - - assume(e.removeListener('foo', function () {}, undefined, true)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', foo, undefined, true)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', foo)).equals(e); - assume(e.listeners('foo').length).equals(0); - - e.on('foo', foo); - e.once('foo', foo); - - assume(e.removeListener('foo', function () {}, undefined, true)).equals(e); - assume(e.listeners('foo').length).equals(2); - assume(e.removeListener('foo', foo, undefined, true)).equals(e); - assume(e.listeners('foo').length).equals(1); - - e.once('foo', foo); - - assume(e.removeListener('foo', foo)).equals(e); - assume(e.listeners('foo').length).equals(0); - }); - - it('should only remove listeners matching the correct context', function () { - var e = new EventEmitter() - , context = { foo: 'bar' }; - - function foo() {} - function bar() {} - e.on('foo', foo, context); - - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', function () {}, context)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', foo, { baz: 'quux' })).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', foo, context)).equals(e); - assume(e.listeners('foo').length).equals(0); - - e.on('foo', foo, context); - e.on('foo', bar); - - assume(e.listeners('foo').length).equals(2); - assume(e.removeListener('foo', foo, { baz: 'quux' })).equals(e); - assume(e.listeners('foo').length).equals(2); - assume(e.removeListener('foo', foo, context)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.listeners('foo')[0]).equals(bar); - - e.on('foo', foo, context); - - assume(e.listeners('foo').length).equals(2); - assume(e.removeAllListeners('foo')).equals(e); - assume(e.listeners('foo').length).equals(0); - }); - }); - - describe('EventEmitter#removeAllListeners', function () { - it('removes all events for the specified events', function () { - var e = new EventEmitter(); - - e.on('foo', function () { throw new Error('oops'); }); - e.on('foo', function () { throw new Error('oops'); }); - e.on('bar', function () { throw new Error('oops'); }); - e.on('aaa', function () { throw new Error('oops'); }); - - assume(e.removeAllListeners('foo')).equals(e); - assume(e.listeners('foo').length).equals(0); - assume(e.listeners('bar').length).equals(1); - assume(e.listeners('aaa').length).equals(1); - - assume(e.removeAllListeners('bar')).equals(e); - assume(e.removeAllListeners('aaa')).equals(e); - - assume(e.emit('foo')).equals(false); - assume(e.emit('bar')).equals(false); - assume(e.emit('aaa')).equals(false); - }); - - it('just nukes the fuck out of everything', function () { - var e = new EventEmitter(); - - e.on('foo', function () { throw new Error('oops'); }); - e.on('foo', function () { throw new Error('oops'); }); - e.on('bar', function () { throw new Error('oops'); }); - e.on('aaa', function () { throw new Error('oops'); }); - - assume(e.removeAllListeners()).equals(e); - assume(e.listeners('foo').length).equals(0); - assume(e.listeners('bar').length).equals(0); - assume(e.listeners('aaa').length).equals(0); - - assume(e.emit('foo')).equals(false); - assume(e.emit('bar')).equals(false); - assume(e.emit('aaa')).equals(false); - }); - }); - - describe('#setMaxListeners', function () { - it('is a function', function () { - var e = new EventEmitter(); - - assume(e.setMaxListeners).is.a('function'); - }); - - it('returns self when called', function () { - var e = new EventEmitter(); - - assume(e.setMaxListeners()).to.equal(e); - }); - }); }); + +// EventEmitter.listeners() +// should return array of functions +ee.listeners(eventName).map((listener) => { + return listener.bind(this); +}); +// should accept symbol as event name +ee.listeners(eventSymbol).map((listener) => { + return listener.bind(this); +}); +// should return boolean with 'exists' flag +const hasListeners: boolean = ee.listeners(eventName, true); + +// EventEmitter.emit() +// should support any number of arguments +ee.emit(eventName, 1, true, {}, [], 'test', Symbol(), null); +// should accept symbol as event name +ee.emit(eventSymbol); + +// EventEmitter.addListener() and EventEmitter.on() +// should accept function +ee.on(eventName, fn); +ee.addListener(eventName, fn); +// should accept optional context argument +ee.on(eventName, fn, this); +ee.addListener(eventName, fn, this); +// should accept symbol as event name +ee.on(eventSymbol, fn); +ee.addListener(eventSymbol, fn); +// should support fluent interface +ee.on(eventSymbol, fn).on(eventName, fn); +ee.addListener(eventSymbol, fn).addListener(eventName, fn); + +// EventEmitter.once() +// should accept event name and function +ee.once(eventName, fn); +// should accept optional context argument +ee.once(eventName, fn, this); +ee.once(eventName, fn, {}); +// should accept symbol as event name +ee.once(eventSymbol, fn); +// should support fluent interface +ee.once(eventSymbol, fn).once(eventName, fn); + +// EventEmitter.removeListener() and EventEmitter.off() +// should accept event name +ee.removeListener(eventName); +ee.off(eventName); +// should accept optional function +ee.removeListener(eventName, fn); +ee.off(eventName, fn); +// should accept optional context argument +ee.removeListener(eventName, fn, {}); +ee.off(eventName, fn, {}); +// should accept optional boolean flag for removing listeners added with `EventEmitter.once()` +ee.removeListener(eventName, fn, null, true); +ee.off(eventName, fn, null, true); +// should accept symbol as event name +ee.removeListener(eventSymbol); +ee.off(eventSymbol); +// should support fluent interface +ee.removeListener(eventName).removeListener(eventSymbol); +ee.off(eventName).off(eventSymbol); + +// EventEmitter.removeAllListeners() +// should not require any arguments +ee.removeAllListeners(); +// should accept optional event name +ee.removeAllListeners(eventName); +// should accept symbol as event name +ee.removeAllListeners(eventSymbol); +// should support fluent interface +ee.removeAllListeners(eventName).removeAllListeners(eventSymbol); + +// EventEmitter.setMaxListeners() +// should support fluent interface +ee.setMaxListeners().setMaxListeners(); diff --git a/eventemitter3/eventemitter3-1.2.0-tests.ts.tscparams b/eventemitter3/eventemitter3-tests.ts.tscparams similarity index 100% rename from eventemitter3/eventemitter3-1.2.0-tests.ts.tscparams rename to eventemitter3/eventemitter3-tests.ts.tscparams diff --git a/eventemitter3/eventemitter3.d.ts b/eventemitter3/eventemitter3.d.ts index 0d692b8247..ad71b1d49b 100644 --- a/eventemitter3/eventemitter3.d.ts +++ b/eventemitter3/eventemitter3.d.ts @@ -1,123 +1,109 @@ -// Type definitions for EventEmitter3 1.1.1 +// Type definitions for EventEmitter3 1.2.0 // Project: https://github.com/primus/eventemitter3 -// Definitions by: Yuichi Murata , Leon Yu +// Definitions by: Yuichi Murata , Leon Yu , Boriss Nazarovs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace EventEmitter3 { - interface EventEmitter3Static { - new (): EventEmitter; - prefixed: string | boolean; - } + /** + * Minimal EventEmitter interface that is molded against the Node.js + * EventEmitter interface. + */ class EventEmitter { - /** - * Minimal EventEmitter interface that is molded against the Node.js - * EventEmitter interface. - * - * @constructor - * @api public - */ constructor(); /** - * Return a list of assigned event listeners. + * Return an array listing the events for which the emitter has registered listeners. * - * @param {String} event The events that should be listed. - * @returns {Array} - * @api public + * @returns {(string|symbol)[]} */ - listeners(event?: string): Function[]; + eventNames(): (string|symbol)[]; /** - * Return a list of assigned event listeners. + * Return the listeners registered for a given event. * - * @param {String} event The events that should be listed. - * @param {Boolean} exists We only need to know if there are listeners. - * @returns {Boolean} - * @api public + * @param {(string|symbol)} event The event name. + * @returns {Function[]} */ - listeners(event: string, param: boolean): boolean; + listeners(event: string|symbol): Function[]; /** - * Emit an event to all registered event listeners. + * Check if there listeners for a given event. + * If `exists` argument is not `true` lists listeners. * - * @param {String} event The name of the event. - * @returns {Boolean} Indication if we've emitted an event. - * @api public + * @param {(string|symbol)} event The event name. + * @param {boolean} exists Only check if there are listeners. + * @returns {boolean} */ - emit(event: string, ...args: any[]): boolean; + listeners(event: string|symbol, exists: boolean): boolean; /** - * Register a new EventListener for the given event. + * Calls each of the listeners registered for a given event. * - * @param {String} event Name of the event. - * @param {Function} fn Callback function. - * @param {Mixed} [context=this] The context of the function. - * @api public + * @param {(string|symbol)} event The event name. + * @param {...*} args Arguments that are passed to registered listeners + * @returns {boolean} `true` if the event had listeners, else `false`. */ - on(event: string, fn: Function, context?: any): EventEmitter; + emit(event: string|symbol, ...args: any[]): boolean; /** - * Add an EventListener that's only called once. + * Add a listener for a given event. * - * @param {String} event Name of the event. - * @param {Function} fn Callback function. - * @param {Mixed} [context=this] The context of the function. - * @api public + * @param {(string|symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. */ - once(event: string, fn: Function, context?: any): EventEmitter; + on(event: string|symbol, fn: Function, context?: any): EventEmitter; /** - * Remove event listeners. + * Add a one-time listener for a given event. * - * @param {String} event The event we want to remove. - * @param {Function} fn The listener that we need to find. - * @param {Mixed} context Only remove listeners matching this context. - * @param {Boolean} once Only remove once listeners. - * @api public + * @param {(string|symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. */ - removeListener(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; + once(event: string|symbol, fn: Function, context?: any): EventEmitter; /** - * Remove all listeners or only the listeners for the specified event. + * Remove the listeners of a given event. * - * @param {String} event The event want to remove all listeners for. - * @api public + * @param {(string|symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. */ - removeAllListeners(event?: string): EventEmitter; + removeListener(event: string|symbol, fn?: Function, context?: any, once?: boolean): EventEmitter; /** - * Remove event listeners. + * Remove all listeners, or those of the specified event. * - * @param {String} event The event we want to remove. - * @param {Function} fn The listener that we need to find. - * @param {Mixed} context Only remove listeners matching this context. - * @param {Boolean} once Only remove once listeners. - * @api public + * @param {(string|symbol)} event The event name. + * @returns {EventEmitter} `this`. */ - off(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; + removeAllListeners(event?: string|symbol): EventEmitter; /** - * Register a new EventListener for the given event. - * - * @param {String} event Name of the event. - * @param {Function} fn Callback function. - * @param {Mixed} [context=this] The context of the function. - * @api public + * Alias method for `removeListener` */ - addListener(event: string, fn: Function, context?: any): EventEmitter; + off(event: string|symbol, fn?: Function, context?: any, once?: boolean): EventEmitter; + + /** + * Alias method for `on` + */ + addListener(event: string|symbol, fn: Function, context?: any): EventEmitter; /** * This function doesn't apply anymore. * @deprecated */ setMaxListeners(): EventEmitter; + + static prefixed: string|boolean; } } declare module 'eventemitter3' { - // - // Expose the module. - // - var EventEmitter3: EventEmitter3.EventEmitter3Static; - export = EventEmitter3; + export = EventEmitter3.EventEmitter; } From d240f0ad0289e58d73701b8b5667cd973b60a69f Mon Sep 17 00:00:00 2001 From: Boriss Nazarovs Date: Fri, 2 Sep 2016 00:01:37 +0300 Subject: [PATCH 007/554] Added support for fluent interface in classes extending EventEmitter --- eventemitter3/eventemitter3-tests.ts | 18 +++++++++++------- eventemitter3/eventemitter3.d.ts | 14 +++++++------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/eventemitter3/eventemitter3-tests.ts b/eventemitter3/eventemitter3-tests.ts index 895dc7f54b..8af197a80c 100644 --- a/eventemitter3/eventemitter3-tests.ts +++ b/eventemitter3/eventemitter3-tests.ts @@ -12,6 +12,10 @@ class TestEmitter extends EventEmitter { constructor() { super(); } + + test() { + return this; + } } const ee: TestEmitter = new TestEmitter(); @@ -64,8 +68,8 @@ ee.addListener(eventName, fn, this); ee.on(eventSymbol, fn); ee.addListener(eventSymbol, fn); // should support fluent interface -ee.on(eventSymbol, fn).on(eventName, fn); -ee.addListener(eventSymbol, fn).addListener(eventName, fn); +ee.on(eventSymbol, fn).test(); +ee.addListener(eventSymbol, fn).test(); // EventEmitter.once() // should accept event name and function @@ -76,7 +80,7 @@ ee.once(eventName, fn, {}); // should accept symbol as event name ee.once(eventSymbol, fn); // should support fluent interface -ee.once(eventSymbol, fn).once(eventName, fn); +ee.once(eventSymbol, fn).test(); // EventEmitter.removeListener() and EventEmitter.off() // should accept event name @@ -95,8 +99,8 @@ ee.off(eventName, fn, null, true); ee.removeListener(eventSymbol); ee.off(eventSymbol); // should support fluent interface -ee.removeListener(eventName).removeListener(eventSymbol); -ee.off(eventName).off(eventSymbol); +ee.removeListener(eventName).test(); +ee.off(eventName).test(); // EventEmitter.removeAllListeners() // should not require any arguments @@ -106,8 +110,8 @@ ee.removeAllListeners(eventName); // should accept symbol as event name ee.removeAllListeners(eventSymbol); // should support fluent interface -ee.removeAllListeners(eventName).removeAllListeners(eventSymbol); +ee.removeAllListeners(eventName).test(); // EventEmitter.setMaxListeners() // should support fluent interface -ee.setMaxListeners().setMaxListeners(); +ee.setMaxListeners().test(); diff --git a/eventemitter3/eventemitter3.d.ts b/eventemitter3/eventemitter3.d.ts index ad71b1d49b..96af62c94b 100644 --- a/eventemitter3/eventemitter3.d.ts +++ b/eventemitter3/eventemitter3.d.ts @@ -53,7 +53,7 @@ declare namespace EventEmitter3 { * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. */ - on(event: string|symbol, fn: Function, context?: any): EventEmitter; + on(event: string|symbol, fn: Function, context?: any): this; /** * Add a one-time listener for a given event. @@ -63,7 +63,7 @@ declare namespace EventEmitter3 { * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. */ - once(event: string|symbol, fn: Function, context?: any): EventEmitter; + once(event: string|symbol, fn: Function, context?: any): this; /** * Remove the listeners of a given event. @@ -74,7 +74,7 @@ declare namespace EventEmitter3 { * @param {boolean} once Only remove one-time listeners. * @returns {EventEmitter} `this`. */ - removeListener(event: string|symbol, fn?: Function, context?: any, once?: boolean): EventEmitter; + removeListener(event: string|symbol, fn?: Function, context?: any, once?: boolean): this; /** * Remove all listeners, or those of the specified event. @@ -82,23 +82,23 @@ declare namespace EventEmitter3 { * @param {(string|symbol)} event The event name. * @returns {EventEmitter} `this`. */ - removeAllListeners(event?: string|symbol): EventEmitter; + removeAllListeners(event?: string|symbol): this; /** * Alias method for `removeListener` */ - off(event: string|symbol, fn?: Function, context?: any, once?: boolean): EventEmitter; + off(event: string|symbol, fn?: Function, context?: any, once?: boolean): this; /** * Alias method for `on` */ - addListener(event: string|symbol, fn: Function, context?: any): EventEmitter; + addListener(event: string|symbol, fn: Function, context?: any): this; /** * This function doesn't apply anymore. * @deprecated */ - setMaxListeners(): EventEmitter; + setMaxListeners(): this; static prefixed: string|boolean; } From 7c50d2c7a7d11b0e6e76508b59b359b4ae4e558c Mon Sep 17 00:00:00 2001 From: "Dmitry A. Efimenko" Date: Thu, 15 Sep 2016 10:20:57 -0700 Subject: [PATCH 008/554] added prop options and func timeFormatter added property `options`, which can be found in [the code](https://github.com/joewalnes/smoothie/blob/15fc4b62f5b23c8d5dd1784c820ae73f341626e6/smoothie.js#L270). Even though it's not mentioned in the docs, it useful to be able to access these options after chart is initialized when you want to change appearance in real tme. added function `timeFormatter`, which is mentioned in [right here, in the definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/smoothie/smoothie.d.ts#L127) and can be found in [the code](https://github.com/joewalnes/smoothie/blob/15fc4b62f5b23c8d5dd1784c820ae73f341626e6/smoothie.js#L795) --- smoothie/smoothie.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/smoothie/smoothie.d.ts b/smoothie/smoothie.d.ts index 98f205f598..c396261c52 100644 --- a/smoothie/smoothie.d.ts +++ b/smoothie/smoothie.d.ts @@ -141,6 +141,8 @@ declare module "smoothie" */ export class SmoothieChart { + options: IChartOptions; + constructor(chartOptions?: IChartOptions); /** @@ -188,5 +190,7 @@ declare module "smoothie" updateValueRange(): void; render(canvas?: HTMLCanvasElement, time?: number): void; + + static timeFormatter(date: Date): string; } } From 6151d69fadae62c9a4636a0736b0820b53f44e44 Mon Sep 17 00:00:00 2001 From: Boriss Nazarovs Date: Sat, 24 Sep 2016 14:37:30 +0300 Subject: [PATCH 009/554] Updated import in tests to use standard TypeScript import syntax --- eventemitter3/eventemitter3-tests.ts | 4 ++-- eventemitter3/eventemitter3-tests.ts.tscparams | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eventemitter3/eventemitter3-tests.ts b/eventemitter3/eventemitter3-tests.ts index 8af197a80c..77d84093cf 100644 --- a/eventemitter3/eventemitter3-tests.ts +++ b/eventemitter3/eventemitter3-tests.ts @@ -1,10 +1,10 @@ /// 'use strict'; -import EventEmitter from 'eventemitter3'; +import EventEmitter = require('eventemitter3'); const eventName = 'test'; -const eventSymbol: symbol = Symbol('test'); +const eventSymbol = Symbol('test'); const fn = () => console.log(1); // Extending EventEmitter diff --git a/eventemitter3/eventemitter3-tests.ts.tscparams b/eventemitter3/eventemitter3-tests.ts.tscparams index a0aefcf79a..30c9419a57 100644 --- a/eventemitter3/eventemitter3-tests.ts.tscparams +++ b/eventemitter3/eventemitter3-tests.ts.tscparams @@ -1 +1 @@ ---target es6 --allowSyntheticDefaultImports --noImplicitAny +-m commonjs From f82ccb560ec3b966fa571384047e27152cfed391 Mon Sep 17 00:00:00 2001 From: Matthew McEachen Date: Sun, 25 Sep 2016 16:22:47 -0700 Subject: [PATCH 010/554] Added types for klaw (#11492) * Added types for klaw * addressed pr comments and `tsfmt -r klaw/*.ts` --- klaw/klaw-tests.ts | 46 ++++++++++++++++++++++++++++++++++++++++++++++ klaw/klaw.d.ts | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 klaw/klaw-tests.ts create mode 100644 klaw/klaw.d.ts diff --git a/klaw/klaw-tests.ts b/klaw/klaw-tests.ts new file mode 100644 index 0000000000..5e7ecdebf7 --- /dev/null +++ b/klaw/klaw-tests.ts @@ -0,0 +1,46 @@ +/// +/// + +import * as klaw from "klaw"; +const path = require('path'); + +// README.md: Streams 1 (push) example: + +let items: klaw.Item[] = [] // files, directories, symlinks, etc + +klaw('/some/dir') + .on('data', function(item: klaw.Item) { + items.push(item) + }) + .on('end', function() { + console.dir(items) // => [ ... array of files] + }) + +// README.md: Streams 2 & 3 (pull) with error handling + +klaw('/some/dir') + .on('readable', function() { + let item: klaw.Item; + while (item = this.read()) { + items.push(item) + } + }) + .on('error', function(err: Error, item: klaw.Item) { + console.log(err.message) + console.log(item.path) // the file the error occurred on + }) + .on('end', function() { + console.log(items) // => [ ... array of files] + }) + +// README.md: Example (ignore hidden directories): + +var filterFunc = function(item: klaw.Item): boolean { + var basename = path.basename(item.path) + return basename === '.' || basename[0] !== '.' +} + +klaw('/some/dir', { filter: filterFunc }) + .on('data', function(item: klaw.Item) { + // only items of none hidden folders will reach here + }) diff --git a/klaw/klaw.d.ts b/klaw/klaw.d.ts new file mode 100644 index 0000000000..e2b641f546 --- /dev/null +++ b/klaw/klaw.d.ts @@ -0,0 +1,44 @@ +// Type definitions for klaw v1.3.0 +// Project: https://github.com/jprichardson/node-klaw +// Definitions by: Matthew McEachen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "klaw" { + + import * as fs from "fs" + import { Readable, ReadableOptions } from 'stream' + + function K(root: string, options?: K.Options): K.Walker + + namespace K { + interface Item { + path: string + stats: fs.Stats + } + + type QueueMethod = "shift" | "pop" + + interface Options extends ReadableOptions { + queueMethod?: QueueMethod + pathSorter?: (a: Array) => Array + fs?: any // fs or mock-fs + filter?: (a: Item) => boolean + } + + type Event = "close" | "data" | "end" | "readable" | "error" + + interface Walker { + on(event: Event, listener: Function): this + on(event: "close", listener: () => void): this + on(event: "data", listener: (item: Item) => void): this + on(event: "end", listener: () => void): this + on(event: "readable", listener: () => void): this + on(event: "error", listener: (err: Error) => void): this + read(): Item + } + } + + export = K +} From d0a34b8791e95a0f17314c8754e3b0a96e812be7 Mon Sep 17 00:00:00 2001 From: Hisham A Date: Mon, 26 Sep 2016 08:33:32 -0600 Subject: [PATCH 011/554] add typings for onselected and onunselected methods, refs #11493 (#11496) --- c3/c3.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/c3/c3.d.ts b/c3/c3.d.ts index e815b44391..83ccf85853 100644 --- a/c3/c3.d.ts +++ b/c3/c3.d.ts @@ -385,10 +385,10 @@ declare namespace c3 { * - d is the data where mouse cursor moves out. In this callback, this will be the Chart object. */ onmouseout?: (d: any, element?: any) => void; - // onselected?: any; - // onunselected?: any; - // ondragstart?: any; - // ondragend?: any; + + onselected?: (d: any, element?: any) => void; + + onunselected?: (d: any, element?: any) => void; } interface Axis { From 55d9114bbd68142c1afb846732cfaae002aca27c Mon Sep 17 00:00:00 2001 From: Ben Chauvette Date: Mon, 26 Sep 2016 07:52:03 -0700 Subject: [PATCH 012/554] Improve through2 declarations (#11499) * [through2] Fix typos * [through2] Change return types to stream.Transform `through2` creates `stream.Transform`-flavored streams, so switching the return types to `stream.Transform` gives us richer typing information than using `NodeJS.ReadWriteStream`, which is missing methods (e.g. `stream.Transform#push`) and the ability to use object mode. * [through2] Add through2.ctor method * [through2] Update header and docs --- through2/through2-tests.ts | 49 +++++++++++++++++++++++++++++++++++++- through2/through2.d.ts | 28 +++++++++++++++------- 2 files changed, 67 insertions(+), 10 deletions(-) diff --git a/through2/through2-tests.ts b/through2/through2-tests.ts index e6f97fb712..94d60e0bff 100644 --- a/through2/through2-tests.ts +++ b/through2/through2-tests.ts @@ -1,9 +1,11 @@ /// /// +import stream = require('stream'); import through2 = require('through2'); -var rws: NodeJS.ReadWriteStream; +var rws: stream.Transform; +var Rws: through2.Through2Constructor; rws = through2({ objectMode: true, @@ -53,3 +55,48 @@ rws = through2.obj(function (entry: any, enc: string, callback: (err: any) => vo }, (flashCallback) => { flashCallback(); }); + +// ctor +Rws = through2.ctor({ + objectMode: true, + allowHalfOpen: true +}, function (entry: any, enc: string, callback: () => void) { + this.push('foo'); + callback(); +}, () => { + +}); + +rws = Rws(); +rws = new Rws(); +rws = new Rws({ objectMode: true, allowHalfOpen: true }); + +Rws = through2.ctor(function (entry: any, enc: string, callback: () => void) { + this.push('foo'); + callback(); +}, () => { + +}); + +rws = Rws(); +rws = new Rws(); +rws = new Rws({ objectMode: true, allowHalfOpen: true }); + +Rws = through2.ctor(function (entry: any, enc: string, callback: (error: any, data?: any) => void) { + callback(null, 'foo'); +}, (flushCallback: () => void) => { + flushCallback(); +}); + +rws = Rws(); +rws = new Rws(); +rws = new Rws({ objectMode: true, allowHalfOpen: true }); + +Rws = through2.ctor(function (entry: any, enc: string, callback: () => void) { + this.push('foo'); + callback(); +}); + +rws = Rws(); +rws = new Rws(); +rws = new Rws({ objectMode: true, allowHalfOpen: true }); diff --git a/through2/through2.d.ts b/through2/through2.d.ts index 77cc817caa..27b8a93178 100644 --- a/through2/through2.d.ts +++ b/through2/through2.d.ts @@ -1,6 +1,6 @@ // Type definitions for through2 v 2.0.0 // Project: https://github.com/rvagg/through2 -// Definitions by: Bart van der Schoor , jedmao , Georgios Valotasios +// Definitions by: Bart van der Schoor , jedmao , Georgios Valotasios , Ben Chauvette // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -9,20 +9,30 @@ declare module 'through2' { import stream = require('stream'); - type TransfofmCallback = (err?: any, data?: any) => void; - type TransformFunction = (chunk: any, enc: string, callback: TransfofmCallback) => void; - type FlashCallback = (flushCallback: () => void) => void; + type TransformCallback = (err?: any, data?: any) => void; + type TransformFunction = (chunk: any, enc: string, callback: TransformCallback) => void; + type FlushCallback = (flushCallback: () => void) => void; - function through2(transform?: TransformFunction, flush?: FlashCallback): NodeJS.ReadWriteStream; + function through2(transform?: TransformFunction, flush?: FlushCallback): stream.Transform; - function through2(opts?: stream.DuplexOptions, transform?: TransformFunction, flush?: FlashCallback): NodeJS.ReadWriteStream; + function through2(opts?: stream.DuplexOptions, transform?: TransformFunction, flush?: FlushCallback): stream.Transform; namespace through2 { + export interface Through2Constructor extends stream.Transform { + new(opts?: stream.DuplexOptions): stream.Transform; + (opts?: stream.DuplexOptions): stream.Transform; + } - export function obj(transform?: TransformFunction, flush?: FlashCallback): NodeJS.ReadWriteStream; - - export function push(data: any): void; + /** + * Convenvience method for creating object streams + */ + export function obj(transform?: TransformFunction, flush?: FlushCallback): stream.Transform; + /** + * Creates a constructor for a custom Transform. This is useful when you + * want to use the same transform logic in multiple instances. + */ + export function ctor(opts?: stream.DuplexOptions, transfrom?: TransformFunction, flush?: FlushCallback): Through2Constructor; } export = through2; From d907b02638bf6c56ae3f632ca5c151cb869df5b4 Mon Sep 17 00:00:00 2001 From: Izaak Baker Date: Mon, 26 Sep 2016 14:01:45 -0700 Subject: [PATCH 013/554] Add module declaration to crossfilter so that it can be explicitly imported (#11521) --- crossfilter/crossfilter.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crossfilter/crossfilter.d.ts b/crossfilter/crossfilter.d.ts index 646d8abeb0..ed888f6959 100644 --- a/crossfilter/crossfilter.d.ts +++ b/crossfilter/crossfilter.d.ts @@ -1,6 +1,6 @@ // Type definitions for CrossFilter // Project: https://github.com/square/crossfilter -// Definitions by: Schmulik Raskin +// Definitions by: Schmulik Raskin , Izaak Baker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace CrossFilter { @@ -111,3 +111,8 @@ declare namespace CrossFilter { } declare var crossfilter: CrossFilter.CrossFilterStatic; +declare module "crossfilter" { + var crossfilter: CrossFilter.CrossFilterStatic; + export = crossfilter; +} + From 22a311bd60be06c92d4b9a6646e30b3180627158 Mon Sep 17 00:00:00 2001 From: David Lee Date: Mon, 26 Sep 2016 17:44:22 -0500 Subject: [PATCH 014/554] Add typings for murmurhash3js --- murmurhash3js/murmurhash3js-tests.ts | 12 ++++++++++++ murmurhash3js/murmurhash3js.d.ts | 15 +++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 murmurhash3js/murmurhash3js-tests.ts create mode 100644 murmurhash3js/murmurhash3js.d.ts diff --git a/murmurhash3js/murmurhash3js-tests.ts b/murmurhash3js/murmurhash3js-tests.ts new file mode 100644 index 0000000000..297adcbc67 --- /dev/null +++ b/murmurhash3js/murmurhash3js-tests.ts @@ -0,0 +1,12 @@ +/// + +import murmurhash3js = require('murmurhash3js'); + +murmurhash3js.x86.hash32('string'); +murmurhash3js.x86.hash32('string with seed', 1337); + +murmurhash3js.x86.hash128('string'); +murmurhash3js.x86.hash128('string with seed', 1337); + +murmurhash3js.x64.hash128('string'); +murmurhash3js.x64.hash128('string with seed', 1337); diff --git a/murmurhash3js/murmurhash3js.d.ts b/murmurhash3js/murmurhash3js.d.ts new file mode 100644 index 0000000000..f43deeaa37 --- /dev/null +++ b/murmurhash3js/murmurhash3js.d.ts @@ -0,0 +1,15 @@ +// Type definitions for murmurhash3js v3.0.1 +// Project: https://github.com/pid/murmurHash3js +// Definitions by: Dave Lee +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'murmurhash3js' { + export module x86 { + function hash32(val: string, seed?: number): string; + function hash128(val: string, seed?: number): string; + } + + export module x64 { + function hash128(val: string, seed?: number): string; + } +} \ No newline at end of file From 5143d60f3790c68c23ebbaf8f78951316a32322e Mon Sep 17 00:00:00 2001 From: David Lee Date: Mon, 26 Sep 2016 17:46:34 -0500 Subject: [PATCH 015/554] fix module import to be ES6 compliant --- murmurhash3js/murmurhash3js-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/murmurhash3js/murmurhash3js-tests.ts b/murmurhash3js/murmurhash3js-tests.ts index 297adcbc67..f9a40619d6 100644 --- a/murmurhash3js/murmurhash3js-tests.ts +++ b/murmurhash3js/murmurhash3js-tests.ts @@ -1,6 +1,6 @@ /// -import murmurhash3js = require('murmurhash3js'); +import * as murmurhash3js from 'murmurhash3js'; murmurhash3js.x86.hash32('string'); murmurhash3js.x86.hash32('string with seed', 1337); From 7e08a4492cabd1e022f488d3be9ebe9d238c06fe Mon Sep 17 00:00:00 2001 From: David Lee Date: Mon, 26 Sep 2016 17:47:40 -0500 Subject: [PATCH 016/554] newline at EOF --- murmurhash3js/murmurhash3js.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/murmurhash3js/murmurhash3js.d.ts b/murmurhash3js/murmurhash3js.d.ts index f43deeaa37..2193085d5b 100644 --- a/murmurhash3js/murmurhash3js.d.ts +++ b/murmurhash3js/murmurhash3js.d.ts @@ -12,4 +12,4 @@ declare module 'murmurhash3js' { export module x64 { function hash128(val: string, seed?: number): string; } -} \ No newline at end of file +} From 5ac67c6749dd84d45b091ef1b991f5cbb1171536 Mon Sep 17 00:00:00 2001 From: Alex Gorbatchev Date: Mon, 26 Sep 2016 19:40:01 -0700 Subject: [PATCH 017/554] [rethinkdb] Adds missing promise methods to Cursor and Connection --- rethinkdb/rethinkdb-tests.ts | 6 ++++-- rethinkdb/rethinkdb.d.ts | 23 ++++++++++++++--------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/rethinkdb/rethinkdb-tests.ts b/rethinkdb/rethinkdb-tests.ts index a6911e3021..4dbd7ab638 100644 --- a/rethinkdb/rethinkdb-tests.ts +++ b/rethinkdb/rethinkdb-tests.ts @@ -15,8 +15,10 @@ r.connect({host:"localhost", port: 28015}, function(err, conn) { }) .between("james", "beth") .limit(4) - .run(conn, function() { - + .run(conn, function(err, cursor) { + cursor.toArray().then(rows => { + console.log(rows); + }); }) }) diff --git a/rethinkdb/rethinkdb.d.ts b/rethinkdb/rethinkdb.d.ts index 7161e42060..0b4d6b54b9 100644 --- a/rethinkdb/rethinkdb.d.ts +++ b/rethinkdb/rethinkdb.d.ts @@ -35,11 +35,13 @@ declare module "rethinkdb" { export class Cursor { hasNext():boolean; - each(cb:(err:Error, row:any)=>void, done?:()=>void); - each(cb:(err:Error, row:any)=>boolean, done?:()=>void); // returning false stops iteration - next(cb:(err:Error, row:any) => void); - toArray(cb:(err:Error, rows:any[]) => void); - close(); + each(cb:(err:Error, row:any)=>void, done?:()=>void): void; + each(cb:(err:Error, row:any)=>boolean, done?:()=>void): void; // returning false stops iteration + next(cb:(err:Error, row:any) => void): void; + toArray(cb:(err:Error, rows:any[]) => void): void; + toArray(): Promise; + close(cb: (err: Error) => void): void; + close(): Promise; } interface ConnectionOptions { @@ -50,11 +52,14 @@ declare module "rethinkdb" { } interface Connection { - close(); + close(cb: (err: Error) => void): void; + close(opts: { noreplyWait: boolean }, cb: (err: Error) => void): void; + close(): Promise; + close(opts: { noreplyWait: boolean }): Promise; reconnect(cb?:(err:Error, conn:Connection)=>void):Promise; - use(dbName:string); - addListener(event:string, cb:Function); - on(event:string, cb:Function); + use(dbName:string): void; + addListener(event:string, cb:Function): void; + on(event:string, cb:Function): void; } interface Db { From 87a03f83ce8a03188424ca2126f4d1c70e17f0b4 Mon Sep 17 00:00:00 2001 From: Alex Gorbatchev Date: Mon, 26 Sep 2016 19:41:08 -0700 Subject: [PATCH 018/554] [rethinkdb] Applied TypeScript formatting to the file --- rethinkdb/rethinkdb.d.ts | 368 +++++++++++++++++++-------------------- 1 file changed, 184 insertions(+), 184 deletions(-) diff --git a/rethinkdb/rethinkdb.d.ts b/rethinkdb/rethinkdb.d.ts index 0b4d6b54b9..dc251b2a8e 100644 --- a/rethinkdb/rethinkdb.d.ts +++ b/rethinkdb/rethinkdb.d.ts @@ -8,234 +8,234 @@ declare module "rethinkdb" { - export function connect(host:ConnectionOptions, cb?:(err:Error, conn:Connection)=>void):Promise; + export function connect(host: ConnectionOptions, cb?: (err: Error, conn: Connection) => void): Promise; - export function dbCreate(name:string):Operation; - export function dbDrop(name:string):Operation; - export function dbList():Operation; + export function dbCreate(name: string): Operation; + export function dbDrop(name: string): Operation; + export function dbList(): Operation; - export function db(name:string):Db; - export function table(name:string, options?:{useOutdated:boolean}):Table; + export function db(name: string): Db; + export function table(name: string, options?: { useOutdated: boolean }): Table; - export function asc(property:string):Sort; - export function desc(property:string):Sort; + export function asc(property: string): Sort; + export function desc(property: string): Sort; - export var count:Aggregator; - export function sum(prop:string):Aggregator; - export function avg(prop:string):Aggregator; + export var count: Aggregator; + export function sum(prop: string): Aggregator; + export function avg(prop: string): Aggregator; - export function row(name:string):Expression; - export function expr(stuff:any):Expression; + export function row(name: string): Expression; + export function expr(stuff: any): Expression; - export function now():Time; + export function now(): Time; - // Control Structures - export function branch(test:Expression, trueBranch:Expression, falseBranch:Expression):Expression; + // Control Structures + export function branch(test: Expression, trueBranch: Expression, falseBranch: Expression): Expression; - export class Cursor { - hasNext():boolean; - each(cb:(err:Error, row:any)=>void, done?:()=>void): void; - each(cb:(err:Error, row:any)=>boolean, done?:()=>void): void; // returning false stops iteration - next(cb:(err:Error, row:any) => void): void; - toArray(cb:(err:Error, rows:any[]) => void): void; - toArray(): Promise; - close(cb: (err: Error) => void): void; - close(): Promise; - } + export class Cursor { + hasNext(): boolean; + each(cb: (err: Error, row: any) => void, done?: () => void): void; + each(cb: (err: Error, row: any) => boolean, done?: () => void): void; // returning false stops iteration + next(cb: (err: Error, row: any) => void): void; + toArray(cb: (err: Error, rows: any[]) => void): void; + toArray(): Promise; + close(cb: (err: Error) => void): void; + close(): Promise; + } - interface ConnectionOptions { - host:string; - port:number; - db?:string; - authKey?:string; - } + interface ConnectionOptions { + host: string; + port: number; + db?: string; + authKey?: string; + } - interface Connection { - close(cb: (err: Error) => void): void; - close(opts: { noreplyWait: boolean }, cb: (err: Error) => void): void; - close(): Promise; - close(opts: { noreplyWait: boolean }): Promise; - reconnect(cb?:(err:Error, conn:Connection)=>void):Promise; - use(dbName:string): void; - addListener(event:string, cb:Function): void; - on(event:string, cb:Function): void; - } + interface Connection { + close(cb: (err: Error) => void): void; + close(opts: { noreplyWait: boolean }, cb: (err: Error) => void): void; + close(): Promise; + close(opts: { noreplyWait: boolean }): Promise; + reconnect(cb?: (err: Error, conn: Connection) => void): Promise; + use(dbName: string): void; + addListener(event: string, cb: Function): void; + on(event: string, cb: Function): void; + } - interface Db { - tableCreate(name:string, options?:TableOptions):Operation; - tableDrop(name:string):Operation; - tableList():Operation; - table(name:string, options?:GetTableOptions):Table; - } + interface Db { + tableCreate(name: string, options?: TableOptions): Operation; + tableDrop(name: string): Operation; + tableList(): Operation; + table(name: string, options?: GetTableOptions): Table; + } - interface TableOptions { - primary_key?:string; // 'id' - durability?:string; // 'soft' - cache_size?:number; - datacenter?:string; - } + interface TableOptions { + primary_key?: string; // 'id' + durability?: string; // 'soft' + cache_size?: number; + datacenter?: string; + } - interface GetTableOptions { - useOutdated: boolean; - } + interface GetTableOptions { + useOutdated: boolean; + } - interface Writeable { - update(obj:Object, options?:UpdateOptions):Operation; - replace(obj:Object, options?:UpdateOptions):Operation; - replace(expr:ExpressionFunction):Operation; - delete(options?:UpdateOptions):Operation; - } + interface Writeable { + update(obj: Object, options?: UpdateOptions): Operation; + replace(obj: Object, options?: UpdateOptions): Operation; + replace(expr: ExpressionFunction): Operation; + delete(options?: UpdateOptions): Operation; + } - interface Table extends Sequence { - indexCreate(name:string, index?:ExpressionFunction):Operation; - indexDrop(name:string):Operation; - indexList():Operation; + interface Table extends Sequence { + indexCreate(name: string, index?: ExpressionFunction): Operation; + indexDrop(name: string): Operation; + indexList(): Operation; - insert(obj:any[], options?:InsertOptions):Operation; - insert(obj:any, options?:InsertOptions):Operation; + insert(obj: any[], options?: InsertOptions): Operation; + insert(obj: any, options?: InsertOptions): Operation; - get(key:string):Sequence; // primary key - getAll(key:string, index?:Index):Sequence; // without index defaults to primary key - getAll(...keys:string[]):Sequence; - } + get(key: string): Sequence; // primary key + getAll(key: string, index?: Index): Sequence; // without index defaults to primary key + getAll(...keys: string[]): Sequence; + } - interface Sequence extends Operation, Writeable { + interface Sequence extends Operation, Writeable { - between(lower:any, upper:any, index?:Index):Sequence; - filter(rql:ExpressionFunction):Sequence; - filter(rql:Expression):Sequence; - filter(obj:{[key:string]:any}):Sequence; + between(lower: any, upper: any, index?: Index): Sequence; + filter(rql: ExpressionFunction): Sequence; + filter(rql: Expression): Sequence; + filter(obj: { [key: string]: any }): Sequence; - // Join - // these return left, right - innerJoin(sequence:Sequence, join:JoinFunction):Sequence; - outerJoin(sequence:Sequence, join:JoinFunction):Sequence; - eqJoin(leftAttribute:string, rightSequence:Sequence, index?:Index):Sequence; - eqJoin(leftAttribute:ExpressionFunction, rightSequence:Sequence, index?:Index):Sequence; - zip():Sequence; + // Join + // these return left, right + innerJoin(sequence: Sequence, join: JoinFunction): Sequence; + outerJoin(sequence: Sequence, join: JoinFunction): Sequence; + eqJoin(leftAttribute: string, rightSequence: Sequence, index?: Index): Sequence; + eqJoin(leftAttribute: ExpressionFunction, rightSequence: Sequence, index?: Index): Sequence; + zip(): Sequence; - // Transform - map(transform:ExpressionFunction):Sequence; - withFields(...selectors:any[]):Sequence; - concatMap(transform:ExpressionFunction):Sequence; - orderBy(...keys:string[]):Sequence; - orderBy(...sorts:Sort[]):Sequence; - skip(n:number):Sequence; - limit(n:number):Sequence; - slice(start:number, end?:number):Sequence; - nth(n:number):Expression; - indexesOf(obj:any):Sequence; - isEmpty():Expression; - union(sequence:Sequence):Sequence; - sample(n:number):Sequence; + // Transform + map(transform: ExpressionFunction): Sequence; + withFields(...selectors: any[]): Sequence; + concatMap(transform: ExpressionFunction): Sequence; + orderBy(...keys: string[]): Sequence; + orderBy(...sorts: Sort[]): Sequence; + skip(n: number): Sequence; + limit(n: number): Sequence; + slice(start: number, end?: number): Sequence; + nth(n: number): Expression; + indexesOf(obj: any): Sequence; + isEmpty(): Expression; + union(sequence: Sequence): Sequence; + sample(n: number): Sequence; - // Aggregate - reduce(r:ReduceFunction, base?:any):Expression; - count():Expression; - distinct():Sequence; - groupedMapReduce(group:ExpressionFunction, map:ExpressionFunction, reduce:ReduceFunction, base?:any):Sequence; - groupBy(...aggregators:Aggregator[]):Expression; // TODO: reduction object - contains(prop:string):Expression; + // Aggregate + reduce(r: ReduceFunction, base?: any): Expression; + count(): Expression; + distinct(): Sequence; + groupedMapReduce(group: ExpressionFunction, map: ExpressionFunction, reduce: ReduceFunction, base?: any): Sequence; + groupBy(...aggregators: Aggregator[]): Expression; // TODO: reduction object + contains(prop: string): Expression; - // Manipulation - pluck(...props:string[]):Sequence; - without(...props:string[]):Sequence; - } + // Manipulation + pluck(...props: string[]): Sequence; + without(...props: string[]): Sequence; + } - interface ExpressionFunction { - (doc:Expression):Expression; - } + interface ExpressionFunction { + (doc: Expression): Expression; + } - interface JoinFunction { - (left:Expression, right:Expression):Expression; - } + interface JoinFunction { + (left: Expression, right: Expression): Expression; + } - interface ReduceFunction { - (acc:Expression, val:Expression):Expression; - } + interface ReduceFunction { + (acc: Expression, val: Expression): Expression; + } - interface InsertOptions { - upsert: boolean; // true - durability: string; // 'soft' - return_vals: boolean; // false - } + interface InsertOptions { + upsert: boolean; // true + durability: string; // 'soft' + return_vals: boolean; // false + } - interface UpdateOptions { - non_atomic: boolean; - durability: string; // 'soft' - return_vals: boolean; // false - } + interface UpdateOptions { + non_atomic: boolean; + durability: string; // 'soft' + return_vals: boolean; // false + } - interface WriteResult { - inserted: number; - replaced: number; - unchanged: number; - errors: number; - deleted: number; - skipped: number; - first_error: Error; - generated_keys: string[]; // only for insert - } + interface WriteResult { + inserted: number; + replaced: number; + unchanged: number; + errors: number; + deleted: number; + skipped: number; + first_error: Error; + generated_keys: string[]; // only for insert + } - interface JoinResult { - left:any; - right:any; - } + interface JoinResult { + left: any; + right: any; + } - interface CreateResult { - created: number; - } + interface CreateResult { + created: number; + } - interface DropResult { - dropped: number; - } + interface DropResult { + dropped: number; + } - interface Index { - index: string; - left_bound?: string; // 'closed' - right_bound?: string; // 'open' - } + interface Index { + index: string; + left_bound?: string; // 'closed' + right_bound?: string; // 'open' + } - interface Expression extends Writeable, Operation { - (prop:string):Expression; - merge(query:Expression):Expression; - append(prop:string):Expression; - contains(prop:string):Expression; + interface Expression extends Writeable, Operation { + (prop: string): Expression; + merge(query: Expression): Expression; + append(prop: string): Expression; + contains(prop: string): Expression; - and(b:boolean):Expression; - or(b:boolean):Expression; - eq(v:any):Expression; - ne(v:any):Expression; - not():Expression; + and(b: boolean): Expression; + or(b: boolean): Expression; + eq(v: any): Expression; + ne(v: any): Expression; + not(): Expression; - gt(value:T):Expression; - ge(value:T):Expression; - lt(value:T):Expression; - le(value:T):Expression; + gt(value: T): Expression; + ge(value: T): Expression; + lt(value: T): Expression; + le(value: T): Expression; - add(n:number):Expression; - sub(n:number):Expression; - mul(n:number):Expression; - div(n:number):Expression; - mod(n:number):Expression; + add(n: number): Expression; + sub(n: number): Expression; + mul(n: number): Expression; + div(n: number): Expression; + mod(n: number): Expression; - hasFields(...fields:string[]):Expression; + hasFields(...fields: string[]): Expression; - default(value:T):Expression; - } + default(value: T): Expression; + } - interface Operation { - run(conn:Connection, cb?:(err:Error, result:T)=>void):Promise; - } + interface Operation { + run(conn: Connection, cb?: (err: Error, result: T) => void): Promise; + } - interface Aggregator {} - interface Sort {} + interface Aggregator { } + interface Sort { } - interface Time {} + interface Time { } - // http://www.rethinkdb.com/api/#js - // TODO control structures + // http://www.rethinkdb.com/api/#js + // TODO control structures } From 317be6bc69da5f69b9517f1ff4c7908745dd5592 Mon Sep 17 00:00:00 2001 From: Alex Gorbatchev Date: Mon, 26 Sep 2016 19:59:32 -0700 Subject: [PATCH 019/554] [rethinkdb] Adds types to Cursor methods --- rethinkdb/rethinkdb.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/rethinkdb/rethinkdb.d.ts b/rethinkdb/rethinkdb.d.ts index dc251b2a8e..7babd42fe2 100644 --- a/rethinkdb/rethinkdb.d.ts +++ b/rethinkdb/rethinkdb.d.ts @@ -36,10 +36,15 @@ declare module "rethinkdb" { export class Cursor { hasNext(): boolean; each(cb: (err: Error, row: any) => void, done?: () => void): void; + each(cb: (err: Error, row: T) => void, done?: () => void): void; each(cb: (err: Error, row: any) => boolean, done?: () => void): void; // returning false stops iteration + each(cb: (err: Error, row: T) => boolean, done?: () => void): void; // returning false stops iteration next(cb: (err: Error, row: any) => void): void; + next(cb: (err: Error, row: T) => void): void; toArray(cb: (err: Error, rows: any[]) => void): void; + toArray(cb: (err: Error, rows: T[]) => void): void; toArray(): Promise; + toArray(): Promise; close(cb: (err: Error) => void): void; close(): Promise; } From b5979947c9bec28a35a1c4189ec21cea12d5dc3d Mon Sep 17 00:00:00 2001 From: "Dmitry A. Efimenko" Date: Mon, 26 Sep 2016 20:45:56 -0700 Subject: [PATCH 020/554] webpack - HotModuleReplacementPlugin has opts arg --- webpack/webpack.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webpack/webpack.d.ts b/webpack/webpack.d.ts index 96a7c710df..42dbc81e05 100644 --- a/webpack/webpack.d.ts +++ b/webpack/webpack.d.ts @@ -404,7 +404,7 @@ declare module "webpack" { } interface HotModuleReplacementPluginStatic { - new(): Plugin; + new(options?: any): Plugin; } interface ExtendedAPIPluginStatic { From 3a517142892532ae628f98d23990742bf212e34f Mon Sep 17 00:00:00 2001 From: stonio Date: Tue, 27 Sep 2016 09:55:51 +0200 Subject: [PATCH 021/554] [openlayers] forEachFeatureAtPixel can return a value See doc http://openlayers.org/en/latest/apidoc/ol.Map.html#forEachFeatureAtPixel --- openlayers/openlayers.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openlayers/openlayers.d.ts b/openlayers/openlayers.d.ts index 0b9e1b41f4..36026fa70d 100644 --- a/openlayers/openlayers.d.ts +++ b/openlayers/openlayers.d.ts @@ -2131,7 +2131,7 @@ declare namespace ol { * @param ref2 Value to use as this when executing layerFilter. * @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value. */ - forEachFeatureAtPixel(pixel: ol.Pixel, callback: (feature: ol.Feature, layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): void; + forEachFeatureAtPixel(pixel: ol.Pixel, callback: (feature: ol.Feature, layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): any; /** * Detect layers that have a color value at a pixel on the viewport, and execute a callback with each matching layer. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. From 6aff001e47fada0f16768ee435ddcc9eb7c521c1 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 27 Sep 2016 09:23:13 +0100 Subject: [PATCH 022/554] Update react.d.ts Added myself as an author so I get notifications of PRs / updates from GitHub. --- react/react.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react/react.d.ts b/react/react.d.ts index 2f762e0974..c13cdac082 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -1,6 +1,6 @@ // Type definitions for React v0.14 // Project: http://facebook.github.io/react/ -// Definitions by: Asana , AssureSign , Microsoft +// Definitions by: Asana , AssureSign , Microsoft , John Reilly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace __React { From f70bcf9a0ef640915ad4324b23396f28e2803ddc Mon Sep 17 00:00:00 2001 From: Christian Kittelmann Date: Tue, 27 Sep 2016 12:54:43 +0200 Subject: [PATCH 023/554] vue: fixed definition for activate() in ComponentOption --- vue/vue-tests.ts | 5 +++++ vue/vue.d.ts | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/vue/vue-tests.ts b/vue/vue-tests.ts index 48d8d91683..a15c3e49c1 100644 --- a/vue/vue-tests.ts +++ b/vue/vue-tests.ts @@ -88,6 +88,11 @@ namespace TestGlobalAPI { }, init: function() {} }); + Vue.component("component", { + activate: function(callback: Function) { + callback(); + } + }); var transition = Vue.transition("transition"); Vue.transition("transition", transition); Vue.transition("transition", { diff --git a/vue/vue.d.ts b/vue/vue.d.ts index a335ee63d1..d65a50da63 100644 --- a/vue/vue.d.ts +++ b/vue/vue.d.ts @@ -96,7 +96,7 @@ declare namespace vuejs { detached?(): void; beforeDestroy?(): void; destroyed?(): void; - activate?(): void; + activate?(callback: Function): void; directives?: { [key: string]: (DirectiveOption | Function) }; elementDirectives?: { [key: string]: (DirectiveOption | Function) }; filters?: { [key: string]: (Function | FilterOption) }; From 29a2eb800b4cb7ecc5218fd222001c641bdb8258 Mon Sep 17 00:00:00 2001 From: Passakorn Suppakityothin Date: Tue, 27 Sep 2016 17:56:23 +0700 Subject: [PATCH 024/554] Fix error that came using typescript 2 This error come when try compile with typescript 2 kue.d.ts(13,3): error TS2440: Import declaration conflicts with local declaration of 'redis' --- kue/kue.d.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/kue/kue.d.ts b/kue/kue.d.ts index baca094200..ee3571db0d 100644 --- a/kue/kue.d.ts +++ b/kue/kue.d.ts @@ -10,7 +10,7 @@ declare module "kue" { import events = require('events'); import express = require('express'); - import redis = require('redis'); + import redisClientFactory = require('redis'); export class Queue extends events.EventEmitter { name: string; @@ -18,7 +18,7 @@ declare module "kue" { promoter: any; workers: Worker[]; shuttingDown: boolean; - client: redis.RedisClient; + client: redisClientFactory.RedisClient; testMode: TestMode; static singleton: Queue; @@ -63,7 +63,7 @@ declare module "kue" { public id: number; public type: string; public data: any; - public client: redis.RedisClient; + public client: redisClientFactory.RedisClient; private _max_attempts; static priorities: Priorities; @@ -109,7 +109,7 @@ declare module "kue" { class Worker extends events.EventEmitter { queue: Queue; type: string; - client: redis.RedisClient; + client: redisClientFactory.RedisClient; job: Job; constructor(queue: Queue, type: string); @@ -127,10 +127,10 @@ declare module "kue" { interface Redis { configureFactory(options: Object, queue: Queue): void; - createClient(): redis.RedisClient; - createClientFactory(options: Object): redis.RedisClient; - client(): redis.RedisClient; - pubsubClient(): redis.RedisClient; + createClient(): redisClientFactory.RedisClient; + createClientFactory(options: Object): redisClientFactory.RedisClient; + client(): redisClientFactory.RedisClient; + pubsubClient(): redisClientFactory.RedisClient; reset(): void; } From 262f69018bce7a7a11bfbd0bc663c29cd501bb6d Mon Sep 17 00:00:00 2001 From: Erik Mogensen Date: Tue, 27 Sep 2016 13:48:39 +0200 Subject: [PATCH 025/554] path can be string or a hash of options As per http://restify.com/#client-api it states: > Note that all further documentation refers to the "short-hand" > form of methods like get/put/del which take a string path. You > can also pass in an object to any of those methods with extra > params (notably headers): So the path can be either a string or a hash of options. --- restify/restify.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/restify/restify.d.ts b/restify/restify.d.ts index 65b3f44d47..a1b933f419 100644 --- a/restify/restify.d.ts +++ b/restify/restify.d.ts @@ -470,12 +470,12 @@ declare module "restify" { } interface Client { - get: (path: string, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - head: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any; - post: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - put: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - patch: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - del: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any; + get: (opts: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + head: (opts: any, callback?: (err: any, req: Request, res: Response) => any) => any; + post: (opts: any, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + put: (opts: any, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + patch: (opts: any, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + del: (opts: any, callback?: (err: any, req: Request, res: Response) => any) => any; basicAuth: (username: string, password: string) => any; } From 1e7454173b2d2cf76545b361456df7fb42683ce0 Mon Sep 17 00:00:00 2001 From: ryutamaki Date: Tue, 27 Sep 2016 23:17:03 +0900 Subject: [PATCH 026/554] Add CognitoIdentity into aws-sdk --- aws-sdk/aws-sdk.d.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 2a92a4bcc4..d30b3af305 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -22,6 +22,27 @@ declare module "aws-sdk" { constructor(profile: string); } + export module CognitoIdentity { + export interface CognitoIdentityCredentialsParams { + IdentityPoolId?: string; + AccountId?: string; + Logins?: {[k: string]: any}; + + RoleArn?: string; + RoleSessionName?: string; + WebIdentityToken?: string; + ProviderId?: string; + Policy?: string; + DurationSeconds?: number; + + IdentityId?: string; + } + } + + export class CognitoIdentityCredentials extends Credentials { + constructor(params: CognitoIdentity.CognitoIdentityCredentialsParams); + } + export interface Logger { write?: (chunk: any, encoding?: string, callback?: () => void) => void; log?: (...messages: any[]) => void; From 1545f5cd9193d38e465637ad35d38ba620a007af Mon Sep 17 00:00:00 2001 From: Mykhailo Stadnyk Date: Tue, 27 Sep 2016 22:46:12 +0300 Subject: [PATCH 027/554] Font advanced config options added (for v2.0.6+) --- canvas-gauges/canvas-gauges-tests.ts | 6 ++++-- canvas-gauges/canvas-gauges.d.ts | 14 +++++++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/canvas-gauges/canvas-gauges-tests.ts b/canvas-gauges/canvas-gauges-tests.ts index d0f04e1082..015bdfd7e2 100644 --- a/canvas-gauges/canvas-gauges-tests.ts +++ b/canvas-gauges/canvas-gauges-tests.ts @@ -8,10 +8,12 @@ import { } from 'canvas-gauges'; let linearOptions: LinearGaugeOptions = { - renderTo: document.createElement('canvas') + renderTo: document.createElement('canvas'), + fontNumbersStyle: 'italic' }; let radialOptions: RadialGaugeOptions = { - renderTo: 'gauge-id' + renderTo: 'gauge-id', + fontNumbersWeight: 'bold' }; new LinearGauge(linearOptions); diff --git a/canvas-gauges/canvas-gauges.d.ts b/canvas-gauges/canvas-gauges.d.ts index 2b67c7f76f..b330726f55 100644 --- a/canvas-gauges/canvas-gauges.d.ts +++ b/canvas-gauges/canvas-gauges.d.ts @@ -4,6 +4,10 @@ // Definitions: https://github.com/Mikhus/DefinitelyTyped declare namespace CanvasGauges { + export type FontStyle = 'normal' | 'italic' | 'oblique'; + export type FontWeight = 'normal' | 'bold' | 'bolder' | 'lighter' | + '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'; + export type RenderTarget = string|HTMLElement; export interface AnimationRule { @@ -86,7 +90,15 @@ declare namespace CanvasGauges { fontTitleSize?: number, fontValueSize?: number, fontUnitsSize?: number, - fontNumbersSize?: number + fontNumbersSize?: number, + fontTitleStyle?: FontStyle, + fontValueStyle?: FontStyle, + fontUnitsStyle?: FontStyle, + fontNumbersStyle?: FontStyle, + fontTitleWeight?: FontWeight, + fontValueWeight?: FontWeight, + fontUnitsWeight?: FontWeight, + fontNumbersWeight?: FontWeight } export interface RadialGaugeOptions extends GenericOptions { From fd8fdb5cf992e09f0a12da758c1099bcba75cf86 Mon Sep 17 00:00:00 2001 From: Frank Gambino Date: Tue, 27 Sep 2016 18:04:58 -0400 Subject: [PATCH 028/554] Add missing slider parameters --- flexSlider/flexSlider.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/flexSlider/flexSlider.d.ts b/flexSlider/flexSlider.d.ts index c8fa3f949c..276bb35e84 100644 --- a/flexSlider/flexSlider.d.ts +++ b/flexSlider/flexSlider.d.ts @@ -78,10 +78,10 @@ interface FlexSliderOptions { // Callback API start?: (slider: SliderObject) => any; //Callback: function(slider) - Fires when the slider loads the first slide before?: (slider: SliderObject) => any; //Callback: function(slider) - Fires asynchronously with each slider animation - after?: () => any; //Callback: function(slider) - Fires after each slider animation completes - end?: () => any; //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous) - added?: () => any; //{NEW} Callback: function(slider) - Fires after a slide is added - removed?: () => any; + after?: (slider: SliderObject) => any; //Callback: function(slider) - Fires after each slider animation completes + end?: (slider: SliderObject) => any; //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous) + added?: (slider: SliderObject) => any; //{NEW} Callback: function(slider) - Fires after a slide is added + removed?: (slider: SliderObject) => any; } From dc0093e464a1a31a0659b776daee83e68a7320df Mon Sep 17 00:00:00 2001 From: Vipul Shekhawat Date: Tue, 27 Sep 2016 16:03:49 -0700 Subject: [PATCH 029/554] Add backspaceToRemoveMessage prop --- react-select/react-select.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/react-select/react-select.d.ts b/react-select/react-select.d.ts index 701d5efc4a..8011122fed 100644 --- a/react-select/react-select.d.ts +++ b/react-select/react-select.d.ts @@ -87,6 +87,12 @@ declare namespace ReactSelect { * @default true */ backspaceRemoves?: boolean; + /** + * Message to use for screenreaders to press backspace to remove the current item + * {label} is replaced with the item label + * @default "Press backspace to remove..." + */ + backspaceToRemoveMessage?: string; /** * CSS className for the outer element */ From 4c73343ec113a863b7c66f0f1e8e2a1e435c3eaf Mon Sep 17 00:00:00 2001 From: Erik Mogensen Date: Wed, 28 Sep 2016 12:36:05 +0200 Subject: [PATCH 030/554] fixup! path can be string or a hash of options --- restify/restify.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/restify/restify.d.ts b/restify/restify.d.ts index a1b933f419..eb4f5b5702 100644 --- a/restify/restify.d.ts +++ b/restify/restify.d.ts @@ -470,24 +470,24 @@ declare module "restify" { } interface Client { - get: (opts: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - head: (opts: any, callback?: (err: any, req: Request, res: Response) => any) => any; - post: (opts: any, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - put: (opts: any, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - patch: (opts: any, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - del: (opts: any, callback?: (err: any, req: Request, res: Response) => any) => any; + get: (opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + head: (opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response) => any) => any; + post: (opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + put: (opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + patch: (opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + del: (opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response) => any) => any; basicAuth: (username: string, password: string) => any; } interface HttpClient extends Client { - get: (path?: any, callback?: Function) => any; - head: (path?:any, callback?: Function) => any; - post: (opts?: any, callback?: Function) => any; - put: (opts?: any, callback?: Function) => any; - patch: (opts?: any, callback?: Function) => any; - del: (opts?: any, callback?: Function) => any; + get: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + head: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + post: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + put: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + patch: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + del: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; } - + interface ThrottleOptions { burst?: number; rate?: number; From 27986da0aa5f78c596bd8068b3e617b9c55b7137 Mon Sep 17 00:00:00 2001 From: Chen Zhutian Date: Wed, 28 Sep 2016 20:24:41 +0800 Subject: [PATCH 031/554] add request.body (#11395) * add request.body * Update koa-bodyparser.d.ts According to the documentation of `koa-bodyparser`: ```javascript // the parsed body will store in this.request.body // if nothing was parsed, body will be an empty object {} ctx.body = ctx.request.body; ``` Therefore the `body` property will exit in the `request` object. Changing the `body` property from optional to required can also fix the conflict problem in Koa's declaration file: ```ts class Koa extend Request, Response {} ``` --- koa-bodyparser/koa-bodyparser.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/koa-bodyparser/koa-bodyparser.d.ts b/koa-bodyparser/koa-bodyparser.d.ts index f8e1b25aae..0daf7cdb2a 100644 --- a/koa-bodyparser/koa-bodyparser.d.ts +++ b/koa-bodyparser/koa-bodyparser.d.ts @@ -18,6 +18,11 @@ declare module "koa-bodyparser" { import * as Koa from "koa"; + module "koa" { + interface Request { + body: any; + } + } function bodyParser(opts?: { /** From 02aed91b3d7e1b0d4226609ac2453f8555491206 Mon Sep 17 00:00:00 2001 From: Denis Date: Wed, 28 Sep 2016 08:27:39 -0400 Subject: [PATCH 032/554] Implement tilebelt definition (#11495) --- tilebelt/tilebelt-tests.ts | 29 ++++++ tilebelt/tilebelt.d.ts | 189 +++++++++++++++++++++++++++++++++++++ 2 files changed, 218 insertions(+) create mode 100644 tilebelt/tilebelt-tests.ts create mode 100644 tilebelt/tilebelt.d.ts diff --git a/tilebelt/tilebelt-tests.ts b/tilebelt/tilebelt-tests.ts new file mode 100644 index 0000000000..90c0923f36 --- /dev/null +++ b/tilebelt/tilebelt-tests.ts @@ -0,0 +1,29 @@ +/// +import * as tilebelt from 'tilebelt' + +const lon = 30.5 +const lat = 50.5 +const z = 15 +const tile = [5, 10, 10] +const tiles = [ + [0, 0, 5], + [0, 1, 5], + [1, 1, 5], + [1, 0, 5] +] +const quadkey = '00001033' +const bbox = [ -178.24, 84.70, -177.89, 84.73 ] + +tilebelt.tileToQuadkey(tile) +tilebelt.tileToBBOX(tile) +tilebelt.tileToGeoJSON(tile) +tilebelt.getParent(tile) +tilebelt.getSiblings(tile) +tilebelt.tileToQuadkey(tile) +tilebelt.pointToTile(lon, lat, z) +tilebelt.quadkeyToTile(quadkey) +tilebelt.bboxToTile(bbox) +tilebelt.pointToTileFraction(lon, lat, z) +tilebelt.hasSiblings(tile, tiles) +tilebelt.hasTile(tiles, tile) +tilebelt.tilesEqual(tiles[0], tiles[1]) \ No newline at end of file diff --git a/tilebelt/tilebelt.d.ts b/tilebelt/tilebelt.d.ts new file mode 100644 index 0000000000..c35a803228 --- /dev/null +++ b/tilebelt/tilebelt.d.ts @@ -0,0 +1,189 @@ +// Type definitions for tilebelt 1.0.1 +// Project: https://github.com/mapbox/tilebelt +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare const tilebelt: tilebelt.TilebeltStatic; +declare namespace tilebelt { + interface TilebeltStatic { + /** + * Get a geojson representation of a tile + * + * @name tileToGeoJSON + * @param {Array} tile + * @returns {Feature} + * @example + * var poly = tileToGeoJSON([5, 10, 10]) + * //=poly + */ + tileToGeoJSON(tile: Array): GeoJSON.Feature + + /** + * Get the bbox of a tile + * + * @name tileToBBOX + * @param {Array} tile + * @returns {Array} bbox + * @example + * var bbox = tileToBBOX([5, 10, 10]) + * //=bbox + */ + tileToBBOX(tile: Array): Array + + /** + * Get the tile for a point at a specified zoom level + * + * @name pointToTile + * @param {number} lon + * @param {number} lat + * @param {number} z + * @returns {Array} tile + * @example + * var tile = pointToTile(1, 1, 20) + * //=tile + */ + pointToTile(lon: number, lat: number, z: number): Array + + /** + * Get the 4 tiles one zoom level higher + * + * @name getChildren + * @param {Array} tile + * @returns {Array>} tiles + * @example + * var tiles = getChildren([5, 10, 10]) + * //=tiles + */ + getChildren(tile: Array): Array> + + /** + * Get the tile one zoom level lower + * + * @name getParent + * @param {Array} tile + * @returns {Array} tile + * @example + * var tile = getParent([5, 10, 10]) + * //=tile + */ + getParent(tile: Array): Array + + /** + * Get the 3 sibling tiles for a tile + * + * @name getSiblings + * @param {Array} tile + * @returns {Array>} tiles + * @example + * var tiles = getSiblings([5, 10, 10]) + * //=tiles + */ + getSiblings(tile: Array): Array> + + /** + * Check to see if an array of tiles contains a tiles siblings + * + * @name hasSiblings + * @param {Array} tile + * @param {Array>} tiles + * @returns {boolean} + * @example + * var tiles = [ + * [0, 0, 5], + * [0, 1, 5], + * [1, 1, 5], + * [1, 0, 5] + * ] + * hasSiblings([0, 0, 5], tiles) + * //=boolean + */ + hasSiblings(tile: Array, tiles: Array>): boolean + + /** + * Check to see if an array of tiles contains a particular tile + * + * @name hasTile + * @param {Array>} tiles + * @param {Array} tile + * @returns {boolean} + * @example + * var tiles = [ + * [0, 0, 5], + * [0, 1, 5], + * [1, 1, 5], + * [1, 0, 5] + * ] + * hasTile(tiles, [0, 0, 5]) + * //=boolean + */ + hasTile(tiles: Array>, tile: Array): boolean + + /** + * Check to see if two tiles are the same + * + * @name tilesEqual + * @param {Array} tile1 + * @param {Array} tile2 + * @returns {boolean} + * @example + * tilesEqual([0, 1, 5], [0, 0, 5]) + * //=boolean + */ + tilesEqual(tile1: Array, tile2: Array): boolean + + /** + * Get the quadkey for a tile + * + * @name tileToQuadkey + * @param {Array} tile + * @returns {string} quadkey + * @example + * var quadkey = tileToQuadkey([0, 1, 5]) + * //=quadkey + */ + tileToQuadkey(tile: Array): string + + /** + * Get the tile for a quadkey + * + * @name quadkeyToTile + * @param {string} quadkey + * @returns {Array} tile + * @example + * var tile = quadkeyToTile('00001033') + * //=tile + */ + quadkeyToTile(quadkey: string): Array + + /** + * Get the smallest tile to cover a bbox + * + * @name bboxToTile + * @param {Array} bbox + * @returns {Array} tile + * @example + * var tile = bboxToTile([ -178, 84, -177, 85 ]) + * //=tile + */ + bboxToTile(bbox: Array): Array + + /** + * Get the precise fractional tile location for a point at a zoom level + * + * @name pointToTileFraction + * @param {number} lon + * @param {number} lat + * @param {number} z + * @returns {Array} tile fraction + * var tile = pointToTileFraction(30.5, 50.5, 15) + * //=tile + */ + pointToTileFraction(lon: number, lat: number, z: number): Array + } +} + +declare module "tilebelt" { + export = tilebelt +} \ No newline at end of file From 7b9c3257214af878d92693308cd7686cbe1f1384 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 28 Sep 2016 20:29:10 +0800 Subject: [PATCH 033/554] Add import test (#11476) --- validator/validator-tests.ts | 252 +++++++++++++++++++++++++++++++++++ 1 file changed, 252 insertions(+) diff --git a/validator/validator-tests.ts b/validator/validator-tests.ts index cc857121bb..fa2f72439f 100644 --- a/validator/validator-tests.ts +++ b/validator/validator-tests.ts @@ -2,6 +2,258 @@ import * as validator from 'validator'; + +/************************************************ +* * +* IMPORT TESTS * +* * +************************************************/ +import { + blacklist as blacklistFunc, + contains as containsFunc, + equals as equalsFunc, + escape as escapeFunc, + isAfter as isAfterFunc, + isAlpha as isAlphaFunc, + isAlphanumeric as isAlphanumericFunc, + isAscii as isAsciiFunc, + isBase64 as isBase64Func, + isBefore as isBeforeFunc, + isBoolean as isBooleanFunc, + isByteLength as isByteLengthFunc, + isCreditCard as isCreditCardFunc, + isCurrency as isCurrencyFunc, + isDataURI as isDataURIFunc, + isDate as isDateFunc, + isDecimal as isDecimalFunc, + isDivisibleBy as isDivisibleByFunc, + isEmail as isEmailFunc, + isFQDN as isFQDNFunc, + isFloat as isFloatFunc, + isFullWidth as isFullWidthFunc, + isHalfWidth as isHalfWidthFunc, + isHexColor as isHexColorFunc, + isHexadecimal as isHexadecimalFunc, + isIP as isIPFunc, + isISBN as isISBNFunc, + isISIN as isISINFunc, + isISO8601 as isISO8601Func, + isIn as isInFunc, + isInt as isIntFunc, + isJSON as isJSONFunc, + isLength as isLengthFunc, + isLowercase as isLowercaseFunc, + isMACAddress as isMACAddressFunc, + isMD5 as isMD5Func, + isMobilePhone as isMobilePhoneFunc, + isMongoId as isMongoIdFunc, + isMultibyte as isMultibyteFunc, + isNull as isNullFunc, + isNumeric as isNumericFunc, + isSurrogatePair as isSurrogatePairFunc, + isURL as isURLFunc, + isUUID as isUUIDFunc, + isUppercase as isUppercaseFunc, + isVariableWidth as isVariableWidthFunc, + isWhitelisted as isWhitelistedFunc, + ltrim as ltrimFunc, + matches as matchesFunc, + normalizeEmail as normalizeEmailFunc, + rtrim as rtrimFunc, + stripLow as stripLowFunc, + toBoolean as toBooleanFunc, + toDate as toDateFunc, + toFloat as toFloatFunc, + toInt as toIntFunc, + trim as trimFunc, + unescape as unescapeFunc, + whitelist as whitelistFunc, +} from 'validator' + +namespace import_tests { + let _blacklist = validator.blacklist; + _blacklist = blacklistFunc; + + let _contains = validator.contains; + _contains = containsFunc; + + let _equals = validator.equals; + _equals = equalsFunc; + + let _escape = validator.escape; + _escape = escapeFunc; + + let _isAfter = validator.isAfter; + _isAfter = isAfterFunc; + + let _isAlpha = validator.isAlpha; + _isAlpha = isAlphaFunc; + + let _isAlphanumeric = validator.isAlphanumeric; + _isAlphanumeric = isAlphanumericFunc; + + let _isAscii = validator.isAscii; + _isAscii = isAsciiFunc; + + let _isBase64 = validator.isBase64; + _isBase64 = isBase64Func; + + let _isBefore = validator.isBefore; + _isBefore = isBeforeFunc; + + let _isBoolean = validator.isBoolean; + _isBoolean = isBooleanFunc; + + let _isByteLength = validator.isByteLength; + _isByteLength = isByteLengthFunc; + + let _isCreditCard = validator.isCreditCard; + _isCreditCard = isCreditCardFunc; + + let _isCurrency = validator.isCurrency; + _isCurrency = isCurrencyFunc; + + let _isDataURI = validator.isDataURI; + _isDataURI = isDataURIFunc; + + let _isDate = validator.isDate; + _isDate = isDateFunc; + + let _isDecimal = validator.isDecimal; + _isDecimal = isDecimalFunc; + + let _isDivisibleBy = validator.isDivisibleBy; + _isDivisibleBy = isDivisibleByFunc; + + let _isEmail = validator.isEmail; + _isEmail = isEmailFunc; + + let _isFQDN = validator.isFQDN; + _isFQDN = isFQDNFunc; + + let _isFloat = validator.isFloat; + _isFloat = isFloatFunc; + + let _isFullWidth = validator.isFullWidth; + _isFullWidth = isFullWidthFunc; + + let _isHalfWidth = validator.isHalfWidth; + _isHalfWidth = isHalfWidthFunc; + + let _isHexColor = validator.isHexColor; + _isHexColor = isHexColorFunc; + + let _isHexadecimal = validator.isHexadecimal; + _isHexadecimal = isHexadecimalFunc; + + let _isIP = validator.isIP; + _isIP = isIPFunc; + + let _isISBN = validator.isISBN; + _isISBN = isISBNFunc; + + let _isISIN = validator.isISIN; + _isISIN = isISINFunc; + + let _isISO8601 = validator.isISO8601; + _isISO8601 = isISO8601Func; + + let _isIn = validator.isIn; + _isIn = isInFunc; + + let _isInt = validator.isInt; + _isInt = isIntFunc; + + let _isJSON = validator.isJSON; + _isJSON = isJSONFunc; + + let _isLength = validator.isLength; + _isLength = isLengthFunc; + + let _isLowercase = validator.isLowercase; + _isLowercase = isLowercaseFunc; + + let _isMACAddress = validator.isMACAddress; + _isMACAddress = isMACAddressFunc; + + let _isMD5 = validator.isMD5; + _isMD5 = isMD5Func; + + let _isMobilePhone = validator.isMobilePhone; + _isMobilePhone = isMobilePhoneFunc; + + let _isMongoId = validator.isMongoId; + _isMongoId = isMongoIdFunc; + + let _isMultibyte = validator.isMultibyte; + _isMultibyte = isMultibyteFunc; + + let _isNull = validator.isNull; + _isNull = isNullFunc; + + let _isNumeric = validator.isNumeric; + _isNumeric = isNumericFunc; + + let _isSurrogatePair = validator.isSurrogatePair; + _isSurrogatePair = isSurrogatePairFunc; + + let _isURL = validator.isURL; + _isURL = isURLFunc; + + let _isUUID = validator.isUUID; + _isUUID = isUUIDFunc; + + let _isUppercase = validator.isUppercase; + _isUppercase = isUppercaseFunc; + + let _isVariableWidth = validator.isVariableWidth; + _isVariableWidth = isVariableWidthFunc; + + let _isWhitelisted = validator.isWhitelisted; + _isWhitelisted = isWhitelistedFunc; + + let _ltrim = validator.ltrim; + _ltrim = ltrimFunc; + + let _matches = validator.matches; + _matches = matchesFunc; + + let _normalizeEmail = validator.normalizeEmail; + _normalizeEmail = normalizeEmailFunc; + + let _rtrim = validator.rtrim; + _rtrim = rtrimFunc; + + let _stripLow = validator.stripLow; + _stripLow = stripLowFunc; + + let _toBoolean = validator.toBoolean; + _toBoolean = toBooleanFunc; + + let _toDate = validator.toDate; + _toDate = toDateFunc; + + let _toFloat = validator.toFloat; + _toFloat = toFloatFunc; + + let _toInt = validator.toInt; + _toInt = toIntFunc; + + let _trim = validator.trim; + _trim = trimFunc; + + let _unescape = validator.unescape; + _unescape = unescapeFunc; + + let _whitelist = validator.whitelist; + _whitelist = whitelistFunc; +} + +/************************************************ +* * +* API TESTS * +* * +************************************************/ let any: any; // ************** From f597aadbe9227b84dcd231c0396d6a93d271621f Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 28 Sep 2016 20:29:27 +0800 Subject: [PATCH 034/554] [validator] Add new stuff which document not mentioned (#11498) * Add new stuff which document not mentioned * Add related test --- validator/validator-tests.ts | 10 ++++++++++ validator/validator.d.ts | 4 ++++ 2 files changed, 14 insertions(+) diff --git a/validator/validator-tests.ts b/validator/validator-tests.ts index fa2f72439f..a0ee4a4cbf 100644 --- a/validator/validator-tests.ts +++ b/validator/validator-tests.ts @@ -551,6 +551,16 @@ let any: any; result = validator.whitelist('sample', 'abc'); } +{ + let str: string; + str = validator.toString([123, 456, '123', '456', true, false]); +} + +{ + let ver: string; + ver = validator.version; +} + // ************** // * Extensions * // ************** diff --git a/validator/validator.d.ts b/validator/validator.d.ts index eb09d12b95..02e8eba732 100644 --- a/validator/validator.d.ts +++ b/validator/validator.d.ts @@ -213,6 +213,10 @@ declare namespace ValidatorJS { // remove characters that do not appear in the whitelist. The characters are used in a RegExp and so you will // need to escape some chars, e.g. whitelist(input, '\\[\\]'). whitelist(input: string, chars: string): string; + + toString(input: any | any[]): string; + + version: string; // ************** // * Extensions * From bbf7d433237a5e8eb455e74bbd561f614eea9f15 Mon Sep 17 00:00:00 2001 From: Samuel Marks Date: Wed, 28 Sep 2016 22:42:23 +1000 Subject: [PATCH 035/554] http.ServerRequest => http.IncomingMessage (#11500) --- acl/acl.d.ts | 2 +- applicationinsights/applicationinsights.d.ts | 8 ++++---- browser-sync/browser-sync.d.ts | 4 ++-- bufferstream/bufferstream.d.ts | 2 +- busboy/busboy-tests.ts | 2 +- express-serve-static-core/express-serve-static-core.d.ts | 2 +- formidable/formidable-tests.ts | 2 +- multiparty/multiparty-tests.ts | 2 +- multiparty/multiparty.d.ts | 2 +- on-headers/on-headers-tests.ts | 2 +- restify/restify.d.ts | 2 +- urlrouter/urlrouter.d.ts | 2 +- ws/ws-tests.ts | 2 +- 13 files changed, 17 insertions(+), 17 deletions(-) diff --git a/acl/acl.d.ts b/acl/acl.d.ts index d222f9ebb6..eaa728cb2c 100644 --- a/acl/acl.d.ts +++ b/acl/acl.d.ts @@ -20,7 +20,7 @@ declare module "acl" { type Callback = (err: Error) => any; type AnyCallback = (err: Error, obj: any) => any; type AllowedCallback = (err: Error, allowed: boolean) => any; - type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value; + type GetUserId = (req: http.IncomingMessage, res: http.ServerResponse) => Value; interface AclStatic { new (backend: Backend, logger: Logger, options: Option): Acl; diff --git a/applicationinsights/applicationinsights.d.ts b/applicationinsights/applicationinsights.d.ts index 96d5773fa5..45c89556a6 100644 --- a/applicationinsights/applicationinsights.d.ts +++ b/applicationinsights/applicationinsights.d.ts @@ -346,24 +346,24 @@ interface Client { * Log an incoming http request to your server. The request data will be tracked during the response "finish" event if it is successful or the request "error" * event if it fails. The request duration is automatically calculated as the timespan between when the trackRequest method was called, and when the response "finish" * or request "error" events were fired. - * @param request The http.ServerRequest object to track + * @param request The http.IncomingMessage object to track * @param response The http.ServerResponse object for this request * @param properties map[string, string] - additional data used to filter requests in the portal. Defaults to empty. */ - trackRequest(request: any /* http.ServerRequest */, response: any /* http.ServerResponse */, properties?: { + trackRequest(request: any /* http.IncomingMessage */, response: any /* http.ServerResponse */, properties?: { [key: string]: string; }): void; /** * Log an incoming http request to your server. The request data is tracked synchronously rather than waiting for the response "finish"" or request "error"" events. * Use this if you need your request telemetry to respect custom app insights operation and user context (for example if you set any appInsights.client.context.tags). - * @param request The http.ServerRequest object to track + * @param request The http.IncomingMessage object to track * @param response The http.ServerResponse object for this request * @param ellapsedMilliseconds The duration for this request. Defaults to 0. * @param properties map[string, string] - additional data used to filter requests in the portal. Defaults to empty. * @param error An error that was returned for this request if it was unsuccessful. Defaults to null. */ - trackRequestSync(request: any /*http.ServerRequest */, response: any /*http.ServerResponse */, ellapsedMilliseconds?: number, properties?: { + trackRequestSync(request: any /*http.IncomingMessage */, response: any /*http.ServerResponse */, ellapsedMilliseconds?: number, properties?: { [key: string]: string;}, error?: any) : void; /** diff --git a/browser-sync/browser-sync.d.ts b/browser-sync/browser-sync.d.ts index 00d234f958..54b42aff4a 100644 --- a/browser-sync/browser-sync.d.ts +++ b/browser-sync/browser-sync.d.ts @@ -288,11 +288,11 @@ declare module "browser-sync" { middleware?: MiddlewareHandler; ws: boolean; reqHeaders: (config: any) => Hash; - proxyRes: (res: http.ServerResponse, req: http.ServerRequest, next: Function) => any; + proxyRes: (res: http.ServerResponse, req: http.IncomingMessage, next: Function) => any; } interface MiddlewareHandler { - (req: http.ServerRequest, res: http.ServerResponse, next: Function): any; + (req: http.IncomingMessage, res: http.ServerResponse, next: Function): any; } interface PerRouteMiddleware { diff --git a/bufferstream/bufferstream.d.ts b/bufferstream/bufferstream.d.ts index ee115d0ab5..c43a716d4b 100644 --- a/bufferstream/bufferstream.d.ts +++ b/bufferstream/bufferstream.d.ts @@ -104,7 +104,7 @@ declare module 'bufferstream/postbuffer' { http client buffer */ - constructor(req: http.ServerRequest); + constructor(req: http.IncomingMessage); /* set a callback to get all post data from a http server request */ diff --git a/busboy/busboy-tests.ts b/busboy/busboy-tests.ts index 058b5c92d3..11e8b6c9ad 100644 --- a/busboy/busboy-tests.ts +++ b/busboy/busboy-tests.ts @@ -5,7 +5,7 @@ import * as Busboy from 'busboy'; import * as http from 'http'; import * as util from 'util'; -function serverFn(req: http.ServerRequest, res: http.ServerResponse) { +function serverFn(req: http.IncomingMessage, res: http.ServerResponse) { if (req.method === 'POST') { var busboy = new Busboy({ headers: req.headers }); busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { diff --git a/express-serve-static-core/express-serve-static-core.d.ts b/express-serve-static-core/express-serve-static-core.d.ts index 0371c2bb6a..648f1447a5 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -130,7 +130,7 @@ declare module "express-serve-static-core" { interface Errback { (err: Error): void; } - interface Request extends http.ServerRequest, Express.Request { + interface Request extends http.IncomingMessage, Express.Request { /** * Return request header. diff --git a/formidable/formidable-tests.ts b/formidable/formidable-tests.ts index a0f70a713c..4fdc5ba4cf 100644 --- a/formidable/formidable-tests.ts +++ b/formidable/formidable-tests.ts @@ -48,7 +48,7 @@ if (form.bytesReceived > 100) { if (form.bytesExpected > 100) { } -var req: http.ServerRequest; +var req: http.IncomingMessage; form.parse(req); form.parse(req, (err: any, fields: formidable.Fields, files: formidable.Files) => { diff --git a/multiparty/multiparty-tests.ts b/multiparty/multiparty-tests.ts index 47e6a62f71..e84320ca46 100644 --- a/multiparty/multiparty-tests.ts +++ b/multiparty/multiparty-tests.ts @@ -4,7 +4,7 @@ import multiparty = require('multiparty'); import http = require('http'); import util = require('util'); -http.createServer(function (req: http.ServerRequest, res: http.ServerResponse) { +http.createServer(function (req: http.IncomingMessage, res: http.ServerResponse) { if (req.url === '/upload' && req.method === 'POST') { var count = 0; var form = new multiparty.Form(); diff --git a/multiparty/multiparty.d.ts b/multiparty/multiparty.d.ts index a280c366f8..b0977ff034 100644 --- a/multiparty/multiparty.d.ts +++ b/multiparty/multiparty.d.ts @@ -18,7 +18,7 @@ declare module "multiparty" { * @param request * @param callback */ - parse(request: http.ServerRequest, callback?: (error: Error, fields: any, files: any) => any): void; + parse(request: http.IncomingMessage, callback?: (error: Error, fields: any, files: any) => any): void; } export interface File { diff --git a/on-headers/on-headers-tests.ts b/on-headers/on-headers-tests.ts index 11f33c4ef0..35b62764ed 100644 --- a/on-headers/on-headers-tests.ts +++ b/on-headers/on-headers-tests.ts @@ -6,7 +6,7 @@ import onHeaders = require('on-headers') http.createServer(onRequest) .listen(3000); -function onRequest(req: http.ServerRequest, res: http.ServerResponse) { +function onRequest(req: http.IncomingMessage, res: http.ServerResponse) { onHeaders(res, addPoweredBy); res.setHeader('Content-Type', 'text/plain') res.end('hello!'); diff --git a/restify/restify.d.ts b/restify/restify.d.ts index 65b3f44d47..5f6ca472b1 100644 --- a/restify/restify.d.ts +++ b/restify/restify.d.ts @@ -35,7 +35,7 @@ declare module "restify" { } } - interface Request extends http.ServerRequest { + interface Request extends http.IncomingMessage { /** * builds an absolute URI for the request. * @private diff --git a/urlrouter/urlrouter.d.ts b/urlrouter/urlrouter.d.ts index c7a741ac90..0a1fff0d4c 100644 --- a/urlrouter/urlrouter.d.ts +++ b/urlrouter/urlrouter.d.ts @@ -13,7 +13,7 @@ declare module "urlrouter" { namespace UrlRouterInternal { - interface ServerRequest extends http.ServerRequest { + interface ServerRequest extends http.IncomingMessage { params: any; } diff --git a/ws/ws-tests.ts b/ws/ws-tests.ts index 3c85d678cb..4afa12bfe8 100644 --- a/ws/ws-tests.ts +++ b/ws/ws-tests.ts @@ -66,7 +66,7 @@ var WebSocketServer = WebSocket.Server; info: { origin: string secure: boolean - req: http.ServerRequest + req: http.IncomingMessage } , callback: (res: boolean) => void ): void { From 7315e9e81faa9d6e940561f5b25a72762b9719e5 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 28 Sep 2016 20:44:55 +0800 Subject: [PATCH 036/554] [node] Add events for dgram (#11501) * Add events for dgram * Add tests for dgram * Correct dgram.RemoteInfo interface * Correct emit * Correct emit --- node/node-tests.ts | 88 +++++++++++++++++++++++++++++++++++++++++----- node/node.d.ts | 45 +++++++++++++++++++++++- 2 files changed, 124 insertions(+), 9 deletions(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index 30ea4bcaa3..623d31c1f9 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -659,14 +659,86 @@ namespace tty_tests { //////////////////////////////////////////////////// namespace dgram_tests { - var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { - }); - ds.bind(); - ds.bind(41234); - var ai: dgram.AddressInfo = ds.address(); - ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { - }); - ds.send(new Buffer("hello"), 5000, "127.0.0.1"); + { + var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { + }); + ds.bind(); + ds.bind(41234); + var ai: dgram.AddressInfo = ds.address(); + ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { + }); + ds.send(new Buffer("hello"), 5000, "127.0.0.1"); + } + + { + let _socket: dgram.Socket; + let _boolean: boolean; + let _err: Error; + let _str: string; + let _rinfo: dgram.AddressInfo; + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + **/ + + _socket = _socket.addListener("close", () => {}); + _socket = _socket.addListener("error", (err) => { + let _err: Error = err; + }) + _socket = _socket.addListener("listening", () => {}); + _socket = _socket.addListener("message", (msg, rinfo) => { + let _msg: string = msg; + let _rinfo: dgram.AddressInfo = rinfo; + }) + + _boolean = _socket.emit("close") + _boolean = _socket.emit("error", _err); + _boolean = _socket.emit("listening"); + _boolean = _socket.emit("message", _str, _rinfo); + + _socket = _socket.on("close", () => {}); + _socket = _socket.on("error", (err) => { + let _err: Error = err; + }) + _socket = _socket.on("listening", () => {}); + _socket = _socket.on("message", (msg, rinfo) => { + let _msg: string = msg; + let _rinfo: dgram.AddressInfo = rinfo; + }) + + _socket = _socket.once("close", () => {}); + _socket = _socket.once("error", (err) => { + let _err: Error = err; + }) + _socket = _socket.once("listening", () => {}); + _socket = _socket.once("message", (msg, rinfo) => { + let _msg: string = msg; + let _rinfo: dgram.AddressInfo = rinfo; + }) + + _socket = _socket.prependListener("close", () => {}); + _socket = _socket.prependListener("error", (err) => { + let _err: Error = err; + }) + _socket = _socket.prependListener("listening", () => {}); + _socket = _socket.prependListener("message", (msg, rinfo) => { + let _msg: string = msg; + let _rinfo: dgram.AddressInfo = rinfo; + }) + + _socket = _socket.prependOnceListener("close", () => {}); + _socket = _socket.prependOnceListener("error", (err) => { + let _err: Error = err; + }) + _socket = _socket.prependOnceListener("listening", () => {}); + _socket = _socket.prependOnceListener("message", (msg, rinfo) => { + let _msg: string = msg; + let _rinfo: dgram.AddressInfo = rinfo; + }) + } } //////////////////////////////////////////////////// diff --git a/node/node.d.ts b/node/node.d.ts index 5b807cb5b2..3473ab3281 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1855,8 +1855,8 @@ declare module "dgram" { interface RemoteInfo { address: string; + family: string; port: number; - size: number; } interface AddressInfo { @@ -1894,6 +1894,49 @@ declare module "dgram" { dropMembership(multicastAddress: string, multicastInterface?: string): void; ref(): void; unref(): void; + + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + **/ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: string, rinfo: AddressInfo): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; } } From c48f9b3fd516a74fd38c51818b0eae6e98c63d38 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 28 Sep 2016 20:46:43 +0800 Subject: [PATCH 037/554] [node] Add events for tls.Server and tls.TLSSocket (#11502) * Add events for tls.Server * Add tests for tls.Server * Add tests for TLSSocket * Add events for TLSSocket --- node/node-tests.ts | 199 ++++++++++++++++++++++++++++++++++++++++++--- node/node.d.ts | 79 ++++++++++++++++++ 2 files changed, 268 insertions(+), 10 deletions(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index 623d31c1f9..433435ee13 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -558,17 +558,196 @@ namespace crypto_tests { ////////////////////////////////////////////////// namespace tls_tests { - var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", - }); - var blah = ctx.context; + { + var ctx: tls.SecureContext = tls.createSecureContext({ + key: "NOT REALLY A KEY", + cert: "SOME CERTIFICATE", + }); + var blah = ctx.context; - var connOpts: tls.ConnectionOptions = { - host: "127.0.0.1", - port: 55 - }; - var tlsSocket = tls.connect(connOpts); + var connOpts: tls.ConnectionOptions = { + host: "127.0.0.1", + port: 55 + }; + var tlsSocket = tls.connect(connOpts); + } + + { + let _server: tls.Server; + let _boolean: boolean; + let _func1 = function(err: Error, resp: Buffer){}; + let _func2 = function(err: Error, sessionData: any){}; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + **/ + + _server = _server.addListener("tlsClientError", (err, tlsSocket) => { + let _err: Error = err; + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + _server = _server.addListener("newSession", (sessionId, sessionData, callback) => { + let _sessionId: any = sessionId; + let _sessionData: any = sessionData; + let _func1 = callback; + }) + _server = _server.addListener("OCSPRequest", (certificate, issuer, callback) => { + let _certificate: Buffer = certificate; + let _issuer: Buffer = issuer; + let _callback: Function = callback; + }) + _server = _server.addListener("resumeSession", (sessionId, callback) => { + let _sessionId: any = sessionId; + let _func2 = callback; + }) + _server = _server.addListener("secureConnection", (tlsSocket) => { + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + + let _err: Error; + let _tlsSocket: tls.TLSSocket; + let _any: any; + let _func: Function; + let _buffer: Buffer; + _boolean = _server.emit("tlsClientError", _err, _tlsSocket); + _boolean = _server.emit("newSession", _any, _any, _func1); + _boolean = _server.emit("OCSPRequest", _buffer, _buffer, _func); + _boolean = _server.emit("resumeSession", _any, _func2); + _boolean = _server.emit("secureConnection", _tlsSocket); + + _server = _server.on("tlsClientError", (err, tlsSocket) => { + let _err: Error = err; + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + _server = _server.on("newSession", (sessionId, sessionData, callback) => { + let _sessionId: any = sessionId; + let _sessionData: any = sessionData; + let _func1 = callback; + }) + _server = _server.on("OCSPRequest", (certificate, issuer, callback) => { + let _certificate: Buffer = certificate; + let _issuer: Buffer = issuer; + let _callback: Function = callback; + }) + _server = _server.on("resumeSession", (sessionId, callback) => { + let _sessionId: any = sessionId; + let _func2 = callback; + }) + _server = _server.on("secureConnection", (tlsSocket) => { + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + + _server = _server.once("tlsClientError", (err, tlsSocket) => { + let _err: Error = err; + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + _server = _server.once("newSession", (sessionId, sessionData, callback) => { + let _sessionId: any = sessionId; + let _sessionData: any = sessionData; + let _func1 = callback; + }) + _server = _server.once("OCSPRequest", (certificate, issuer, callback) => { + let _certificate: Buffer = certificate; + let _issuer: Buffer = issuer; + let _callback: Function = callback; + }) + _server = _server.once("resumeSession", (sessionId, callback) => { + let _sessionId: any = sessionId; + let _func2 = callback; + }) + _server = _server.once("secureConnection", (tlsSocket) => { + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + + _server = _server.prependListener("tlsClientError", (err, tlsSocket) => { + let _err: Error = err; + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + _server = _server.prependListener("newSession", (sessionId, sessionData, callback) => { + let _sessionId: any = sessionId; + let _sessionData: any = sessionData; + let _func1 = callback; + }) + _server = _server.prependListener("OCSPRequest", (certificate, issuer, callback) => { + let _certificate: Buffer = certificate; + let _issuer: Buffer = issuer; + let _callback: Function = callback; + }) + _server = _server.prependListener("resumeSession", (sessionId, callback) => { + let _sessionId: any = sessionId; + let _func2 = callback; + }) + _server = _server.prependListener("secureConnection", (tlsSocket) => { + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + + _server = _server.prependOnceListener("tlsClientError", (err, tlsSocket) => { + let _err: Error = err; + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + _server = _server.prependOnceListener("newSession", (sessionId, sessionData, callback) => { + let _sessionId: any = sessionId; + let _sessionData: any = sessionData; + let _func1 = callback; + }) + _server = _server.prependOnceListener("OCSPRequest", (certificate, issuer, callback) => { + let _certificate: Buffer = certificate; + let _issuer: Buffer = issuer; + let _callback: Function = callback; + }) + _server = _server.prependOnceListener("resumeSession", (sessionId, callback) => { + let _sessionId: any = sessionId; + let _func2 = callback; + }) + _server = _server.prependOnceListener("secureConnection", (tlsSocket) => { + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + } + + { + let _TLSSocket: tls.TLSSocket; + let _boolean: boolean; + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + **/ + + _TLSSocket = _TLSSocket.addListener("OCSPResponse", (response) => { + let _response: Buffer = response; + }) + _TLSSocket = _TLSSocket.addListener("secureConnect", () => { }); + + let _buffer: Buffer; + _boolean = _TLSSocket.emit("OCSPResponse", _buffer); + _boolean = _TLSSocket.emit("secureConnect"); + + _TLSSocket = _TLSSocket.on("OCSPResponse", (response) => { + let _response: Buffer = response; + }) + _TLSSocket = _TLSSocket.on("secureConnect", () => { }); + + _TLSSocket = _TLSSocket.once("OCSPResponse", (response) => { + let _response: Buffer = response; + }) + _TLSSocket = _TLSSocket.once("secureConnect", () => { }); + + _TLSSocket = _TLSSocket.prependListener("OCSPResponse", (response) => { + let _response: Buffer = response; + }) + _TLSSocket = _TLSSocket.prependListener("secureConnect", () => { }); + + _TLSSocket = _TLSSocket.prependOnceListener("OCSPResponse", (response) => { + let _response: Buffer = response; + }) + _TLSSocket = _TLSSocket.prependOnceListener("secureConnect", () => { }); + } } //////////////////////////////////////////////////// diff --git a/node/node.d.ts b/node/node.d.ts index 3473ab3281..5c016af3fd 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2628,6 +2628,35 @@ declare module "tls" { * @returns {boolean} - Returns true on success, false otherwise. */ setMaxSendFragment(size: number): boolean; + + /** + * events.EventEmitter + * 1. OCSPResponse + * 2. secureConnect + **/ + addListener(event: string, listener: Function): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + + on(event: string, listener: Function): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; } export interface TlsOptions { @@ -2686,6 +2715,56 @@ declare module "tls" { }): void; maxConnections: number; connections: number; + + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + **/ + addListener(event: string, listener: Function): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; + emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + + on(event: string, listener: Function): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + once(event: string, listener: Function): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; } export interface ClearTextStream extends stream.Duplex { From ce70e15ee4639ce8648acfd4b0a81b021e4c7998 Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Wed, 28 Sep 2016 16:02:02 +0300 Subject: [PATCH 038/554] [react-router] Update getComponents signatures (#11319) Update `getComponent(s)` all over the place. See #9530 for more info. --- react-router/react-router.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 1a68cc89a5..321adf9bb7 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -169,8 +169,8 @@ declare namespace ReactRouter { path?: RoutePattern component?: RouteComponent components?: RouteComponents - getComponent?: (location: H.Location, cb: (error: any, component?: RouteComponent) => void) => void - getComponents?: (location: H.Location, cb: (error: any, components?: RouteComponents) => void) => void + getComponent?: (nextState: RouterState, cb: (error: any, component?: RouteComponent) => void) => void + getComponents?: (nextState: RouterState, cb: (error: any, components?: RouteComponents) => void) => void onEnter?: EnterHook onLeave?: LeaveHook indexRoute?: PlainRoute @@ -195,8 +195,8 @@ declare namespace ReactRouter { interface IndexRouteProps extends React.Props { component?: RouteComponent components?: RouteComponents - getComponent?: (location: H.Location, cb: (error: any, component?: RouteComponent) => void) => void - getComponents?: (location: H.Location, cb: (error: any, components?: RouteComponents) => void) => void + getComponent?: (nextState: RouterState, cb: (error: any, component?: RouteComponent) => void) => void + getComponents?: (nextState: RouterState, cb: (error: any, components?: RouteComponents) => void) => void onEnter?: EnterHook onLeave?: LeaveHook } From 3518ba75e124a9afae1f18df34043e4a982047eb Mon Sep 17 00:00:00 2001 From: Craig Boland Date: Wed, 28 Sep 2016 08:05:50 -0500 Subject: [PATCH 039/554] Updated jquery.dataTables for 1.10.7. (#11408) * Updated jquery.dataTables for 1.10.7. Version release notes: https://cdn.datatables.net/1.10.7/ * Added any() * Added i18n() Note: selector-modifier support currently exists with interface ObjectSelectorModifier. * Added strong variable typing in jquery.dataTables-tests.ts * For parameter 'def', replaced 'Object' data type with 'any' per TypeScript declaration file guidance. --- jquery.dataTables/jquery.dataTables-tests.ts | 5 +++++ jquery.dataTables/jquery.dataTables.d.ts | 18 +++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/jquery.dataTables/jquery.dataTables-tests.ts b/jquery.dataTables/jquery.dataTables-tests.ts index 6329861604..09014f39f4 100644 --- a/jquery.dataTables/jquery.dataTables-tests.ts +++ b/jquery.dataTables/jquery.dataTables-tests.ts @@ -311,6 +311,9 @@ $(document).ready(function () { var initSettings = dt.init(); + var i18n: string = dt.i18n('buttons.copy', 'Copy to clipboard'); + i18n = dt.i18n('select.rows', { _: '%d rows selected', 1: '1 row selected' }, 0); + var off = dt.off("event"); off = dt.off("event", function () { }); off.$(""); @@ -901,5 +904,7 @@ $(document).ready(function () { //#region "Methods-Util" + var util_1: boolean = dt.any(); + //#endregion "Methods-Util" }); diff --git a/jquery.dataTables/jquery.dataTables.d.ts b/jquery.dataTables/jquery.dataTables.d.ts index 459676f87d..70c72b8570 100644 --- a/jquery.dataTables/jquery.dataTables.d.ts +++ b/jquery.dataTables/jquery.dataTables.d.ts @@ -1,4 +1,4 @@ -// Type definitions for JQuery DataTables 1.10.6 +// Type definitions for JQuery DataTables 1.10.7 // Project: http://www.datatables.net // Definitions by: Kiarash Ghiaseddin , Omid Rad , Armin Sander // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -188,6 +188,17 @@ declare namespace DataTables { */ draw(reset?: boolean): DataTable; + /* + * Look up a language token that was defined in the DataTables' language initialisation object. + * + * @param token The language token to lookup from the language object. + * @param def The default value to use if the DataTables initialisation has not specified a value. + * @param numeric If handling numeric output, the number to be presented should be given in this parameter. If not numeric operator is required (for example button label text) this parameter is not required. + * + * @returns Resulting internationalised string. + */ + i18n(token: string, def: any | string, numeric?: number): string; + /* * Get the initialisation options used for the table. Since: DataTables 1.10.6 */ @@ -412,6 +423,11 @@ declare namespace DataTables { //#region "util-methods" interface UtilityMethods { + /* + * Get a boolean value to indicate if there are any entries in the API instance's result set (i.e. any data, selected rows, etc). + */ + any(): boolean; + /** * Concatenate two or more API instances together * From 3929fe1b6762a5380c717a52f296af3d55740ede Mon Sep 17 00:00:00 2001 From: AKFish Date: Wed, 28 Sep 2016 21:41:30 +0800 Subject: [PATCH 040/554] [HAPI] Add `IStrictSessionHandler` (#11523) * Fix #11519 --- hapi/hapi-8.2.0.d.ts | 8 ++++++-- hapi/hapi-tests-8.2.0.ts | 10 ++++++++++ hapi/hapi-tests.ts | 10 ++++++++++ hapi/hapi.d.ts | 8 ++++++-- 4 files changed, 32 insertions(+), 4 deletions(-) diff --git a/hapi/hapi-8.2.0.d.ts b/hapi/hapi-8.2.0.d.ts index ef81b4fba3..a789915965 100644 --- a/hapi/hapi-8.2.0.d.ts +++ b/hapi/hapi-8.2.0.d.ts @@ -300,8 +300,12 @@ declare module "hapi" { } export interface ISessionHandler { (request: Request, reply: IReply): void; + } + + export interface IStrictSessionHandler{ (request: Request, reply: IStrictReply): void; } + export interface IRequestHandler { (request: Request): T; } @@ -464,7 +468,7 @@ declare module "hapi" { }; /** an alternative location for the route handler option. */ - handler?: ISessionHandler | string | IRouteHandlerConfig; + handler?: ISessionHandler | IStrictSessionHandler | 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: */ @@ -834,7 +838,7 @@ declare module "hapi" { /** - 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; + handler: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; /** - additional route options.*/ config?: IRouteAdditionalConfigurationOptions; } diff --git a/hapi/hapi-tests-8.2.0.ts b/hapi/hapi-tests-8.2.0.ts index e26ce193bc..012e913432 100644 --- a/hapi/hapi-tests-8.2.0.ts +++ b/hapi/hapi-tests-8.2.0.ts @@ -124,5 +124,15 @@ server.route([{ } }]); +// Implict handler +server.route({ + method: 'GET', + path: '/hello6', + handler: function (request, reply) { + request.log('info', { route: '/hello' }, Date.now()); + reply('hello world'); + } +}); + // Start the server server.start(); diff --git a/hapi/hapi-tests.ts b/hapi/hapi-tests.ts index 3288618816..c33e934611 100644 --- a/hapi/hapi-tests.ts +++ b/hapi/hapi-tests.ts @@ -112,6 +112,16 @@ server.route([{ } }]); +// Implict handler +server.route({ + method: 'GET', + path: '/hello6', + handler: function (request, reply) { + request.log('info', { route: '/hello' }, Date.now()); + reply('hello world'); + } +}); + // config.validate parameters should be optional server.route([{ method: 'GET', diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index ff5e1d9fe8..9c01eb741d 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -330,8 +330,12 @@ declare module "hapi" { export interface ISessionHandler { (request: Request, reply: IReply): void; + } + + export interface IStrictSessionHandler { (request: Request, reply: IStrictReply): void; } + export interface IRequestHandler { (request: Request): T; } @@ -495,7 +499,7 @@ declare module "hapi" { }; /** an alternative location for the route handler option. */ - handler?: ISessionHandler | string | IRouteHandlerConfig; + handler?: ISessionHandler | IStrictSessionHandler | 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: */ @@ -894,7 +898,7 @@ declare module "hapi" { /** - 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; + handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; /** - additional route options.*/ config?: IRouteAdditionalConfigurationOptions; } From 351b4c7598c689337b8ce2c82543f902f8b30045 Mon Sep 17 00:00:00 2001 From: nkovacic Date: Wed, 28 Sep 2016 15:47:15 +0200 Subject: [PATCH 041/554] Added FileResizeOptions for the changed resize function call --- ng-file-upload/ng-file-upload-tests.ts | 12 +++++++++++- ng-file-upload/ng-file-upload.d.ts | 21 +++++++++++++++++---- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/ng-file-upload/ng-file-upload-tests.ts b/ng-file-upload/ng-file-upload-tests.ts index f7fdcf1015..ff3044977a 100644 --- a/ng-file-upload/ng-file-upload-tests.ts +++ b/ng-file-upload/ng-file-upload-tests.ts @@ -78,7 +78,17 @@ class UploadController { fileWithNewName = this.Upload.rename(files[0], "newName.jpg"); this.Upload - .resize(files[0], 1024, 1024, 0.7, 'image/jpeg', 0.9, true) + .resize(files[0], { + height: 1024, + width: 1024, + quality: 0.7, + ratio: 0.9, + centerCrop: true, + restoreExif: true, + resizeIf: (width, height) => { + return true; + } + }) .then((resizedFile) => { console.log(resizedFile); }); diff --git a/ng-file-upload/ng-file-upload.d.ts b/ng-file-upload/ng-file-upload.d.ts index 41b0331dbe..2700a5d206 100644 --- a/ng-file-upload/ng-file-upload.d.ts +++ b/ng-file-upload/ng-file-upload.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular File Upload 11.1.1 +// Type definitions for Angular File Upload 12.2.12 // Project: https://github.com/danialfarid/ng-file-upload // Definitions by: John Reilly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -92,6 +92,20 @@ declare namespace angular.angularFileUpload { ngfValidateForce?: boolean; } + interface ResizeIfFunction { + (width: number, height: number): boolean; + } + + interface FileResizeOptions { + centerCrop?: boolean; + height?: number; + ratio?: number; + resizeIf?: ResizeIfFunction; + restoreExif?: boolean; + quality?: number; + width?: number; + } + interface IUploadService { /** * Convert a single file or array of files to a single or array of @@ -166,7 +180,7 @@ declare namespace angular.angularFileUpload { * @param {string} newName * @return {File} */ - rename(file: File, newName: string): File; + rename(file: File, newName: string): Blob; /** * Resizes an image. Returns a promise * @@ -179,8 +193,7 @@ declare namespace angular.angularFileUpload { * @param {boolean} [centerCrop] * @return {angular.IPromise} */ - resize(file: File, width?: number, height?: number, quality?: number, type?: string, - ratio?: number | string, centerCrop?: boolean): angular.IPromise; + resize(file: File, options: FileResizeOptions): angular.IPromise; /** * Set the default values for ngf-select and ngf-drop directives * From 462850812b7b471d6d8d01223accb3ca282b8731 Mon Sep 17 00:00:00 2001 From: Maux Date: Wed, 28 Sep 2016 23:49:22 +1000 Subject: [PATCH 042/554] getEvent should not be set to void it should return a value (#11135) * getEvent should not be set to void it should return a value * Add type to getActionData for testing * pnotify Add type fpr notice styling and state * fix pnotify test * Remove Generics and replaces by return any * convert space tp tabs --- dhtmlxscheduler/dhtmlxscheduler.d.ts | 60 +++++++++++++------------- jquery.pnotify/jquery.pnotify-tests.ts | 4 +- jquery.pnotify/jquery.pnotify.d.ts | 14 +++--- 3 files changed, 37 insertions(+), 41 deletions(-) diff --git a/dhtmlxscheduler/dhtmlxscheduler.d.ts b/dhtmlxscheduler/dhtmlxscheduler.d.ts index 40123827ca..3f075861ab 100644 --- a/dhtmlxscheduler/dhtmlxscheduler.d.ts +++ b/dhtmlxscheduler/dhtmlxscheduler.d.ts @@ -3,12 +3,12 @@ // Definitions by: Maksim Kozhukh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface SchedulerCallback { (...args: any[]) : any } +interface SchedulerCallback { (...args: any[]): any } interface SchedulerFilterCallback { (id: string | number, event: any): boolean } -type SchedulerEventName ='onAfterEventDisplay'|'onAfterFolderToggle'|'onAfterLightbox'|'onAfterSchedulerResize'|'onBeforeCollapse'|'onBeforeDrag'|'onBeforeEventChanged'|'onBeforeEventCreated'|'onBeforeEventDelete'|'onBeforeEventDisplay'|'onBeforeEventDragIn'|'onBeforeEventDragOut'|'onBeforeExpand'|'onBeforeExternalDragIn'|'onBeforeFolderToggle'|'onBeforeLightbox'|'onBeforeSectionRender'|'onBeforeTodayDisplayed'|'onBeforeTooltip'|'onBeforeViewChange'|'onCellClick'|'onCellDblClick'|'onClearAll'|'onClick'|'onCollapse'|'onConfirmedBeforeEventDelete'|'onContextMenu'|'onDblClick'|'onDragEnd'|'onEmptyClick'|'onEventAdded'|'onEventCancel'|'onEventChanged'|'onEventCollision'|'onEventCopied'|'onEventCreated'|'onEventCut'|'onEventDeleted'|'onEventDrag'|'onEventDragIn'|'onEventDragOut'|'onEventDropOut'|'onEventIdChange'|'onEventLoading'|'onEventPasted'|'onEventSave'|'onExpand'|'onExternalDragIn'|'onLightbox'|'onLightboxButton'|'onLimitViolation'|'onLoadError'|'onLocationError'|'onMouseDown'|'onMouseMove'|'onOptionsLoad'|'onOptionsLoadFinal'|'onOptionsLoadStart'|'onSaveError'|'onScaleAdd'|'onScaleDblClick'|'onSchedulerReady'|'onSchedulerResize'|'onTemplatesReady'|'onTimelineCreated'|'onViewChange'|'onViewMoreClick'|'onXLE'|'onXLS'|'onXScaleClick'|'onXScaleDblClick'|'onYScaleClick'|'onYScaleDblClick'; +type SchedulerEventName = 'onAfterEventDisplay' | 'onAfterFolderToggle' | 'onAfterLightbox' | 'onAfterSchedulerResize' | 'onBeforeCollapse' | 'onBeforeDrag' | 'onBeforeEventChanged' | 'onBeforeEventCreated' | 'onBeforeEventDelete' | 'onBeforeEventDisplay' | 'onBeforeEventDragIn' | 'onBeforeEventDragOut' | 'onBeforeExpand' | 'onBeforeExternalDragIn' | 'onBeforeFolderToggle' | 'onBeforeLightbox' | 'onBeforeSectionRender' | 'onBeforeTodayDisplayed' | 'onBeforeTooltip' | 'onBeforeViewChange' | 'onCellClick' | 'onCellDblClick' | 'onClearAll' | 'onClick' | 'onCollapse' | 'onConfirmedBeforeEventDelete' | 'onContextMenu' | 'onDblClick' | 'onDragEnd' | 'onEmptyClick' | 'onEventAdded' | 'onEventCancel' | 'onEventChanged' | 'onEventCollision' | 'onEventCopied' | 'onEventCreated' | 'onEventCut' | 'onEventDeleted' | 'onEventDrag' | 'onEventDragIn' | 'onEventDragOut' | 'onEventDropOut' | 'onEventIdChange' | 'onEventLoading' | 'onEventPasted' | 'onEventSave' | 'onExpand' | 'onExternalDragIn' | 'onLightbox' | 'onLightboxButton' | 'onLimitViolation' | 'onLoadError' | 'onLocationError' | 'onMouseDown' | 'onMouseMove' | 'onOptionsLoad' | 'onOptionsLoadFinal' | 'onOptionsLoadStart' | 'onSaveError' | 'onScaleAdd' | 'onScaleDblClick' | 'onSchedulerReady' | 'onSchedulerResize' | 'onTemplatesReady' | 'onTimelineCreated' | 'onViewChange' | 'onViewMoreClick' | 'onXLE' | 'onXLS' | 'onXScaleClick' | 'onXScaleDblClick' | 'onYScaleClick' | 'onYScaleDblClick'; -interface SchedulerTemplates{ +interface SchedulerTemplates { /** * specifies the date in the header of the view * @param start the start date of the view @@ -458,7 +458,7 @@ interface SchedulerTemplates{ } -interface SchedulerConfigOptions{ +interface SchedulerConfigOptions { /** * 'says' to present the numbers of days in the Month view as clickable links that open the related day in the specified view */ @@ -477,12 +477,12 @@ interface SchedulerConfigOptions{ /** * specifies how to display the default error notification in case the XML data loading failed */ - ajax_error: string|boolean; + ajax_error: string | boolean; /** * 'says' to show multi-day events in the regular way (as one-day events are displayed) */ - all_timed: boolean|string; + all_timed: boolean | string; /** * sets the date format that will be used by the addEvent() method to parse the start_date, end_date properties in case they are specified as strings @@ -812,7 +812,7 @@ interface SchedulerConfigOptions{ /** * sets the height of the area that displays multi-day events */ - multi_day_height_limit: number|boolean; + multi_day_height_limit: number | boolean; /** * enables the possibility to render the same events in several sections of the Timeline or Units view @@ -942,12 +942,12 @@ interface SchedulerConfigOptions{ /** * enables/disables the touch support in the scheduler */ - touch: boolean|string; + touch: boolean | string; /** * defines the time period in milliseconds that is used to differ the long touch gesture from the scroll gesture */ - touch_drag: number|boolean; + touch_drag: number | boolean; /** * enables/disables prompting messages in the right top corner of the screen @@ -996,7 +996,7 @@ interface SchedulerConfigOptions{ } -interface SchedulerDateHelpers{ +interface SchedulerDateHelpers { add(origin: Date, count: number, unit: string): Date; copy(origin: Date): Date; @@ -1017,19 +1017,19 @@ interface SchedulerDateHelpers{ to_fixed(value: number): string; } -interface SchedulerHotkeys{ +interface SchedulerHotkeys { edit_save: number; edit_cancel: number; } -interface SchedulerLocaleDate{ +interface SchedulerLocaleDate { month_full: string[]; month_short: string[]; day_full: string[]; day_short: string[]; } -interface SchedulerLocaleLabels{ +interface SchedulerLocaleLabels { dhx_cal_today_button: string; day_tab: string; week_tab: string; @@ -1046,13 +1046,13 @@ interface SchedulerLocaleLabels{ section_time: string; } -interface SchedulerLocale{ +interface SchedulerLocale { date: SchedulerLocaleDate; labels: SchedulerLocaleLabels; } -interface SchedulerSizes{ +interface SchedulerSizes { /** * the height of day cells in the month view */ @@ -1124,14 +1124,14 @@ interface SchedulerSizes{ scroll_width: number; } -interface SchedulerEnterprise{ +interface SchedulerEnterprise { /** * Creates a new instance of Scheduler */ getSchedulerInstance(): SchedulerStatic; } -interface SchedulerStatic{ +interface SchedulerStatic { templates: SchedulerTemplates; config: SchedulerConfigOptions; date: SchedulerDateHelpers; @@ -1238,7 +1238,7 @@ interface SchedulerStatic{ * @param time_points an array [start_minute,end_minute,..,start_minute_N,end_minute_N],
where each pair sets a certain limit range. The array can have any number of
such pairs * @param items defines specific items of view(s) to block */ - blockTime(date: Date|number, time_points: any[], items?: any): void; + blockTime(date: Date | number, time_points: any[], items?: any): void; /** * calls an inner event @@ -1327,7 +1327,7 @@ interface SchedulerStatic{ * deletes the specified event * @param id the event's id */ - deleteEvent(id: string|number): void; + deleteEvent(id: string | number): void; /** * removes marking/blocking set by the addMarkedTimespan() and blockTime() methods @@ -1393,39 +1393,39 @@ interface SchedulerStatic{ * returns the event object by its id * @param event_id the event's id */ - getEvent(event_id: string|number): void; + getEvent(event_id: string | number): any; /** * gets the event's end date * @param id the event's id */ - getEventEndDate(id: string): Date; + getEventEndDate(id: string | number): Date; /** * gets the event's start date * @param id the event's id */ - getEventStartDate(id: string): Date; + getEventStartDate(id: string | number): Date; /** * gets the event's text * @param id the event's id */ - getEventText(id: string): string; + getEventText(id: string | number): string; /** * returns a collection of events which occur during the specified period * @param from the start date of the period * @param to the end date of the period */ - getEvents(from?: Date, to?: Date): void; + getEvents(from?: Date, to?: Date): any; /** * gets the label of a select control in the lightbox * @param property the name of a data property that the control is mapped to * @param key the option's id. This parameter is compared with the event's data property
to assign the select's option to an event */ - getLabel(property: string, key: string|number): void; + getLabel(property: string, key: string | number): any; /** * gets the lightbox's HTML object element @@ -1486,7 +1486,7 @@ interface SchedulerStatic{ * @param date the initial date of the scheduler (by default, the current date) * @param view the name of the initial view (by default, "week") */ - init(container: string|HTMLElement, date?: Date, view?: string): void; + init(container: string | HTMLElement, date?: Date, view?: string): void; /** * inverts the specified time zones @@ -1497,7 +1497,7 @@ interface SchedulerStatic{ /** * checks whether the calendar is currently opened in the scheduler */ - isCalendarVisible(): boolean|HTMLElement; + isCalendarVisible(): boolean | HTMLElement; /** * checks whether the specified event one-day or multi-day @@ -1607,7 +1607,7 @@ interface SchedulerStatic{ * @param id the event's id * @param event the event object */ - setEvent(id: string|number, event: any): void; + setEvent(id: string | number, event: any): void; /** * sets the event's end date @@ -1739,7 +1739,7 @@ interface SchedulerStatic{ * removes marking/blocking set by the markTimespan() method * @param divs a timespan to remove marking/blocking from (or an array of timespans) */ - unmarkTimespan(divs: HTMLElement|any[]): void; + unmarkTimespan(divs: HTMLElement | any[]): void; /** * unselects the specified event @@ -1776,7 +1776,5 @@ interface SchedulerStatic{ } - - declare var scheduler: SchedulerStatic; declare var Scheduler: SchedulerEnterprise; \ No newline at end of file diff --git a/jquery.pnotify/jquery.pnotify-tests.ts b/jquery.pnotify/jquery.pnotify-tests.ts index 8704da19f3..d0f2c4475e 100644 --- a/jquery.pnotify/jquery.pnotify-tests.ts +++ b/jquery.pnotify/jquery.pnotify-tests.ts @@ -223,7 +223,7 @@ function test_pnotify() { }); var type = "error"; - var stack_bottomright = {"dir1": "up", "dir2": "left", "firstpos1": 25, "firstpos2": 25}; + var stack_bottomright = { "dir1": "up", "dir2": "left", "firstpos1": 25, "firstpos2": 25 }; var opts = { title: "Over Here", @@ -233,8 +233,8 @@ function test_pnotify() { width: "100%", stack: stack_bottomright, type: "error" + } as PNotifyOptions; - }; new PNotify(opts); new PNotify({ diff --git a/jquery.pnotify/jquery.pnotify.d.ts b/jquery.pnotify/jquery.pnotify.d.ts index 8daee5da1e..03a1e91c1c 100644 --- a/jquery.pnotify/jquery.pnotify.d.ts +++ b/jquery.pnotify/jquery.pnotify.d.ts @@ -4,11 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// - -// could not pass the Travis Test if enabled -//type NoticeTypeOptions = "notice" | "info" | "success" | "error"; -//type StylingOptions = "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome"; -//type StateOptions = "initializing" | "opening" | "open" | "closing" | "closed"; +type NoticeTypeOptions = "notice" | "info" | "success" | "error"; +type StylingOptions = "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome"; +type StateOptions = "initializing" | "opening" | "open" | "closing" | "closed"; interface PNotifyStack { dir1?: string; @@ -137,7 +135,7 @@ interface PNotifyOptions { /** * What styling classes to use. (Can be either "brighttheme", "jqueryui", "bootstrap2", "bootstrap3", or "fontawesome".) */ - styling?: string; + styling?: StylingOptions; /** * Additional classes to be added to the notice. (For custom styling.) */ @@ -182,7 +180,7 @@ interface PNotifyOptions { /** * Type of the notice. "notice", "info", "success", or "error". */ - type?: string; + type?: NoticeTypeOptions; /** * Set icon to true to use the default icon for the selected style/type, false for no icon, or a string for your own icon class. */ @@ -263,7 +261,7 @@ interface PNotify { /** * The state can be "initializing", "opening", "open", "closing", and "closed" */ - state?: string; + state?: StateOptions; /** * This function is for updating the notice. From f65b3822d91e01e95d80e9f1e02bf21468709256 Mon Sep 17 00:00:00 2001 From: Yvo Date: Wed, 28 Sep 2016 09:52:20 -0400 Subject: [PATCH 043/554] Add barTintColor to NavigatorIOS (#11522) --- react-native/react-native.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index 4973fa08f9..e3e0cf0209 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -1591,7 +1591,11 @@ declare namespace __React { export interface NavigatorIOSProperties extends React.Props { - + /** + * The background color of the navigation bar + */ + barTintColor?: string + /** * NavigatorIOS uses "route" objects to identify child views, their props, and navigation bar configuration. * "push" and all the other navigation operations expect routes to be like this From 750936896bacf9027eccc80228822f4f131a77a5 Mon Sep 17 00:00:00 2001 From: lucap86 Date: Wed, 28 Sep 2016 15:52:35 +0200 Subject: [PATCH 044/554] GreenSock TweenMax TweenLite config Object typed refs #11265 (#11310) * refs #9944 * refs #11265 * refs #11265 --- greensock/greensock.d.ts | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/greensock/greensock.d.ts b/greensock/greensock.d.ts index a3b3801775..004ec79dab 100644 --- a/greensock/greensock.d.ts +++ b/greensock/greensock.d.ts @@ -13,7 +13,38 @@ interface IDispatcher { declare type Tween = TweenLite | TweenMax; declare type Timeline = SimpleTimeline | TimelineLite | TimelineMax; - +declare type TweenConfig = { + [tweenProp: string]: any; + delay?: number; + ease?: Ease; + repeat?: number; + repeatDelay?: number; + yoyo?: boolean; + paused?: boolean; + overwrite?: string|number; + onComplete?: Function; + immediateRender?: boolean; + onCompleteParams?: any[]; + onCompleteScope?: Object; + onRepeat?: Function; + onRepeatScope?: Object; + onReverseComplete?: Function; + onReverseCompleteParams?: any[]; + onReverseCompleteScope?: Object; + onStart?: Function; + onStartParams?: any[]; + onStartScope?: Object; + onUpdate?: Function; + onUpdateParams?: any[]; + onUpdateScope?: Object; + startAt?: Object; + useFrames?: boolean; + lazy?: boolean; + onOverwrite?: Function; + autoCSS?: boolean; + callbackScope?: Object; +} + //com.greensock.core declare class Animation { static ticker: IDispatcher; @@ -86,7 +117,7 @@ declare class TweenLite extends Animation { static killTweensOf(target: Object, onlyActive?: boolean, vars?: Object): void; static lagSmoothing(threshold: number, adjustedLag: number): void; static set(target: Object, vars: Object): TweenLite; - static to(target: Object, duration: number, vars: Object): TweenLite; + static to(target: Object, duration: number, vars: TweenConfig): TweenLite; } declare class TweenMax extends TweenLite { @@ -112,7 +143,7 @@ declare class TweenMax extends TweenLite { static staggerFrom(targets: any, duration: number, vars: Object, stagger: number, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; static staggerFromTo(targets: any, duration: number, fromVars: Object, toVars: Object, stagger: number, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; static staggerTo(targets: any, duration: number, vars: Object, stagger: number, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; - static to(target:Object, duration:number, vars:Object):TweenMax; + static to(target:Object, duration:number, vars:TweenConfig):TweenMax; updateTo(vars: Object, resetDuration?: boolean): TweenMax; yoyo(): boolean; yoyo(value?: boolean): TweenMax; From 881408c91909383843f7cf10de4f39fcd71baa06 Mon Sep 17 00:00:00 2001 From: Prashant Tiwari Date: Wed, 28 Sep 2016 19:24:45 +0530 Subject: [PATCH 045/554] Call strategy with only mode or options (#11466) * Call strategy with only mode or options * Refactor `server.auth.strategy` --- hapi/hapi.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 9c01eb741d..a25ecff38d 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -1876,7 +1876,9 @@ declare module "hapi" { } } });*/ - strategy(name: string, scheme: any, mode?: boolean | string, options?: any): void; + strategy(name: string, scheme: string, mode?: boolean | string, options?: any): void; + strategy(name: string, scheme: string, mode?: boolean | string): void; + strategy(name: string, scheme: string, options?:any): void; /** server.auth.test(strategy, request, next) Tests a request against an authentication strategy where: From 15345f88562b77cbf03013382581838bf97813d3 Mon Sep 17 00:00:00 2001 From: panoti Date: Wed, 28 Sep 2016 21:01:54 +0700 Subject: [PATCH 046/554] - add client.exists([params, [callback]]) (#11515) --- elasticsearch/elasticsearch.d.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index 2816a0dee0..26a9a1e880 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -15,6 +15,8 @@ declare module Elasticsearch { create(params: CreateDocumentParams, callback: (err: any, response: any, status: any) => void): void; delete(params: DeleteDocumentParams): PromiseLike; delete(params: DeleteDocumentParams, callback: (error: any, response: any) => void): void; + exists(params: ExistsParams): PromiseLike; + exists(params: ExistsParams, callback: (error: any, response: any, status?: any) => void): void; get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; get(params: GetParams): PromiseLike>; index(params: IndexDocumentParams): PromiseLike; @@ -95,6 +97,7 @@ declare module Elasticsearch { method?: string; body?: any; ignore?: number | number[]; + filterPath?: string | string[]; } export interface BulkIndexDocumentsParams extends GenericParams { @@ -205,6 +208,17 @@ declare module Elasticsearch { _source: T; } + export interface ExistsParams extends GenericParams { + id: string; + index: string; + parent?: string; + preference?: string; + realtime?: boolean; + refresh?: boolean; + routing?: string; + type: string; + } + export interface IndexDocumentParams extends GenericParams { index: string; type: string; From 32b5d0a12c4a8e5be4e51c82d8636de022b6b4ec Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Wed, 28 Sep 2016 07:23:24 -0700 Subject: [PATCH 047/554] Update to Electron 1.4.1 (#11481) --- github-electron/github-electron.d.ts | 62 ++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 8 deletions(-) diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 64b7cf6a02..9541d64ac6 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.3.6 +// Type definitions for Electron v1.4.1 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -176,7 +176,7 @@ declare namespace Electron { /** * Emitted when the gpu process crashes. */ - on(event: 'gpu-process-crashed', listener: Function): this; + on(event: 'gpu-process-crashed', listener: (event: Event, killed: boolean) => void): this; /** * Emitted when Chrome's accessibility support changes. * @@ -841,6 +841,11 @@ declare namespace Electron { * Note: This is only implemented on macOS. */ on(event: 'scroll-touch-end', listener: Function): this; + /** + * Emitted when scroll wheel event phase filed upon reaching the edge of element. + * Note: This is only implemented on macOS. + */ + on(event: 'scroll-touch-edge', listener: Function): this; /** * Emitted on 3-finger swipe. * Note: This is only implemented on macOS. @@ -2589,6 +2594,7 @@ declare namespace Electron { static createEmpty(): NativeImage; /** * Creates a new NativeImage instance from file located at path. + * This method returns an empty image if the path does not exist, cannot be read, or is not a valid image. */ static createFromPath(path: string): NativeImage; /** @@ -2769,8 +2775,18 @@ declare namespace Electron { referrer: string; method: string; uploadData?: { + /** + * Content being sent. + */ bytes: Buffer, - file: string + /** + * Path of file being uploaded. + */ + file: string, + /** + * UUID of blob data. Use session.getBlobData method to retrieve the data. + */ + blobUUID: string; }[]; } @@ -3016,6 +3032,10 @@ declare namespace Electron { * @returns The user agent for this session. */ getUserAgent(): string; + /** + * Returns the blob data associated with the identifier. + */ + getBlobData(identifier: string, callback: (result: Buffer) => void): void; /** * The webRequest API set allows to intercept and modify contents of a request at various stages of its lifetime. */ @@ -3317,6 +3337,10 @@ declare namespace Electron { * Path of file being uploaded. */ file: string; + /** + * UUID of blob data. Use session.getBlobData method to retrieve the data. + */ + blobUUID: string; } interface BeforeRequestDetails extends Details { @@ -3495,6 +3519,11 @@ declare namespace Electron { * Get system preferences. */ interface SystemPreferences { + /** + * Note: This is only implemented on Windows. + */ + on(event: 'accent-color-changed', listener: (event: Event, newColor: string) => void): this; + on(event: string, listener: Function): this; /** * @returns If the system is in Dark Mode. * @@ -3549,13 +3578,17 @@ declare namespace Electron { */ getUserDefault(key: string, type: 'string' | 'boolean' | 'integer' | 'float' | 'double' | 'url' | 'array' | 'dictionary'): any; /** - * This method returns true if DWM composition (Aero Glass) is enabled, - * and false otherwise. You can use it to determine if you should create - * a transparent window or not (transparent windows won’t work correctly when DWM composition is disabled). + * @returns Whether DWM composition (Aero Glass) is enabled. * * Note: This is only implemented on Windows. */ isAeroGlassEnabled(): boolean; + /** + * @returns The users current system wide color preference in the form of an RGBA hexadecimal string. + * + * Note: This is only implemented on Windows. + */ + getAccentColor(): string; } // https://github.com/electron/electron/blob/master/docs/api/tray.md @@ -3822,7 +3855,7 @@ declare namespace Electron { /** * Emitted when the renderer process has crashed. */ - on(event: 'crashed', listener: Function): this; + on(event: 'crashed', listener: (event: Event, killed: boolean) => void): this; /** * Emitted when a plugin process has crashed. */ @@ -4237,6 +4270,10 @@ declare namespace Electron { * If offscreen rendering is enabled returns the current frame rate. */ getFrameRate(): number; + /** + * If offscreen rendering is enabled invalidates the frame and generates a new one through the 'paint' event. + */ + invalidate(): void; /** * Sets the item as dragging item for current drag-drop operation. */ @@ -4438,7 +4475,7 @@ declare namespace Electron { [key: string]: string; } - type NewWindowDisposition = 'default' | 'foreground-tab' | 'background-tab' | 'new-window' | 'other'; + type NewWindowDisposition = 'default' | 'foreground-tab' | 'background-tab' | 'new-window' | 'save-to-disk' | 'other'; /** * Specifies the action to take place when ending webContents.findInPage request. @@ -4881,6 +4918,15 @@ declare namespace Electron { * A list of strings which specifies the blink features to be disabled separated by ,. */ disableblinkfeatures: string; + /** + * A value that links the webview to a specific webContents. + * When a webview first loads a new webContents is created and this attribute is set + * to its instance identifier. Setting this attribute on a new or existing webview connects + * it to the existing webContents that currently renders in a different webview. + * + * The existing webview will see the destroy event and will then create a new webContents when a new url is loaded. + */ + guestinstance: string; /** * Loads the url in the webview, the url must contain the protocol prefix, e.g. the http:// or file://. */ From 7be68adbdff4bea14f33f54f27d3bdb5822e3b10 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 28 Sep 2016 22:34:18 +0800 Subject: [PATCH 048/554] Correct fs.createWriteStream (#11560) --- node/node.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/node/node.d.ts b/node/node.d.ts index 5c016af3fd..0f2374ae10 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2321,6 +2321,8 @@ declare module "fs" { encoding?: string; fd?: number; mode?: number; + autoClose?: boolean; + start?: number; }): WriteStream; export function fdatasync(fd: number, callback: Function): void; export function fdatasyncSync(fd: number): void; From b8cdd448dd9bc6236fef31a11aa6bd1daf074739 Mon Sep 17 00:00:00 2001 From: vargeek Date: Wed, 28 Sep 2016 23:11:03 +0800 Subject: [PATCH 049/554] add declaration file for weapp (#11554) * add declaration file of weapp * rename "weapp" to "weapp-api" rename "weapp" to "weapp-api" to avoid naming conflicts --- weapp-api/weapp-api-tests.ts | 678 ++++++++++++++++++++ weapp-api/weapp-api.d.ts | 1135 ++++++++++++++++++++++++++++++++++ 2 files changed, 1813 insertions(+) create mode 100644 weapp-api/weapp-api-tests.ts create mode 100644 weapp-api/weapp-api.d.ts diff --git a/weapp-api/weapp-api-tests.ts b/weapp-api/weapp-api-tests.ts new file mode 100644 index 0000000000..0b249701c6 --- /dev/null +++ b/weapp-api/weapp-api-tests.ts @@ -0,0 +1,678 @@ +/// + + +App({ + onLaunch: function () { + //调用API从本地缓存中获取数据 + var logs = wx.getStorageSync('logs') as Array || [] + logs.unshift(Date.now()) + wx.setStorageSync('logs', logs) + }, + getUserInfo: function (cb: Function) { + var that = this; + if (this.globalData.userInfo) { + typeof cb == "function" && cb(this.globalData.userInfo) + } else { + //调用登录接口 + wx.login({ + success: function () { + wx.getUserInfo({ + success: function (res) { + that.globalData.userInfo = res.userInfo; + typeof cb == "function" && cb(that.globalData.userInfo) + } + }) + } + }); + } + }, + globalData: { + userInfo: null + } +}) + + +let app = getApp(); +let page = app.getCurrentPage(); +page.setData({ 'foo': 'bar' }); +Page({ + data: { + foo: 'bar' + }, + onLoad: function (options) { + console.log(options.title); + } +}) + + +wx.request({ + url: 'test.php', + data: { + x: '', + y: '' + }, + header: { + 'Content-Type': 'application/json' + }, + success: function (res) { + console.log(res.data) + } +}) + +wx.chooseImage({ + success: function (res) { + var tempFilePaths = res.tempFilePaths + wx.uploadFile({ + url: 'http://example.com/upload', + filePath: tempFilePaths[0], + name: 'file', + formData: { + 'user': 'test' + } + }) + } +}) + +wx.downloadFile({ + url: 'http://example.com/audio/123', + type: 'audio', + success: function (res) { + wx.playVoice({ + filePath: res.tempFilePath + }) + } +}) + +wx.connectSocket({ + url: 'test.php', + data: { + x: '', + y: '' + }, + header: { + 'content-type': 'application/json' + }, + method: "GET", +}) + +wx.connectSocket({ + url: 'test.php' +}) +wx.onSocketOpen(function (res) { + console.log('WebSocket连接已打开!') +}) + +wx.connectSocket({ + url: 'test.php' +}) +wx.onSocketOpen(function (res) { + console.log('WebSocket连接已打开!') +}) +wx.onSocketError(function (res) { + console.log('WebSocket连接打开失败,请检查!') +}) + +var socketOpen = false +var socketMsgQueue: Array = [] +wx.connectSocket({ + url: 'test.php' +}) + +wx.onSocketOpen(function (res) { + socketOpen = true + for (var i = 0; i < socketMsgQueue.length; i++) { + sendSocketMessage(socketMsgQueue[i]) + } + socketMsgQueue = [] +}) + +function sendSocketMessage(msg: string) { + if (socketOpen) { + wx.sendSocketMessage({ + data: msg + }) + } else { + socketMsgQueue.push(msg) + } +} + +wx.connectSocket({ + url: 'test.php' +}) + +wx.onSocketMessage(function (res) { + console.log('收到服务器内容:' + res.data) +}) + +wx.connectSocket({ + url: 'test.php' +}) + +//注意这里有时序问题, +//如果 wx.connectSocket 还没回调 wx.onSocketOpen,而先调用 wx.closeSocket,那么就做不到关闭 WebSocket 的目的。 +//必须在 WebSocket 打开期间调用 wx.closeSocket 才能关闭。 +wx.onSocketOpen(function () { + wx.closeSocket() +}) + +wx.onSocketClose(function (res) { + console.log('WebSocket 已关闭!') +}) + +wx.chooseImage({ + count: 1, // 默认9 + sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 + sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 + success: function (res) { + // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 + var tempFilePaths = res.tempFilePaths + } +}) + +wx.previewImage({ + current: '', // 当前显示图片的http链接 + urls: [] // 需要预览的图片http链接列表 +}) + +wx.startRecord({ + success: function (res) { + var tempFilePath = res.tempFilePath + }, + fail: function (res) { + //录音失败 + } +}) +setTimeout(function () { + //结束录音 + wx.stopRecord() +}, 10000) + +wx.startRecord({ + success: function (res) { + var tempFilePath = res.tempFilePath + wx.playVoice({ + filePath: tempFilePath, + complete: function () { + } + }) + } +}) + +wx.startRecord({ + success: function (res) { + var tempFilePath = res.tempFilePath + wx.playVoice({ + filePath: tempFilePath + }) + + setTimeout(function () { + //暂停播放 + wx.pauseVoice() + }, 5000) + } +}) + +wx.startRecord({ + success: function (res) { + var tempFilePath = res.tempFilePath + wx.playVoice({ + filePath: tempFilePath + }) + + setTimeout(function () { + wx.stopVoice() + }, 5000) + } +}) + +wx.getBackgroundAudioPlayerState({ + success: function (res) { + var status = res.status + var dataUrl = res.dataUrl + var currentPosition = res.currentPosition + var duration = res.duration + var downloadPercent = res.downloadPercent + } +}) + +wx.playBackgroundAudio({ + dataUrl: '', + title: '', + coverImgUrl: '' +}) + +wx.pauseBackgroundAudio() + +wx.seekBackgroundAudio({ + position: 30 +}) +wx.stopBackgroundAudio() + +wx.startRecord({ + success: function (res) { + var tempFilePath = res.tempFilePath + wx.saveFile({ + tempFilePath: tempFilePath, + success: function (res) { + var savedFilePath = res.savedFilePath + } + }) + } +}) + + +Page({ + bindButtonTap: function () { + var that = this + wx.chooseVideo({ + sourceType: ['album', 'camera'], + maxDuration: 60, + camera: ['front', 'back'], + success: function (res) { + that.setData({ + src: res.tempFilePath + }) + } + }) + } +}) + +wx.setStorage({ + key: "key", + data: "value" +}) + +try { + wx.setStorageSync('key', 'value') +} catch (e) { +} + +wx.getStorage({ + key: 'key', + success: function (res) { + console.log(res.data) + } +}) + + +var value = wx.getStorageSync('key') +if (value) { + // Do something with return value +} + + +wx.clearStorage() + + +try { + wx.clearStorageSync() +} catch (e) { +} + + +wx.getLocation({ + type: 'wgs84', + success: function (res) { + var latitude = res.latitude + var longitude = res.longitude + var speed = res.speed + var accuracy = res.accuracy + } +}) + +wx.getLocation({ + type: 'gcj02', //返回可以用于wx.openLocation的经纬度 + success: function(res) { + var latitude = res.latitude + var longitude = res.longitude + wx.openLocation({ + latitude: latitude, + longitude: longitude, + scale: 28 + }) + } +}) + +wx.getNetworkType({ + success: function(res) { + var networkType = res.networkType // 返回网络类型2g,3g,4g,wifi + } +}) + +wx.getSystemInfo({ + success: function(res) { + console.log(res.model) + console.log(res.pixelRatio) + console.log(res.windowWidth) + console.log(res.windowHeight) + console.log(res.language) + console.log(res.version) + } +}) + +wx.onAccelerometerChange(function(res) { + console.log(res.x) + console.log(res.y) + console.log(res.z) +}) + +wx.onCompassChange(function (res) { + console.log(res.direction) +}) + +wx.setNavigationBarTitle({ + title: '当前页面' +}) + +wx.navigateTo({ + url: 'test?id=1' +}) + +wx.redirectTo({ + url: 'test?id=1' +}) + + +var animation = wx.createAnimation({ + transformOrigin: "50% 50%", + duration: 1000, + timingFunction: "ease", + delay: 0 +}) + + +Page({ + data: { + animationData: {} + }, + onShow: function(){ + var animation = wx.createAnimation({ + duration: 1000, + timingFunction: 'ease', + }) + + this.animation = animation + + animation.scale(2,2).rotate(45).step() + + this.setData({ + animationData:animation.export() + }) + + setTimeout(function() { + animation.translate(30).step() + this.setData({ + animationData:animation.export() + }) + }.bind(this), 1000) + }, + rotateAndScale: function () { + // 旋转同时放大 + this.animation.rotate(45).scale(2, 2).step() + this.setData({ + animationData:animation.export() + }) + }, + rotateThenScale: function () { + // 先旋转后放大 + this.animation.rotate(45).step() + this.animation.scale(2, 2).step() + this.setData({ + animationData:animation.export() + }) + }, + rotateAndScaleThenTranslate: function () { + // 先旋转同时放大,然后平移 + this.animation.rotate(45).scale(2, 2).step() + this.animation.translate(100, 100).step({ duration: 1000 }) + this.setData({ + animationData:animation.export() + }) + } +}) + +// 假设页面上有3个画布 +var canvas1Id = 3001 +var canvas2Id = 3002 +var canvas3Id = 3003 + +var context = wx.createContext(); + +[canvas1Id, canvas2Id, canvas3Id].forEach(function (id) { + context.clearActions() + // 在context上调用方法 + wx.drawCanvas({ + canvasId: id, + actions: context.getActions() + }) +}) + + +Page({ + onReady: function() { + var context = wx.createContext() + context.rect(5, 5, 25, 15) + context.stroke() + context.scale(2, 2) //再放大2倍 + context.rect(5, 5, 25, 15) + context.stroke() + context.scale(2, 2) //再放大2倍 + context.rect(5, 5, 25, 15) + context.stroke() + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }) + } +}) + + +Page({ + onReady: function() { + var context = wx.createContext() + context.rect(50, 50, 200, 200) + context.stroke() + context.rotate(5 * Math.PI / 180) + context.rect(50, 50, 200, 200) + context.stroke() + context.rotate(5 * Math.PI / 180) + context.rect(50, 50, 200, 200) + context.stroke() + + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }) + } +}) + +Page({ + onReady: function() { + var context = wx.createContext() + + context.rect(50, 50, 200, 200) + context.stroke() + context.translate(50, 50) + context.rect(50, 50, 200, 200) + context.stroke() + + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }) + } +}) + +Page({ + onReady: function() { + var context = wx.createContext() + + context.rect(50, 50, 200, 200) + context.fill() + context.clearRect(100, 100, 50, 50) + + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }) + } +}) + +Page({ + onReady: function() { + var context = wx.createContext() + wx.chooseImage({ + success: function(res) { + context.drawImage(res.tempFilePaths[0], 0, 0) + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }) + } + }) + } +}) + +Page({ + onReady:function(){ + var context = wx.createContext() + + context.setFontSize(14) + context.fillText("MINA", 50, 50) + context.moveTo(0, 50) + context.lineTo(100, 50) + context.stroke() + + context.setFontSize(20) + context.fillText("MINA", 100, 100) + context.moveTo(0, 100) + context.lineTo(200, 100) + context.stroke() + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }); + } +}) + +Page({ + onReady: function() { + var context = wx.createContext() + + context.setFillStyle("#ff00ff") + context.setStrokeStyle("#00ffff") + + context.rect(50, 50, 100, 100) + context.fill() + context.stroke() + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }); + } +}) + +Page({ + onReady: function() { + var context = wx.createContext() + + context.setLineWidth(10) + context.setLineCap("round") + context.setLineJoin("miter") + context.setMiterLimit(10) + context.moveTo(20, 20) + context.lineTo(150, 27) + context.lineTo(20, 54) + context.stroke() + + context.beginPath() + + context.setMiterLimit(3) + context.moveTo(20, 70) + context.lineTo(150, 77) + context.lineTo(20, 104) + context.stroke() + + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }); + } +}) +Page({ + canvasIdErrorCallback: function (e:any) { + console.error(e.detail.errMsg) + }, + onReady: function() { + //使用wx.createContext获取绘图上下文context + var context = wx.createContext() + + context.setStrokeStyle("#00ff00") + context.setLineWidth(5) + context.rect(0, 0, 200, 200) + context.stroke() + context.setStrokeStyle("#ff0000") + context.setLineWidth(2) + context.moveTo(160, 100) + context.arc(100, 100, 60, 0,2 * Math.PI, true) + context.moveTo(140, 100) + context.arc(100, 100, 40, 0, Math.PI, false) + context.moveTo(85, 80) + context.arc(80, 80, 5, 0,2 * Math.PI, true) + context.moveTo(125, 80) + context.arc(120, 80, 5, 0, 2 * Math.PI, true) + context.stroke() + + // 调用 wx.drawCanvas,通过 canvasId 指定在哪张画布上绘制,通过 actions 指定绘制行为 + wx.drawCanvas({ + canvasId: 'firstCanvas', + actions: context.getActions() // 获取绘图动作数组 + }) + } +}) + + +App({ + onLaunch: function() { + wx.login({ + success: function(res) { + if (res.code) { + //发起网络请求 + wx.request({ + url: 'https://test.com/onLogin', + data: { + code: res.code + } + }) + } else { + console.log('获取用户登录态失败!' + res.errMsg) + } + } + }); + } +}) + + +wx.getUserInfo({ + success: function(res) { + var userInfo = res.userInfo + var nickName = userInfo.nickName + var avatarUrl = userInfo.avatarUrl + var gender = userInfo.gender //性别 0:未知、1:男、2:女 + var province = userInfo.province + var city = userInfo.city + var country = userInfo.country + } +}) + +wx.requestPayment({ + 'timeStamp': '', + 'nonceStr': '', + 'package': '', + 'signType': 'MD5', + 'paySign': '', + 'success':function(res){ + }, + 'fail':function(res){ + } +}) diff --git a/weapp-api/weapp-api.d.ts b/weapp-api/weapp-api.d.ts new file mode 100644 index 0000000000..cb9d00383d --- /dev/null +++ b/weapp-api/weapp-api.d.ts @@ -0,0 +1,1135 @@ +// Type definitions for weapp +// Project: https://mp.weixin.qq.com/debug/wxadoc/dev/index.html +// Definitions by: vargeek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace wx { + type NoneParamCallback = () => void; + type OneParamCallback = (data: any) => void; + type ResponseCallback = (res: any) => void; + type DataResponseCallback = (res: DataResponse) => void; + type TempFileResponseCallback = (res: TempFileResponse) => void; + type ErrorCallback = (error: any) => void; + type EventCallback = (event: any) => void; + + interface DataResponse { + /** 回调函数返回的内容 */ + data: any; + } + interface TempFileResponse { + /** 文件的临时路径 */ + tempFilePath: string; + } + + interface PageOptions { + /** 页面的初始数据 */ + data?: any; + /** 生命周期函数--监听页面加载 */ + onLoad?: (options: any) => void; + /** 生命周期函数--监听页面渲染完成 */ + onReady?: NoneParamCallback; + /** 生命周期函数--监听页面显示 */ + onShow?: NoneParamCallback; + /** 生命周期函数--监听页面隐藏 */ + onHide?: NoneParamCallback; + /** 生命周期函数--监听页面卸载 */ + onUnload?: NoneParamCallback; + [key: string]: any; + } + + interface AppOptions { + /** + * 生命周期函数--监听小程序初始化 + * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次) + */ + onLaunch?: NoneParamCallback; + /** + * 生命周期函数--监听小程序显示 + * 当小程序启动,或从后台进入前台显示,会触发 onShow + */ + onShow?: NoneParamCallback; + /** + * 生命周期函数--监听小程序隐藏 + * 当小程序从前台进入后台,会触发 onHide + */ + onHide?: NoneParamCallback; + [key: string]: any + } + + interface RequestHeader { + [key: string]: string; + } + interface RequestOptions { + /** 开发者服务器接口地址 */ + url: string; + /** 请求的参数 */ + data?: string | any; + /** 设置请求的 header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: string; + /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ + success?: DataResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * wx.request发起的是https请求。一个微信小程序,同时只能有5个网络请求连接。 + */ + function request(options: RequestOptions): void; + + + interface UploadFileOptions { + /** 开发者服务器 url */ + url: string; + /** 要上传文件资源的路径 */ + filePath: string; + /** 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ + name: string; + /** HTTP 请求 Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** HTTP 请求中其他额外的 form data */ + formData?: any; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 将本地资源上传到开发者服务器。 + * 如页面通过 wx.chooseImage 等接口获取到一个本地资源的临时文件路径后, + * 可通过此接口将本地资源上传到指定服务器。 + * 客户端发起一个 HTTPS POST 请求, + * 其中 Content-Type 为 multipart/form-data 。 + */ + function uploadFile(options: UploadFileOptions): void; + + + interface DownloadFileOptions { + /** 下载资源的 url */ + url: string; + /** 下载资源的类型,用于客户端识别处理,有效值:image/audio/video */ + type?: string; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ + success?: TempFileResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 下载文件资源到本地。客户端直接发起一个 HTTP GET 请求, + * 把下载到的资源根据 type 进行处理,并返回文件的本地临时路径。 + */ + function downloadFile(options: DownloadFileOptions): void; + + + interface ConnectSocketOptions { + /** 开发者服务器接口地址,必须是 HTTPS 协议,且域名必须是后台配置的合法域名 */ + url: string; + /** 请求的数据 */ + data?: any; + /** HTTP Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认是GET,有效值为: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 创建一个 WebSocket 连接; + * 一个微信小程序同时只能有一个 WebSocket 连接, + * 如果当前已存在一个 WebSocket 连接, + * 会自动关闭该连接,并重新创建一个 WebSocket 连接。 + */ + function connectSocket(options: ConnectSocketOptions): void; + + + /** 监听WebSocket连接打开事件。 */ + function onSocketOpen(callback: OneParamCallback): void; + + /** 监听WebSocket错误。 */ + function onSocketError(callback: ErrorCallback): void; + + interface SendSocketMessageOptions { + /** 需要发送的内容 */ + data: string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 通过 WebSocket 连接发送数据,需要先 wx.connectSocket, + * 并在 wx.onSocketOpen 回调之后才能发送。 + */ + function sendSocketMessage(options: SendSocketMessageOptions): void; + + + /** + * 监听WebSocket接受到服务器的消息事件。 + */ + function onSocketMessage(callback: DataResponseCallback): void; + + /** + * 关闭WebSocket连接。 + */ + function closeSocket(): void; + + /** 监听WebSocket关闭。 */ + function onSocketClose(callback: ResponseCallback): void; + + type ImageSizeType = 'original' | 'compressed'; + type ImageSourceType = 'album' | 'camera'; + type VideoSourceType = 'album' | 'camera'; + type CameraDevice = 'front' | 'back'; + + interface TempFilesData { + /** 文件的临时路径 */ + tempFilePaths: string; + } + interface ChooseImageOptions { + /** 最多可以选择的图片张数,默认9 */ + count?: number; + /** original 原图,compressed 压缩图,默认二者都有 */ + sizeType?: Array; + /** album 从相册选图,camera 使用相机,默认二者都有 */ + sourceType?: Array; + /** 成功则返回图片的本地文件路径列表 tempFilePaths */ + success: (res: TempFilesData) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 从本地相册选择图片或使用相机拍照。 + */ + function chooseImage(options: ChooseImageOptions): void; + + interface PreviewImageOptions { + /** 当前显示图片的链接,不填则默认为 urls 的第一张 */ + current?: string; + /** 需要预览的图片链接列表 */ + urls: Array; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 预览图片。 + */ + function previewImage(options: PreviewImageOptions): void; + + interface StartRecordOptions { + /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ + success?: TempFileResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 开始录音。当主动调用wx.stopRecord, + * 或者录音超过1分钟时自动结束录音,返回录音文件的临时文件路径。 + * 注:文件的临时路径,在小程序本次启动期间可以正常使用, + * 如需持久保存,需在主动调用wx.saveFile,在小程序下次启动时才能访问得到。 + */ + function startRecord(options: StartRecordOptions): void; + + /** + * ​ 主动调用停止录音。 + */ + function stopRecord(): void; + + interface PlayVoiceOptions { + /** 需要播放的语音文件的文件路径 */ + filePath: string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 开始播放语音,同时只允许一个语音文件正在播放, + * 如果前一个语音文件还没播放完,将中断前一个语音播放。 + */ + function playVoice(options: PlayVoiceOptions): void; + + /** + * 暂停正在播放的语音。 + * 再次调用wx.playVoice播放同一个文件时,会从暂停处开始播放。 + * 如果想从头开始播放,需要先调用 wx.stopVoice。 + */ + function pauseVoice(): void; + + /** + * 结束播放语音。 + */ + function stopVoice(): void; + + interface BackgroundAudioPlayerState { + /** 选定音频的长度(单位:s),只有在当前有音乐播放时返回 */ + duration?: number; + /** 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回 */ + currentPosition?: number; + /** 播放状态(2:没有音乐在播放,1:播放中,0:暂停中) */ + status: number; + /** 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回 */ + downloadPercent?: number; + /** 歌曲数据链接,只有在当前有音乐播放时返回 */ + dataUrl?: string; + } + type GetBackgroundAudioPlayerStateSuccessCallback = (state: BackgroundAudioPlayerState) => void; + interface GetBackgroundAudioPlayerStateOptions { + /** 接口调用成功的回调函数 */ + success?: GetBackgroundAudioPlayerStateSuccessCallback; + /** 接口调用失败的回调函数 */ + fail?: NoneParamCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: NoneParamCallback; + } + /** 获取音乐播放状态。 */ + function getBackgroundAudioPlayerState(options: GetBackgroundAudioPlayerStateOptions): void; + + interface PlayBackgroundAudioOptions { + /** 音乐链接 */ + dataUrl: string; + /** 音乐标题 */ + title?: string; + /** 封面URL */ + coverImgUrl?: string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + + } + /** 播放音乐,同时只能有一首音乐正在播放。 */ + function playBackgroundAudio(options: PlayBackgroundAudioOptions): void; + + /** 暂停播放音乐。 */ + function pauseBackgroundAudio(): void; + + interface SeekBackgroundAudioOptions { + /** 音乐位置,单位:秒 */ + position: number; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 控制音乐播放进度。 + */ + function seekBackgroundAudio(options: SeekBackgroundAudioOptions): void; + + /** + * 停止播放音乐。 + */ + function stopBackgroundAudio(): void; + + /** 监听音乐播放。 */ + function onBackgroundAudioPlay(callback: NoneParamCallback): void; + + /** 监听音乐暂停。 */ + function onBackgroundAudioPause(callback: NoneParamCallback): void; + + /** 监听音乐停止。 */ + function onBackgroundAudioStop(callback: NoneParamCallback): void; + + interface SavedFileData { + /** 文件的保存路径 */ + savedFilePath: string; + } + interface SaveFileOptions { + /** 需要保存的文件的临时路径 */ + tempFilePath: string; + /** 返回文件的保存路径,res = {savedFilePath: '文件的保存路径'} */ + success?: (res: SavedFileData) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 保存文件到本地。 + */ + function saveFile(options: SaveFileOptions): void; + + interface VideoData { + /** 选定视频的临时文件路径 */ + tempFilePath: string; + /** 选定视频的时间长度 */ + duration: number; + /** 选定视频的数据量大小 */ + size: number; + /** 返回选定视频的长 */ + height: number; + /** 返回选定视频的宽 */ + width: number; + } + interface ChooseVideoOptions { + /** album 从相册选视频,camera 使用相机拍摄,默认为:['album', 'camera'] */ + sourceType?: Array; + /** 拍摄视频最长拍摄时间,单位秒。最长支持60秒 */ + maxDuration?: number; + /** 前置或者后置摄像头,默认为前后都有,即:['front', 'back'] */ + camera?: Array; + /** 接口调用成功,返回视频文件的临时文件路径,详见返回参数说明 */ + success?: (res: VideoData) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 拍摄视频或从手机相册中选视频,返回视频的临时文件路径。 + */ + function chooseVideo(options: ChooseVideoOptions): void; + + interface SetStorageOptions { + /** 本地缓存中的指定的 key */ + key: string; + /** 需要存储的内容 */ + data: any | string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 将数据存储在本地缓存中指定的 key 中, + * 会覆盖掉原来该 key 对应的内容,这是一个异步接口。 + */ + function setStorage(options: SetStorageOptions): void; + /** + * 将 data 存储在本地缓存中指定的 key 中, + * 会覆盖掉原来该 key 对应的内容,这是一个同步接口。 + * + * @param {string} key 本地缓存中的指定的 key + * @param {(Object | string)} data 需要存储的内容 + */ + function setStorageSync(key: string, data: any | string): void; + + interface GetStorageOptions { + /** 本地缓存中的指定的 key */ + key: string; + /** 接口调用的回调函数,res = {data: key对应的内容} */ + success: DataResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 从本地缓存中异步获取指定 key 对应的内容。 + */ + function getStorage(options: GetStorageOptions): void; + + /** + * 从本地缓存中同步获取指定 key 对应的内容。 + * + * @param {string} key + * @returns {(Object | string)} + */ + function getStorageSync(key: string): any | string; + + /** + * 清理本地数据缓存。 + */ + function clearStorage(): void; + /** + * 同步清理本地数据缓存 + */ + function clearStorageSync(): void; + + interface LocationData { + /** 纬度,浮点数,范围为-90~90,负数表示南纬 */ + latitude: number; + /** 经度,浮点数,范围为-180~180,负数表示西经 */ + longitude: number; + /** 速度,浮点数,单位m/s */ + speed: number; + /** 位置的精确度 */ + accuracy: number; + } + + interface GetLocationOptions { + /** 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于wx.openLocation的坐标 */ + type?: 'wgs84' | 'gcj02'; + /** 接口调用成功的回调函数,返回内容详见返回参数说明。 */ + success: (res: LocationData) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 获取当前的地理位置、速度。 + */ + function getLocation(options: GetLocationOptions): void; + + interface OpenLocationOptions { + /** 纬度,范围为-90~90,负数表示南纬 */ + latitude: number; + /** 经度,范围为-180~180,负数表示西经 */ + longitude: number; + /** 缩放比例,范围1~28,默认为28 */ + scale?: number; + /** 位置名 */ + name?: string; + /** 地址的详细说明 */ + address?: string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 使用微信内置地图查看位置 + */ + function openLocation(options: OpenLocationOptions): void; + + interface NetworkTypeData { + /** 返回网络类型2g,3g,4g,wifi */ + networkType: '2g' | '3g' | '4g' | 'wifi'; + } + interface GetNetworkTypeOptions { + /** 接口调用成功,返回网络类型 networkType */ + success: (res: NetworkTypeData) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 获取网络类型。 + */ + function getNetworkType(options: GetNetworkTypeOptions): void; + + + interface SystemInfo { + /** 手机型号 */ + model: string; + /** 设备像素比 */ + pixelRatio: number; + /** 窗口宽度 */ + windowWidth: number; + /** 窗口高度 */ + windowHeight: number; + /** 微信设置的语言 */ + language: string; + /** 微信版本号 */ + version: string; + } + interface GetSystemInfoOptions { + /** 成功获取系统信息的回调 */ + success: (res: SystemInfo) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 获取系统信息。 + */ + function getSystemInfo(options: GetSystemInfoOptions): void; + + interface AccelerometerData { + /** X 轴 */ + x: number; + /** Y 轴 */ + y: number; + /** Z 轴 */ + z: number; + } + type AccelerometerChangeCallback = (res: AccelerometerData) => void; + /** + * 监听重力感应数据,频率:5次/秒 + */ + function onAccelerometerChange(callback: AccelerometerChangeCallback): void; + + interface CompassData { + /** 面对的方向度数 */ + direction: number; + } + type CompassChangeCallback = (res: CompassData) => void; + function onCompassChange(callback: CompassChangeCallback): void; + + interface SetNavigationBarTitleOptions { + /** 页面标题 */ + title?: string; + /** 成功获取系统信息的回调 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 动态设置当前页面的标题。 + */ + function setNavigationBarTitle(options: SetNavigationBarTitleOptions): void; + + /** + * 在当前页面显示导航条加载动画。 + */ + function showNavigationBarLoading(): void; + /** + * 隐藏导航条加载动画。 + */ + function hideNavigationBarLoading(): void; + + interface NavigateToOptions { + /** 需要跳转的应用内页面的路径 */ + url: string; + /** 成功获取系统信息的回调 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。 + * + * 注意:为了不让用户在使用小程序时造成困扰, + * 我们规定页面路径只能是五层,请尽量避免多层级的交互方式。 + */ + function navigateTo(options: NavigateToOptions): void; + + interface RedirectToOptions { + /** 需要跳转的应用内页面的路径 */ + url: string; + /** 成功获取系统信息的回调 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 关闭当前页面,跳转到应用内的某个页面。 + */ + function redirectTo(options: RedirectToOptions): void; + + /** + * 关闭当前页面,回退前一页面。 + */ + function navigateBack(): void; + + type TimingFunction = 'linear' | 'ease' | 'ease-in' | 'ease-in-out' | 'ease-out' | 'step-start' | 'step-end'; + + interface CreateAnimationOptions { + /** 动画持续时间,单位ms,默认值 400 */ + duration?: number; + /** 定义动画的效果,默认值"linear",有效值:"linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end" */ + timingFunction?: TimingFunction; + /** 动画持续时间,单位 ms,默认值 0 */ + delay?: number; + /** 设置transform-origin,默认为"50% 50% 0" */ + transformOrigin?: string; + } + + interface Animator { + actions: Array; + } + interface AnimationAction { + animates: Array; + option: AnimationActionOption; + } + interface AnimationActionOption { + transformOrigin: string; + transition: AnimationTransition; + } + interface AnimationTransition { + delay: number; + duration: number; + timingFunction: TimingFunction; + } + interface Animate { + type: string; + args: Array; + } + + /** + * 创建一个动画实例animation。调用实例的方法来描述动画。 + * 最后通过动画实例的export方法导出动画数据传递给组件的animation属性。 + * + * 注意: export 方法每次调用后会清掉之前的动画操作 + */ + function createAnimation(options?: CreateAnimationOptions): Animation; + /** 动画实例可以调用以下方法来描述动画,调用结束后会返回自身,支持链式调用的写法。 */ + interface Animation { + /** + * 调用动画操作方法后要调用 step() 来表示一组动画完成, + * 可以在一组动画中调用任意多个动画方法, + * 一组动画中的所有动画会同时开始, + * 一组动画完成后才会进行下一组动画。 + * @param {CreateAnimationOptions} options 指定当前组动画的配置 + */ + step(options?: CreateAnimationOptions): void; + /** + * 导出动画操作 + * + * 注意: export 方法每次调用后会清掉之前的动画操作 + */ + export(): Animator; + + /** 透明度,参数范围 0~1 */ + opacity(value: number): Animation; + /** 颜色值 */ + backgroundColor(color: string): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + width(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + height(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + top(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + left(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + bottom(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + right(length: number): Animation; + + /** deg的范围-180~180,从原点顺时针旋转一个deg角度 */ + rotate(deg: number): Animation; + /** deg的范围-180~180,在X轴旋转一个deg角度 */ + rotateX(deg: number): Animation; + /** deg的范围-180~180,在Y轴旋转一个deg角度 */ + rotateY(deg: number): Animation; + /** deg的范围-180~180,在Z轴旋转一个deg角度 */ + rotateZ(deg: number): Animation; + /** 同transform-function rotate3d */ + rotate3d(x: number, y: number, z: number, deg: number): Animation; + + /** + * 一个参数时,表示在X轴、Y轴同时缩放sx倍数; + * 两个参数时表示在X轴缩放sx倍数,在Y轴缩放sy倍数 + */ + scale(sx: number, sy?: number): Animation; + /** 在X轴缩放sx倍数 */ + scaleX(sx: number): Animation; + /** 在Y轴缩放sy倍数 */ + scaleY(sy: number): Animation; + /** 在Z轴缩放sy倍数 */ + scaleZ(sz: number): Animation; + /** 在X轴缩放sx倍数,在Y轴缩放sy倍数,在Z轴缩放sz倍数 */ + scale3d(sx: number, sy: number, sz: number): Animation; + + /** + * 一个参数时,表示在X轴偏移tx,单位px; + * 两个参数时,表示在X轴偏移tx,在Y轴偏移ty,单位px。 + */ + translate(tx: number, ty?: number): Animation; + /** + * 在X轴偏移tx,单位px + */ + translateX(tx: number): Animation; + /** + * 在Y轴偏移tx,单位px + */ + translateY(ty: number): Animation; + /** + * 在Z轴偏移tx,单位px + */ + translateZ(tz: number): Animation; + /** + * 在X轴偏移tx,在Y轴偏移ty,在Z轴偏移tz,单位px + */ + translate3d(tx: number, ty: number, tz: number): Animation; + + /** + * 参数范围-180~180; + * 一个参数时,Y轴坐标不变,X轴坐标延顺时针倾斜ax度; + * 两个参数时,分别在X轴倾斜ax度,在Y轴倾斜ay度 + */ + skew(ax: number, ay?: number): Animation; + /** 参数范围-180~180;Y轴坐标不变,X轴坐标延顺时针倾斜ax度 */ + skewX(ax: number): Animation; + /** 参数范围-180~180;X轴坐标不变,Y轴坐标延顺时针倾斜ay度 */ + skewY(ay: number): Animation; + + /** + * 同transform-function matrix + */ + matrix(a: number, b: number, c: number, d: number, tx: number, ty: number): Animation; + /** 同transform-function matrix3d */ + matrix3d(a1: number, b1: number, c1: number, d1: number, a2: number, b2: number, c2: number, d2: number, a3: number, b3: number, c3: number, d3: number, a4: number, b4: number, c4: number, d4: number): Animation; + } + + interface CanvasAction { + method: string; + data: Array | Array + } + type LineCapType = 'butt' | 'round' | 'square'; + type LineJoinType = 'bevel' | 'round' | 'miter'; + /** + * context只是一个记录方法调用的容器,用于生成记录绘制行为的actions数组。context跟不存在对应关系,一个context生成画布的绘制动作数组可以应用于多个。 + */ + interface CanvasContext { + /** 获取当前context上存储的绘图动作 */ + getActions(): Array + /** 清空当前的存储绘图动作 */ + clearActions(): void; + /** + * 对横纵坐标进行缩放 + * 在调用scale方法后,之后创建的路径其横纵坐标会被缩放。 + * 多次调用scale,倍数会相乘。 + * + * @param {number} scaleWidth 横坐标缩放的倍数 + * @param {number} scaleHeight 纵坐标轴缩放的倍数 + */ + scale(scaleWidth: number, scaleHeight?: number): void; + /** + * 对坐标轴进行顺时针旋转 + * 以原点为中心,原点可以用 translate方法修改。 + * 顺时针旋转当前坐标轴。多次调用rotate,旋转的角度会叠加。 + * + * @param {number} rotate 旋转角度,以弧度计。 + */ + rotate(rotate: number): void; + /** + * 对坐标原点进行缩放 + * 对当前坐标系的原点(0, 0)进行变换,默认的坐标系原点为页面左上角。 + * + * @param {number} x 水平坐标平移量 + * @param {number} y 竖直坐标平移量 + */ + translate(x: number, y: number): void; + /** + * 保存当前坐标轴的缩放、旋转、平移信息 + */ + save(): void; + /** + * 恢复之前保存过的坐标轴的缩放、旋转、平移信息 + */ + restore(): void; + /** + * 在给定的矩形区域内,清除画布上的像素 + * 清除画布上在该矩形区域内的内容。 + * + * @param {number} x 矩形区域左上角的x坐标 + * @param {number} y 矩形区域左上角的y坐标 + * @param {number} width 矩形区域的宽度 + * @param {number} height 矩形区域的高度 + */ + clearRect(x: number, y: number, width: number, height: number): void; + /** + * 在画布上绘制被填充的文本 + * + * @param {string} text 在画布上输出的文本 + * @param {number} x 绘制文本的左上角x坐标位置 + * @param {number} y 绘制文本的左上角y坐标位置 + */ + fillText(text: string, x: number, y: number): void; + /** + * 在画布上绘制图像 + * 绘制图像,图像保持原始尺寸。 + * + * @param {string} imageResource 所要绘制的图片资源。 通过chooseImage得到一个文件路径或者一个项目目录内的图片 + * @param {number} x 图像左上角的x坐标 + * @param {number} y 图像左上角的y坐标 + */ + drawImage(imageResource: string, x: number, y: number): void; + /** + * 对当前路径进行填充 + */ + fill(): void; + /** + * 对当前路径进行描边 + */ + stroke(): void; + /** + * 开始一个路径 + * 开始创建一个路径,需要调用fill或者stroke才会使用路径进行填充或描边。 + * 同一个路径内的多次setFillStyle、setStrokeStyle、setLineWidth等设置, + * 以最后一次设置为准。 + */ + beginPath(): void; + /** + * 关闭一个路径 + */ + closePath(): void; + /** + * 把路径移动到画布中的指定点,但不创建线条。 + * + * @param {number} x 目标位置的x坐标 + * @param {number} y 目标位置的y坐标 + */ + moveTo(x: number, y: number): void; + /** + * 在当前位置添加一个新点,然后在画布中创建从该点到最后指定点的路径。 + * + * @param {number} x 目标位置的x坐标 + * @param {number} y 目标位置的y坐标 + */ + lineTo(x: number, y: number): void; + /** + * 添加一个矩形路径到当前路径。 + * + * @param {number} x 矩形路径左上角的x坐标 + * @param {number} y 矩形路径左上角的y坐标 + * @param {number} width 矩形路径的宽度 + * @param {number} height 矩形路径的高度 + */ + rect(x: number, y: number, width: number, height: number): void; + /** + * 添加一个弧形路径到当前路径,顺时针绘制。 + * + * @param {number} x 矩形路径左上角的x坐标 + * @param {number} y 矩形路径左上角的y坐标 + * @param {number} radius 矩形路径左上角的y坐标 + * @param {number} startAngle 起始弧度 + * @param {number} endAngle 结束弧度 + * @param {boolean} sweepAngle 从起始弧度开始,扫过的弧度 + */ + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, sweepAngle: boolean): void; + /** + * 创建二次方贝塞尔曲线 + * + * @param {number} cpx 贝塞尔控制点的x坐标 + * @param {number} cpy 贝塞尔控制点的y坐标 + * @param {number} x 结束点的x坐标 + * @param {number} y 结束点的y坐标 + */ + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + /** + * 创建三次方贝塞尔曲线 + * + * @param {number} cp1x 第一个贝塞尔控制点的 x 坐标 + * @param {number} cp1y 第一个贝塞尔控制点的 y 坐标 + * @param {number} cp2x 第二个贝塞尔控制点的 x 坐标 + * @param {number} cp2y 第二个贝塞尔控制点的 y 坐标 + * @param {number} x 结束点的x坐标 + * @param {number} y 结束点的y坐标 + */ + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + /** + * 设置填充样式 + * + * @param {string} color 设置为填充样式的颜色。'rgb(255, 0, 0)'或'rgba(255, 0, 0, 0.6)'或'#ff0000'格式的颜色字符串 + */ + setFillStyle(color: string): void; + /** + * 设置线条样式 + * + * @param {string} color 设置为填充样式的颜色。'rgb(255, 0, 0)'或'rgba(255, 0, 0, 0.6)'或'#ff0000'格式的颜色字符串 + */ + setStrokeStyle(color: string): void; + /** + * 设置阴影 + * + * @param {number} offsetX 阴影相对于形状在水平方向的偏移 + * @param {number} offsetY 阴影相对于形状在竖直方向的偏移 + * @param {number} blur 阴影的模糊级别,数值越大越模糊 0~100 + * @param {string} color 阴影的颜色。 'rgb(255, 0, 0)'或'rgba(255, 0, 0, 0.6)'或'#ff0000'格式的颜色字符串 + */ + setShadow(offsetX: number, offsetY: number, blur: number, color: string): void; + /** + * 设置字体大小 + * + * @param {number} fontSize 字体的字号 + */ + setFontSize(fontSize: number): void; + /** + * 设置线条端点的样式 + * + * @param {LineCapType} lineCap 线条的结束端点样式。 'butt'、'round'、'square' + */ + setLineCap(lineCap: LineCapType): void; + /** + * 设置两线相交处的样式 + * @param {LineJoinType} lineJoin 两条线相交时,所创建的拐角类型 + */ + setLineJoin(lineJoin: LineJoinType): void; + /** + * 设置线条宽度 + * + * @param {number} lineWidth 线条的宽度 + */ + setLineWidth(lineWidth: number): void; + /** 设置最大斜接长度,斜接长度指的是在两条线交汇处内角和外角之间的距离。 + * 当 setLineJoin为 miter 时才有效。 + * 超过最大倾斜长度的,连接处将以 lineJoin 为 bevel 来显示 + * + * @param {number} miterLimit 最大斜接长度 + */ + setMiterLimit(miterLimit: number): void; + } + /** + * 创建并返回绘图上下文context对象。 + * context只是一个记录方法调用的容器, + * 用于生成记录绘制行为的actions数组。c + * ontext跟不存在对应关系, + * 一个context生成画布的绘制动作数组可以应用于多个。 + */ + function createContext(): CanvasContext; + + interface DrawCanvasOptions { + /** 画布标识,传入 的 cavas-id */ + canvasId: number | string; + /** + * 绘图动作数组,由 wx.createContext 创建的 context, + * 调用 getActions 方法导出绘图动作数组。 + */ + actions: Array; + } + /** + * 绘制画布 + */ + function drawCanvas(options: DrawCanvasOptions): void; + + /** + * 收起键盘。 + */ + function hideKeyboard(): void; + + interface LoginResponse { + /** 调用结果 */ + errMsg: string; + /** 用户允许登录后,回调内容会带上 code(有效期五分钟), + * 开发者需要将 code 发送到开发者服务器后台, + * 使用code 换取 session_key api, + * 将 code 换成 openid 和 session_key */ + code: string; + } + interface LoginOptions { + /** 接口调用成功的回调函数 */ + success?: (res: LoginResponse) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + + /** + * 调用接口获取登录凭证(code)进而换取用户登录态信息, + * 包括用户的唯一标识(openid) 及本次登录的 会话密钥(session_key)。 + * 用户数据的加解密通讯需要依赖会话密钥完成。 + */ + function login(option: LoginOptions): void; + + interface UserInfo { + nickName: string; + avatarUrl: string; + gender: number; + province: string; + city: string; + country: string; + } + interface UserInfoResponse { + /** 用户信息对象,不包含 openid 等敏感信息 */ + userInfo: UserInfo; + /** 不包括敏感信息的原始数据字符串,用于计算签名。 */ + rawData: string; + /** 使用 sha1( rawData + sessionkey ) 得到字符串,用于校验用户信息。 */ + signature: string; + /** 包括敏感数据在内的完整用户信息的加密数据,详细见加密数据解密算法 */ + encryptData: string; + } + interface GetUserInfoOptions { + /** 接口调用成功的回调函数 */ + success?: (res: UserInfoResponse) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 获取用户信息,需要先调用 wx.login 接口。 + */ + function getUserInfo(options: GetUserInfoOptions): void; + + type PaymentSignType = 'MD5'; + interface RequestPaymentOptions { + /** 时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间 */ + timeStamp: string|number; + /** 随机字符串,长度为32个字符以下。 */ + nonceStr: string; + /** 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=* */ + package: string; + /** 签名算法,暂支持 MD5 */ + signType: PaymentSignType; + /** 签名,具体签名方案参见微信公众号支付帮助文档; */ + paySign: string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 发起微信支付。 + */ + function requestPayment(options: RequestPaymentOptions): void; +} + + +interface Page { + /** + * setData 函数用于将数据从逻辑层发送到视图层, + * 同时改变对应的 this.data 的值。 + * 注意: + * 1. 直接修改 this.data 无效,无法改变页面的状态,还会造成数据不一致。 + * 2. 单次设置的数据不能超过1024kB,请尽量避免一次设置过多的数据。 + */ + setData(data: any): void; +} +interface PageConstructor { + /** + * Page() 函数用来注册一个页面。 + * 接受一个 object 参数,其指定页面的初始数据、生命周期函数、事件处理函数等。 + */ + (options: wx.PageOptions): void; +} +declare var Page: PageConstructor; + + +interface App { + /** + * getCurrentPage() 函数用户获取当前页面的实例。 + */ + getCurrentPage(): Page; +} +interface AppConstructor { + /** + * App() 函数用来注册一个小程序。 + * 接受一个 object 参数,其指定小程序的生命周期函数等。 + */ + (options: wx.AppOptions): void; +} +declare var App: AppConstructor; + +/** + * 我们提供了全局的 getApp() 函数,可以获取到小程序实例。 + */ +declare function getApp(): App; From 727c305d5e32c5dec79b8f407013aad6d8cf4abd Mon Sep 17 00:00:00 2001 From: Denis Date: Wed, 28 Sep 2016 11:11:29 -0400 Subject: [PATCH 050/554] Added more methods to Turf (#11558) * Added more methods to Turf - circle - geojsonType - propReduce - coordAll - tesselate * Replace Object with GeoJSON --- turf/turf-tests.ts | 20 +++++- turf/turf.d.ts | 166 ++++++++++++++++++++++++++++++++------------- 2 files changed, 139 insertions(+), 47 deletions(-) diff --git a/turf/turf-tests.ts b/turf/turf-tests.ts index 31462adc51..0e887e2e3e 100644 --- a/turf/turf-tests.ts +++ b/turf/turf-tests.ts @@ -499,8 +499,26 @@ turf.collect(polygons, points, 'population', 'values') /////////////////////////////////////////// // Tests Assertions /////////////////////////////////////////// +// -- Test bbox -- turf.bbox(polygon1) turf.bbox(point1) turf.bbox(lineString1) turf.bbox(multiLineString1) -turf.bbox(multiPolygon1) \ No newline at end of file +turf.bbox(multiPolygon1) + +// -- Test circle -- +turf.circle(point1, 10) +turf.circle(point1, 10, 32) +turf.circle(point1, 10, 64, 'miles') + +// -- Test geojsonType -- +turf.geojsonType(point1, 'point', 'Test') + +// -- Test propReduce -- +turf.propReduce(point1, (memo, coord) => {}, 'point') + +// -- Test coordAll -- +turf.coordAll(polygon1) + +// -- Test tesselate -- +turf.tesselate(polygon1) \ No newline at end of file diff --git a/turf/turf.d.ts b/turf/turf.d.ts index e90cf69276..773802a103 100644 --- a/turf/turf.d.ts +++ b/turf/turf.d.ts @@ -80,16 +80,22 @@ ASSERTIONS - [ ] featureOf - [ ] collectionOf - [x] bbox -- [ ] circle -- [ ] geojsonType -- [ ] propReduce -- [ ] coordAll -- [ ] tesselate +- [x] circle +- [x] geojsonType +- [x] propReduce +- [x] coordAll +- [x] tesselate */ declare const turf: turf.TurfStatic; declare const TemplateUnits: 'miles' | 'nauticalmiles' | 'degrees' | 'radians' | 'inches' | 'yards' | 'meters' | 'metres' | 'kilometers' | 'kilometres' declare const TemplateType: 'point'| 'points' | 'polygon' | 'polygons' +declare interface OptionsRandom { + bbox?: Array + num_vertices?: number + max_radial_length?: number +} +declare type PropReduceCallback = (memo: any, coord: GeoJSON.Feature | GeoJSON.FeatureCollection) => any declare module turf { interface TurfStatic { ////////////////////////////////////////////////////// @@ -169,11 +175,79 @@ declare module turf { * var bboxPolygon = turf.bboxPolygon(bbox); * * //=bbox - * + * * //=bboxPolygon */ bbox(bbox: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; + /** + * Takes a {@link Point} and calculates the circle polygon given a radius in degrees, radians, miles, or kilometers; and steps for precision. + * + * @name circle + * @param {Feature} center center point + * @param {number} radius radius of the circle + * @param {number} [steps=64] number of steps + * @param {string} [units=kilometers] miles, kilometers, degrees, or radians + * @returns {Feature} circle polygon + * @example + * var center = point([-75.343, 39.984]); + * var radius = 5; + * var steps = 10; + * var units = 'kilometers'; + * + * var circle = turf.circle(center, radius, steps, units); + * + * //=circle + */ + circle(center: GeoJSON.Feature, radius: number, steps?: number, units?: typeof TemplateUnits): GeoJSON.Feature; + + + /** + * Enforce expectations about types of GeoJSON objects for Turf. + * + * @name geojsonType + * @param {GeoJSON} value any GeoJSON object + * @param {string} type expected GeoJSON type + * @param {string} name name of calling function + * @throws {Error} if value is not the expected type. + */ + geojsonType(value: GeoJSON.Feature | GeoJSON.FeatureCollection, type: string, name: string): void + + /** + * Reduce properties in any GeoJSON object into a single value, similar to how Array.reduce works. However, in this case we lazily run the reduction, so an array of all properties is unnecessary. + * + * @name propReduce + * @param {GeoJSON} layer any GeoJSON object + * @param {Function} callback a method that takes (memo, coord) and returns a new memo + * @param {*} memo the starting value of memo: can be any type. + * @return {*} combined value + */ + propReduce(layer: GeoJSON.Feature | GeoJSON.FeatureCollection, callback: PropReduceCallback, memo: any): any + + /** + * Get all coordinates from any GeoJSON object, returning an array of coordinate arrays. + * + * @name coordAll + * @param {GeoJSON} layer any GeoJSON object + * @returns {Array>} coordinate position array + */ + coordAll(layer: GeoJSON.Feature | GeoJSON.FeatureCollection): Array> + + /** + * Tesselates a {@link Feature} into a {@link FeatureCollection} of triangles using [earcut](https://github.com/mapbox/earcut). + * + * @name tesselate + * @param {Feature} polygon the polygon to tesselate + * @returns {FeatureCollection} a geometrycollection feature + * @example + * var polygon = turf.random('polygon').features[0]; + * + * var triangles = turf.tesselate(polygon); + * + * //=triangles + */ + tesselate(poly: GeoJSON.Feature): GeoJSON.FeatureCollection + /** * Takes a bbox and returns an equivalent polygon. * @param bbox An Array of bounding box coordinates in the form: [xLow, yLow, xHigh, yHigh] @@ -298,7 +372,7 @@ declare module turf { */ buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; - buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; @@ -343,7 +417,7 @@ declare module turf { * If they share a border, returns the border if they don't intersect, returns undefined. * * @name [intersect](http://turfjs.org/docs/#intersect) - * @param {Feature} poly1 + * @param {Feature} poly1 * @param {Feature} poly2 * @returns {Feature|undefined} A feature representing the point(s) they share (in case of a {Point} or {MultiPoint}), the borders they share (in case of a {LineString} or a {MultiLineString}), the area they share (in case of {Polygon} or {MultiPolygon}). If they do not share any point, returns `undefined`. * @example @@ -456,7 +530,7 @@ declare module turf { /** * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}. - * + * * @name [featureCollection](http://turfjs.org/docs/#featurecollection) * @param {Feature[]} features input features * @returns {FeatureCollection} a FeatureCollection of input features @@ -497,7 +571,7 @@ declare module turf { /** * Creates a {@link LineString} based on a coordinate array. Properties can be added optionally. - * + * * @name [lineString](http://turfjs.org/docs/#linestring) * @param {Array>} coordinates an array of Positions * @param {Object=} properties an Object of key-value pairs to add as properties @@ -525,7 +599,7 @@ declare module turf { /** * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. - * + * * @name [multiLineString](http://turfjs.org/docs/#multilinestring) * @param {Array>>} coordinates an array of LineStrings * @param {Object=} properties an Object of key-value pairs to add as properties @@ -541,7 +615,7 @@ declare module turf { /** * Takes coordinates and properties (optional) and returns a new {@link Point} feature. - * + * * @name [point](http://turfjs.org/docs/#point) * @param {Array} coordinates longitude, latitude position (each in decimal degrees) * @param {Object=} properties an Object that is used as the {@link Feature}'s @@ -556,7 +630,7 @@ declare module turf { /** * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. - * + * * @name [multiPoint](http://turfjs.org/docs/#multipoint) * @param {Array>} coordinates an array of Positions * @param {Object=} properties an Object of key-value pairs to add as properties @@ -572,7 +646,7 @@ declare module turf { /** * Takes an array of LinearRings and optionally an {@link Object} with properties and returns a {@link Polygon} feature. - * + * * @name [polygon](http://turfjs.org/docs/#polygon) * @param {Array>>} coordinates an array of LinearRings * @param {Object=} properties a properties object @@ -595,7 +669,7 @@ declare module turf { /** * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. - * + * * @name [multiPolygon](http://turfjs.org/docs/#multipolygon) * @param {Array>>>} coordinates an array of Polygons * @param {Object=} properties an Object of key-value pairs to add as properties @@ -664,15 +738,15 @@ declare module turf { * * //=polygons */ - random(type?: typeof TemplateType, count?: number, options?: { - bbox?: Array - num_vertices?: number - max_radial_length?: number - }): GeoJSON.FeatureCollection; + random(type?: 'point', count?: number, options?: OptionsRandom): GeoJSON.FeatureCollection; + random(type?: 'points', count?: number, options?: OptionsRandom): GeoJSON.FeatureCollection; + random(type?: 'polygon', count?: number, options?: OptionsRandom): GeoJSON.FeatureCollection; + random(type?: 'polygons', count?: number, options?: OptionsRandom): GeoJSON.FeatureCollection; + random(type?: typeof TemplateType, count?: number, options?: OptionsRandom): GeoJSON.FeatureCollection; /** * Takes a {@link FeatureCollection} and returns a FeatureCollection with given number of {@link Feature|features} at random. - * + * * @name [sample](http://turfjs.org/docs/#sample) * @param {FeatureCollection} featurecollection set of input features * @param {number} num number of features to select @@ -694,7 +768,7 @@ declare module turf { /** * Takes a bounding box and a cell size in degrees and returns a {@link FeatureCollection} of flat-topped hexagons ({@link Polygon} features) aligned in an "odd-q" vertical grid as described in [Hexagonal Grids](http://www.redblobgames.com/grids/hexagons/). - * + * * @name [hexGrid](http://turfjs.org/docs/#hexgrid) * @param {Array} bbox bounding box in [minX, minY, maxX, maxY] order * @param {number} cellSize dimension of cell in specified units @@ -737,7 +811,7 @@ declare module turf { pointGrid( bbox: Array, cellSize: number, - units?: typeof TemplateUnits + units?: typeof TemplateUnits ): GeoJSON.FeatureCollection; /** @@ -835,7 +909,7 @@ declare module turf { * var poly = polygon([[[-81, 41], [-81, 47], [-72, 47], [-72, 41], [-81, 41]]]) * * var isInside = turf.inside(pt, poly) - * + * * //=isInside */ inside( @@ -857,10 +931,10 @@ declare module turf { * var pt2 = point([-77, 38]) * var poly1 = polygon([[[-81, 41], [-81, 47], [-72, 47], [-72, 41], [-81, 41]]], {pop: 1000}) * var poly2 = polygon([[[-81, 35], [-81, 41], [-72, 41], [-72, 35], [-81, 35]]], {pop: 3000}) - * + * * var points = featureCollection([pt1, pt2]) * var polygons = featureCollection([poly1, poly2]) - * + * * var tagged = turf.tag(points, polygons, 'pop', 'population') * //=tagged */ @@ -1181,27 +1255,27 @@ declare module "@turf/bbox" { export = bbox; } -// declare module "@turf/circle" { -// const circle: typeof turf.circle; -// export = circle; -// } +declare module "@turf/circle" { + const circle: typeof turf.circle; + export = circle; +} -// declare module "@turf/geojsonType" { -// const geojsonType: typeof turf.geojsonType; -// export = geojsonType; -// } +declare module "@turf/geojsonType" { + const geojsonType: typeof turf.geojsonType; + export = geojsonType; +} -// declare module "@turf/propReduce" { -// const propReduce: typeof turf.propReduce; -// export = propReduce; -// } +declare module "@turf/propReduce" { + const propReduce: typeof turf.propReduce; + export = propReduce; +} -// declare module "@turf/coordAll" { -// const coordAll: typeof turf.coordAll; -// export = coordAll; -// } +declare module "@turf/coordAll" { + const coordAll: typeof turf.coordAll; + export = coordAll; +} -// declare module "@turf/tesselate" { -// const tesselate: typeof turf.tesselate; -// export = tesselate; -// } +declare module "@turf/tesselate" { + const tesselate: typeof turf.tesselate; + export = tesselate; +} From 9fadbac5f835d7ad1b0b2d7241e25bf2c8c33d72 Mon Sep 17 00:00:00 2001 From: Denis Carriere Date: Wed, 28 Sep 2016 11:28:19 -0400 Subject: [PATCH 051/554] Implemented cheap-ruler definition --- cheap-ruler/cheap-ruler-tests.ts | 60 ++++++++ cheap-ruler/cheap-ruler.d.ts | 226 +++++++++++++++++++++++++++++++ 2 files changed, 286 insertions(+) create mode 100644 cheap-ruler/cheap-ruler-tests.ts create mode 100644 cheap-ruler/cheap-ruler.d.ts diff --git a/cheap-ruler/cheap-ruler-tests.ts b/cheap-ruler/cheap-ruler-tests.ts new file mode 100644 index 0000000000..67388e52fd --- /dev/null +++ b/cheap-ruler/cheap-ruler-tests.ts @@ -0,0 +1,60 @@ +/// + +import * as cheapRuler from 'cheap-ruler' + +// -- Fixtures -- +const unit = 'miles' +const lineString: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "LineString", + "coordinates": [ + [-77.031669, 38.878605], + [-77.029609, 38.881946], + [-77.020339, 38.884084], + [-77.025661, 38.885821], + [-77.021884, 38.889563], + [-77.019824, 38.892368] + ] + } +} +const line = lineString.geometry.coordinates +const polygon = [[ + [-67.031, 50.458], [-67.031, 50.534], [-66.929, 50.534], + [-66.929, 50.458], [-67.031, 50.458] +]] +const points = [ + [-67.031, 50.458], [-67.031, 50.534], + [-66.929, 50.534], [-66.929, 50.458] +] + +// -- Test initiators -- +cheapRuler(35.05) +cheapRuler(35.05, 'miles') +cheapRuler(35.05, unit) +cheapRuler.fromTile(1567, 12) +cheapRuler.fromTile(1567, 12, 'miles') +cheapRuler.fromTile(1567, 12, unit) + +// -- Test units -- +cheapRuler.units +cheapRuler.units.miles +cheapRuler.units.kilometers +50 * cheapRuler.units.yards / cheapRuler.units.meters + +// -- Test cheapRuler -- +const ruler = cheapRuler(35.05, 'kilometers') + +console.log(ruler.distance([30.5, 50.5], [30.51, 50.49])) +ruler.bearing([30.5, 50.5], [30.51, 50.49]) +ruler.destination([30.5, 50.5], 0.1, 90) +ruler.lineDistance(points) +ruler.area(polygon) +ruler.along(line, 2.5) +ruler.pointOnLine(line, [-67.04, 50.5]).point +ruler.lineSlice([-67.04, 50.5], [-67.05, 50.56], line) +ruler.lineSliceAlong(10, 20, line) +ruler.bufferPoint([30.5, 50.5], 0.01) +ruler.bufferBBox([30.5, 50.5, 31, 51], 0.2) +ruler.insideBBox([30.5, 50.5], [30, 50, 31, 51]) \ No newline at end of file diff --git a/cheap-ruler/cheap-ruler.d.ts b/cheap-ruler/cheap-ruler.d.ts new file mode 100644 index 0000000000..97ad51730e --- /dev/null +++ b/cheap-ruler/cheap-ruler.d.ts @@ -0,0 +1,226 @@ +// Type definitions for cheap-ruler 2.4.1 +// Project: https://github.com/mapbox/cheap-ruler +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "cheap-ruler" { + interface TemplateUnits { + kilometers: number + miles: number + nauticalmiles: number + meters: number + metres: number + yards: number + feet: number + inches: number + } + interface InterfacePointOnLine { + point: Array + index: number + t: number + } + class CheapRuler { + /** + * Given two points of the form [longitude, latitude], returns the distance. + * + * @name distance + * @param {Array} a point [longitude, latitude] + * @param {Array} b point [longitude, latitude] + * @returns {number} distance + * @example + * var distance = ruler.distance([30.5, 50.5], [30.51, 50.49]); + * //=distance + */ + distance(a: Array, b: Array): number; + + /** + * Returns the bearing between two points in angles. + * + * @name bearing + * @param {Array} a point [longitude, latitude] + * @param {Array} b point [longitude, latitude] + * @returns {number} bearing + * @example + * var bearing = ruler.bearing([30.5, 50.5], [30.51, 50.49]); + * //=bearing + */ + bearing(a: Array, b: Array): number; + + /** + * Returns a new point given distance and bearing from the starting point. + * + * @name destination + * @param {Array} p point [longitude, latitude] + * @param {number} dist distance + * @param {number} bearing + * @returns {Array} point [longitude, latitude] + * @example + * var point = ruler.destination([30.5, 50.5], 0.1, 90); + * //=point + */ + destination(p: Array, dist: number, bearing: number): Array; + + /** + * Given a line (an array of points), returns the total line distance. + * + * @name lineDistance + * @param {Array>} points [longitude, latitude] + * @returns {number} total line distance + * @example + * var length = ruler.lineDistance([ + * [-67.031, 50.458], [-67.031, 50.534], + * [-66.929, 50.534], [-66.929, 50.458] + * ]); + * //=length + */ + lineDistance(points: Array>): number; + + /** + * Given a polygon (an array of rings, where each ring is an array of points), returns the area. + * + * @name area + * @param {Array>>} polygon + * @returns {number} area value in the specified units (square kilometers by default) + * @example + * var area = ruler.area([[ + * [-67.031, 50.458], [-67.031, 50.534], [-66.929, 50.534], + * [-66.929, 50.458], [-67.031, 50.458] + * ]]); + * //=area + */ + area(polygon: Array>>): number; + + /** + * Returns the point at a specified distance along the line. + * + * @name along + * @param {Array>} line + * @param {number} dist distance + * @returns {Array} point [longitude, latitude] + * @example + * var point = ruler.along(line, 2.5); + * //=point + */ + along(line: Array>, dist: number): Array + + /** + * Returns an object of the form {point, index} where point is closest point on the line from the given point, and index is the start index of the segment with the closest point. + * + * @pointOnLine + * @param {Array>} line + * @param {Array} p point [longitude, latitude] + * @returns {Object} {point, index} + * @example + * var point = ruler.pointOnLine(line, [-67.04, 50.5]).point; + * //=point + */ + pointOnLine(line: Array>, p: Array): InterfacePointOnLine + + /** + * Returns a part of the given line between the start and the stop points (or their closest points on the line). + * + * @name lineSlice + * @param {Array} start point [longitude, latitude] + * @param {Array} stop point [longitude, latitude] + * @param {Array>} line + * @returns {Array>} line part of a line + * @example + * var line2 = ruler.lineSlice([-67.04, 50.5], [-67.05, 50.56], line1); + * //=line2 + */ + lineSlice(start: Array, stop: Array, line: Array>): Array> + + /** + * Returns a part of the given line between the start and the stop points indicated by distance along the line. + * + * @name lineSliceAlong + * @param {number} start distance + * @param {number} stop distance + * @param {Array>} line + * @returns {Array>} line part of a line + * @example + * var line2 = ruler.lineSliceAlong(10, 20, line1); + * //=line2 + */ + lineSliceAlong(start: number, stop: number, line: Array>): Array> + + /** + * Given a point, returns a bounding box object ([w, s, e, n]) created from the given point buffered by a given distance. + * + * @name bufferPoint + * @param {Array} p point [longitude, latitude] + * @param {number} buffer + * @returns {Array} box object ([w, s, e, n]) + * @example + * var bbox = ruler.bufferPoint([30.5, 50.5], 0.01); + * //=bbox + */ + bufferPoint(p: Array, buffer: number): Array + + /** + * Given a bounding box, returns the box buffered by a given distance. + * + * @name bufferBBox + * @param {Array} box object ([w, s, e, n]) + * @param {number} buffer + * @returns {Array} box object ([w, s, e, n]) + * @example + * var bbox = ruler.bufferBBox([30.5, 50.5, 31, 51], 0.2); + * //=bbox + */ + bufferBBox(bbox: Array, buffer: number): Array + + /** + * Returns true if the given point is inside in the given bounding box, otherwise false. + * + * @name insideBBox + * @param {Array} p point [longitude, latitude] + * @param {Array} box object ([w, s, e, n]) + * @returns {boolean} + * @example + * var inside = ruler.insideBBox([30.5, 50.5], [30, 50, 31, 51]); + * //=inside + */ + insideBBox(p: Array, bbox: Array): boolean + } + /** + * A collection of very fast approximations to common geodesic measurements. Useful for performance-sensitive code that measures things on a city scale. + * + * @name cheapRuler + * @param {number} lat latitude + * @param {string} [units='kilometers'] + * @returns {Object} CheapRuler + * @example + * var ruler = cheapRuler(35.05, 'miles'); + * //=ruler + */ + function cheapRuler(lat: number, units?: string): CheapRuler; + namespace cheapRuler { + /** + * Multipliers for converting between units. + * + * @name units + * @example + * // convert 50 meters to yards + * 50 * cheapRuler.units.yards / cheapRuler.units.meters; + */ + const units: TemplateUnits + + /** + * Creates a ruler object from tile coordinates (y and z). Convenient in tile-reduce scripts. + * + * @name fromTile + * @param {number} y + * @param {number} z + * @param {string} [units='kilometers'] + * @returns {Object} CheapRuler + * @example + * var ruler = cheapRuler.fromTile(1567, 12); + * //=ruler + */ + function fromTile(y: number, z: number, units?: string) + } + export = cheapRuler +} \ No newline at end of file From 7898c8c4fabe1dc79bc68066478697f00f516f7e Mon Sep 17 00:00:00 2001 From: Denis Carriere Date: Wed, 28 Sep 2016 11:29:48 -0400 Subject: [PATCH 052/554] Remove GeoJSON dependency --- cheap-ruler/cheap-ruler.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/cheap-ruler/cheap-ruler.d.ts b/cheap-ruler/cheap-ruler.d.ts index 97ad51730e..dd0dcb9dbc 100644 --- a/cheap-ruler/cheap-ruler.d.ts +++ b/cheap-ruler/cheap-ruler.d.ts @@ -3,8 +3,6 @@ // Definitions by: Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare module "cheap-ruler" { interface TemplateUnits { kilometers: number From 4f3c8528c27c42684adea93d5608bc9f90e9ac76 Mon Sep 17 00:00:00 2001 From: Denis Carriere Date: Wed, 28 Sep 2016 11:38:10 -0400 Subject: [PATCH 053/554] Cheap-ruler fixes - Removed GeoJSON from tests - Added return-type to fromTile --- cheap-ruler/cheap-ruler-tests.ts | 6 +++--- cheap-ruler/cheap-ruler.d.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cheap-ruler/cheap-ruler-tests.ts b/cheap-ruler/cheap-ruler-tests.ts index 67388e52fd..2a1bf6521d 100644 --- a/cheap-ruler/cheap-ruler-tests.ts +++ b/cheap-ruler/cheap-ruler-tests.ts @@ -4,7 +4,7 @@ import * as cheapRuler from 'cheap-ruler' // -- Fixtures -- const unit = 'miles' -const lineString: GeoJSON.Feature = { +const lineString = { "type": "Feature", "properties": {}, "geometry": { @@ -44,9 +44,9 @@ cheapRuler.units.kilometers 50 * cheapRuler.units.yards / cheapRuler.units.meters // -- Test cheapRuler -- -const ruler = cheapRuler(35.05, 'kilometers') +const ruler = cheapRuler(35.05) -console.log(ruler.distance([30.5, 50.5], [30.51, 50.49])) +ruler.distance([30.5, 50.5], [30.51, 50.49]) ruler.bearing([30.5, 50.5], [30.51, 50.49]) ruler.destination([30.5, 50.5], 0.1, 90) ruler.lineDistance(points) diff --git a/cheap-ruler/cheap-ruler.d.ts b/cheap-ruler/cheap-ruler.d.ts index dd0dcb9dbc..300af9ee5d 100644 --- a/cheap-ruler/cheap-ruler.d.ts +++ b/cheap-ruler/cheap-ruler.d.ts @@ -218,7 +218,7 @@ declare module "cheap-ruler" { * var ruler = cheapRuler.fromTile(1567, 12); * //=ruler */ - function fromTile(y: number, z: number, units?: string) + function fromTile(y: number, z: number, units?: string): CheapRuler; } export = cheapRuler } \ No newline at end of file From bf34b77b69fbba586273d101a3fb2538b1c080ea Mon Sep 17 00:00:00 2001 From: Denis Carriere Date: Wed, 28 Sep 2016 11:59:07 -0400 Subject: [PATCH 054/554] Update JSDocs cheap-ruler Update based on comments https://github.com/mapbox/cheap-ruler/pull/20 - Removed `{@name}` - Changed {Object} to {CheapRuler} --- cheap-ruler/cheap-ruler.d.ts | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/cheap-ruler/cheap-ruler.d.ts b/cheap-ruler/cheap-ruler.d.ts index 300af9ee5d..187b27ea82 100644 --- a/cheap-ruler/cheap-ruler.d.ts +++ b/cheap-ruler/cheap-ruler.d.ts @@ -23,7 +23,6 @@ declare module "cheap-ruler" { /** * Given two points of the form [longitude, latitude], returns the distance. * - * @name distance * @param {Array} a point [longitude, latitude] * @param {Array} b point [longitude, latitude] * @returns {number} distance @@ -36,7 +35,6 @@ declare module "cheap-ruler" { /** * Returns the bearing between two points in angles. * - * @name bearing * @param {Array} a point [longitude, latitude] * @param {Array} b point [longitude, latitude] * @returns {number} bearing @@ -49,7 +47,6 @@ declare module "cheap-ruler" { /** * Returns a new point given distance and bearing from the starting point. * - * @name destination * @param {Array} p point [longitude, latitude] * @param {number} dist distance * @param {number} bearing @@ -63,7 +60,6 @@ declare module "cheap-ruler" { /** * Given a line (an array of points), returns the total line distance. * - * @name lineDistance * @param {Array>} points [longitude, latitude] * @returns {number} total line distance * @example @@ -78,7 +74,6 @@ declare module "cheap-ruler" { /** * Given a polygon (an array of rings, where each ring is an array of points), returns the area. * - * @name area * @param {Array>>} polygon * @returns {number} area value in the specified units (square kilometers by default) * @example @@ -93,7 +88,6 @@ declare module "cheap-ruler" { /** * Returns the point at a specified distance along the line. * - * @name along * @param {Array>} line * @param {number} dist distance * @returns {Array} point [longitude, latitude] @@ -119,7 +113,6 @@ declare module "cheap-ruler" { /** * Returns a part of the given line between the start and the stop points (or their closest points on the line). * - * @name lineSlice * @param {Array} start point [longitude, latitude] * @param {Array} stop point [longitude, latitude] * @param {Array>} line @@ -133,7 +126,6 @@ declare module "cheap-ruler" { /** * Returns a part of the given line between the start and the stop points indicated by distance along the line. * - * @name lineSliceAlong * @param {number} start distance * @param {number} stop distance * @param {Array>} line @@ -147,7 +139,6 @@ declare module "cheap-ruler" { /** * Given a point, returns a bounding box object ([w, s, e, n]) created from the given point buffered by a given distance. * - * @name bufferPoint * @param {Array} p point [longitude, latitude] * @param {number} buffer * @returns {Array} box object ([w, s, e, n]) @@ -160,7 +151,6 @@ declare module "cheap-ruler" { /** * Given a bounding box, returns the box buffered by a given distance. * - * @name bufferBBox * @param {Array} box object ([w, s, e, n]) * @param {number} buffer * @returns {Array} box object ([w, s, e, n]) @@ -173,7 +163,6 @@ declare module "cheap-ruler" { /** * Returns true if the given point is inside in the given bounding box, otherwise false. * - * @name insideBBox * @param {Array} p point [longitude, latitude] * @param {Array} box object ([w, s, e, n]) * @returns {boolean} @@ -186,10 +175,9 @@ declare module "cheap-ruler" { /** * A collection of very fast approximations to common geodesic measurements. Useful for performance-sensitive code that measures things on a city scale. * - * @name cheapRuler * @param {number} lat latitude * @param {string} [units='kilometers'] - * @returns {Object} CheapRuler + * @returns {CheapRuler} * @example * var ruler = cheapRuler(35.05, 'miles'); * //=ruler @@ -199,7 +187,6 @@ declare module "cheap-ruler" { /** * Multipliers for converting between units. * - * @name units * @example * // convert 50 meters to yards * 50 * cheapRuler.units.yards / cheapRuler.units.meters; @@ -209,11 +196,10 @@ declare module "cheap-ruler" { /** * Creates a ruler object from tile coordinates (y and z). Convenient in tile-reduce scripts. * - * @name fromTile * @param {number} y * @param {number} z * @param {string} [units='kilometers'] - * @returns {Object} CheapRuler + * @returns {CheapRuler} * @example * var ruler = cheapRuler.fromTile(1567, 12); * //=ruler From a4a33e265cf12ce775a9a0e54897fdabf2f6b3ce Mon Sep 17 00:00:00 2001 From: Artur Eshenbrener Date: Wed, 28 Sep 2016 19:20:57 +0300 Subject: [PATCH 055/554] [bluebird] document .suppressUnhandledRejections http://bluebirdjs.com/docs/api/suppressunhandledrejections.html --- bluebird/bluebird.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/bluebird/bluebird.d.ts b/bluebird/bluebird.d.ts index 35b506542a..3dc66b78f0 100644 --- a/bluebird/bluebird.d.ts +++ b/bluebird/bluebird.d.ts @@ -317,6 +317,13 @@ class Bluebird implements Bluebird.Thenable, Bluebird.Inspection { */ cancel(): void; + /** + * Basically sugar for doing: somePromise.catch(function(){}); + * + * Which is needed in case error handlers are attached asynchronously to the promise later, which would otherwise result in premature unhandled rejection reporting. + */ + suppressUnhandledRejections(): void; + /** * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. * From e79245412e9faeb362cac8e46beb1a8767e2f88d Mon Sep 17 00:00:00 2001 From: gatsbimantico Date: Wed, 28 Sep 2016 21:21:30 +0200 Subject: [PATCH 056/554] gapi.analytics --- gapi.analytics/gapi.analytics.d.ts | 124 +++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 gapi.analytics/gapi.analytics.d.ts diff --git a/gapi.analytics/gapi.analytics.d.ts b/gapi.analytics/gapi.analytics.d.ts new file mode 100644 index 0000000000..36cca1263c --- /dev/null +++ b/gapi.analytics/gapi.analytics.d.ts @@ -0,0 +1,124 @@ +// Type definitions for Google Analytics API + +/// + +declare namespace gapi.client.analytics {} +declare namespace gapi.client.analytics.provisioning { + export function createAccountTicket() : Promise; +} + +interface DataQuery { + "ids" ?: string; + "start-date" ?: string; + "30daysAgo" ?: string; + "end-date" ?: string; + "yesterday" ?: string; + "metrics" ?: string; + "dimensions" ?: string; + "sort" ?: string; + "filters" ?: string; + "segment" ?: string; + "samplingLevel" ?: string; + "include-empty-rows" ?: string; + "start-index" ?: string; + "max-results" ?: string; +} +declare namespace gapi.client.analytics.data {} +declare namespace gapi.client.analytics.data.ga { + export function get(data ?: DataQuery) : Promise; +} +declare namespace gapi.client.analytics.data.mcf { + export function get(data ?: DataQuery) : Promise; +} +declare namespace gapi.client.analytics.data.realtime { + export function get(data ?: DataQuery) : Promise; +} + +interface AnalyticsParameter { + "type" ?: string; + "description" ?: string; + "default" ?: string; + "enum" ?: string[]; + "enumDescriptions" ?: string[]; + "location" ?: string; +} +declare namespace gapi.client.analytics.kB { + export class parameters { + alt: AnalyticsParameter; + fields: AnalyticsParameter; + key: AnalyticsParameter; + oauth_token: AnalyticsParameter; + prettyPrint: AnalyticsParameter; + quotaUser: AnalyticsParameter; + userIP: AnalyticsParameter; + } +} + +interface View { + accountId ?: string; + webPropertyId ?: string; + webViewId ?: string; +} +declare namespace gapi.client.analytics.management {} +declare namespace gapi.client.analytics.managementaccountSummaries { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.managementaccountUserLinks { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.accounts { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.customDataSources { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.customDimensions { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.customMetrics { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.experiments { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.filters { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.goals { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.profileFilterLinks { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.profileUserLinks { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.profiles { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.remarketingAudience { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.segments { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.unsampledReports { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.uploads { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.webPropertyAdWordsLinks { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.webproperties { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.webpropertyUserLinks { + export function list(view ?: View) : Promise; +} + +declare namespace gapi.client.analytics.metadata {} +declare namespace gapi.client.analytics.metadata.column { + export function list() : Promise; +} From b8abf4a0e491270df1369d953fdb0af63379947f Mon Sep 17 00:00:00 2001 From: Sean Kelley Date: Wed, 28 Sep 2016 12:20:33 -0700 Subject: [PATCH 057/554] Add typings for shallowequal. --- shallowequal/shallowequal-tests.ts | 12 ++++++++++++ shallowequal/shallowequal.d.ts | 9 +++++++++ 2 files changed, 21 insertions(+) create mode 100644 shallowequal/shallowequal-tests.ts create mode 100644 shallowequal/shallowequal.d.ts diff --git a/shallowequal/shallowequal-tests.ts b/shallowequal/shallowequal-tests.ts new file mode 100644 index 0000000000..73c644c770 --- /dev/null +++ b/shallowequal/shallowequal-tests.ts @@ -0,0 +1,12 @@ +/// + +import shallowEqual = require('shallowequal'); + +const a = {}, b = {}; +function compare(a: any, b: any, indexOrKey?: number | string) { + return false; +} + +shallowEqual(a, b); +shallowEqual(a, b, compare); +shallowEqual(a, b, compare, {}); diff --git a/shallowequal/shallowequal.d.ts b/shallowequal/shallowequal.d.ts new file mode 100644 index 0000000000..d3971e15c9 --- /dev/null +++ b/shallowequal/shallowequal.d.ts @@ -0,0 +1,9 @@ +// Type definitions for shallowequal v0.2.2 +// Project: https://github.com/dashed/shallowequal +// Definitions by: Sean Kelley +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'shallowequal' { + function shallowEqual(objA: any, objB: any, compare?: (objA: any, objB: any, indexOrKey?: number | string) => boolean, compareContext?: any): boolean; + export = shallowEqual; +} From cfdd3db404999e24047ccd0d74a71c411f02ca3b Mon Sep 17 00:00:00 2001 From: Matt Rohr Date: Wed, 28 Sep 2016 17:33:47 -0400 Subject: [PATCH 058/554] URIjs fix .joinPaths() the .joinPaths function is on URIStatic, not an instance of URI https://medialize.github.io/URI.js/docs.html#static-joinPaths --- urijs/URIjs.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/urijs/URIjs.d.ts b/urijs/URIjs.d.ts index 8d784ad1ac..79a65dbb55 100644 --- a/urijs/URIjs.d.ts +++ b/urijs/URIjs.d.ts @@ -52,8 +52,6 @@ declare namespace uri { is(qry: string): boolean; iso8859(): URI; - joinPaths(...paths: (string | URI)[]): URI; - normalize(): URI; normalizeFragment(): URI; normalizeHash(): URI; @@ -190,6 +188,8 @@ declare namespace uri { expand(template: string, vals: Object): URI; iso8859(): void; + + joinPaths(...paths: (string | URI)[]): URI; parse(url: string): { protocol: string; From 4bf0e3eec34fba697afb966879fffe33fd903de1 Mon Sep 17 00:00:00 2001 From: Simon Date: Wed, 28 Sep 2016 18:07:02 -0400 Subject: [PATCH 059/554] set document id property to be optional --- mongoose/mongoose.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 24664cc350..631e9c9581 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -871,7 +871,7 @@ declare module "mongoose" { /** Hash containing current validation errors. */ errors: Object; /** The string version of this documents _id. */ - id: string; + id?: string; /** This documents _id. */ _id: any; /** Boolean flag specifying if the document is new. */ From f58fded0a8cf5deb7fb1b136685c49ec310e9a57 Mon Sep 17 00:00:00 2001 From: Sahin Kureta Date: Thu, 29 Sep 2016 05:17:54 +0300 Subject: [PATCH 060/554] Fixed type of onchallenge --- autobahn/autobahn.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/autobahn/autobahn.d.ts b/autobahn/autobahn.d.ts index bb7a0c86ae..496738875e 100644 --- a/autobahn/autobahn.d.ts +++ b/autobahn/autobahn.d.ts @@ -211,7 +211,7 @@ declare namespace autobahn { retry_delay_jitter?: number; url?: string; protocols?: string[]; - onchallenge?: (session: Session, method: string, extra: any) => OnChallengeHandler; + onchallenge?: OnChallengeHandler; realm?: string; authmethods?: string[]; authid?: string; From 50d20cf6e684b76f26c55eff966735e2db985cd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20Verg=C3=A9?= Date: Wed, 28 Sep 2016 16:46:08 +0200 Subject: [PATCH 061/554] feat(CKEditor): Add missing typings for `focusManager` --- ckeditor/ckeditor-tests.ts | 19 +++++++++++++++++++ ckeditor/ckeditor.d.ts | 13 ++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/ckeditor/ckeditor-tests.ts b/ckeditor/ckeditor-tests.ts index f7deb67069..bcf2a7807b 100644 --- a/ckeditor/ckeditor-tests.ts +++ b/ckeditor/ckeditor-tests.ts @@ -300,3 +300,22 @@ function test_adding_widget() { }); } } + +function test_focusManager() { + var textarea = document.createElement('textarea'); + var instance = CKEDITOR.replace(textarea); + var element = CKEDITOR.document.getById('myElement'); + + instance.focusManager.focus(); + instance.focusManager.focus(element); + instance.focusManager.lock(); + instance.focusManager.unlock(); + instance.focusManager.blur(); + instance.focusManager.blur(true); + instance.focusManager.add(element, true); + instance.focusManager.remove(element); + + var focusManager = new CKEDITOR.focusManager(instance); + var object: CKEDITOR.dom.domObject = focusManager.currentActive; + var bool: boolean = focusManager.hasFocus; +} diff --git a/ckeditor/ckeditor.d.ts b/ckeditor/ckeditor.d.ts index 60b6491407..b5009fa031 100644 --- a/ckeditor/ckeditor.d.ts +++ b/ckeditor/ckeditor.d.ts @@ -544,8 +544,19 @@ declare namespace CKEDITOR { } - interface focusManager { + class focusManager { + // Properties + currentActive: dom.domObject; + hasFocus: boolean; + // Methods + constructor(editor: editor); + focus(currentActive?: dom.element): void; + lock(): void; + unlock(): void; + blur(noDelay?: boolean): void; + add(element: dom.element, isCapture: boolean): void; + remove(element: dom.element): void; } interface keystrokeHandler { From 119234be457b9a7a12cf0e796c909e5bdf0e2e32 Mon Sep 17 00:00:00 2001 From: TANAKA Koichi Date: Thu, 29 Sep 2016 17:05:58 +0900 Subject: [PATCH 062/554] sequelize: fix return value type of Model.findOrXXX methods http://docs.sequelizejs.com/en/latest/api/model/#findorinitialize-promiseinstance-initialized --- sequelize/sequelize-tests.ts | 25 +++++++++++++------------ sequelize/sequelize.d.ts | 6 +++--- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/sequelize/sequelize-tests.ts b/sequelize/sequelize-tests.ts index 5a1dfe4def..80e009f8a2 100644 --- a/sequelize/sequelize-tests.ts +++ b/sequelize/sequelize-tests.ts @@ -962,22 +962,23 @@ User.create( { title : 'Chair', creator : { first_name : 'Matt', last_name : 'Ha User.create( { id : 1, title : 'e', Tags : [{ id : 1, name : 'c' }, { id : 2, name : 'd' }] }, { include : [User] } ); User.create( { id : 'My own ID!' } ).then( ( i ) => i.isNewRecord ); -User.findOrInitialize( { where : { username : 'foo' } } ).then( ( p ) => p ); -User.findOrInitialize( { where : { username : 'foo' }, transaction : t } ); -User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' }, transaction : t } ); +let findOrRetVal: Promise<[AnyInstance, boolean]>; +findOrRetVal = User.findOrInitialize( { where : { username : 'foo' } } ); +findOrRetVal = User.findOrInitialize( { where : { username : 'foo' }, transaction : t } ); +findOrRetVal = User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' }, transaction : t } ); -User.findOrCreate( { where : { a : 'b' }, defaults : { json : { a : { b : 'c' }, d : [1, 2, 3] } } } ); -User.findOrCreate( { where : { a : 'b' }, defaults : { json : 'a', data : 'b' } } ); +findOrRetVal = User.findOrCreate( { where : { a : 'b' }, defaults : { json : { a : { b : 'c' }, d : [1, 2, 3] } } } ); +findOrRetVal = User.findOrCreate( { where : { a : 'b' }, defaults : { json : 'a', data : 'b' } } ); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 User.findOrCreate( { where : { a : 'b' }, transaction : t, lock : t.LOCK.UPDATE } ); */ -User.findOrCreate( { where : { a : 'b' }, logging : function( ) { } } ); -User.findOrCreate( { where : { username : 'Username' }, defaults : { data : 'some data' }, transaction : t } ); -User.findOrCreate( { where : { objectId : 'asdasdasd' }, defaults : { username : 'gottlieb' } } ); -User.findOrCreate( { where : { id : undefined }, defaults : { name : Math.random().toString() } } ); -User.findOrCreate( { where : { email : 'unique.email.@d.com', companyId : Math.floor( Math.random() * 5 ) } } ); -User.findOrCreate( { where : { objectId : 1 }, defaults : { bool : false } } ); -User.findOrCreate( { where : 'c', defaults : {} } ); +findOrRetVal = User.findOrCreate( { where : { a : 'b' }, logging : function( ) { } } ); +findOrRetVal = User.findOrCreate( { where : { username : 'Username' }, defaults : { data : 'some data' }, transaction : t } ); +findOrRetVal = User.findOrCreate( { where : { objectId : 'asdasdasd' }, defaults : { username : 'gottlieb' } } ); +findOrRetVal = User.findOrCreate( { where : { id : undefined }, defaults : { name : Math.random().toString() } } ); +findOrRetVal = User.findOrCreate( { where : { email : 'unique.email.@d.com', companyId : Math.floor( Math.random() * 5 ) } } ); +findOrRetVal = User.findOrCreate( { where : { objectId : 1 }, defaults : { bool : false } } ); +findOrRetVal = User.findOrCreate( { where : 'c', defaults : {} } ); User.upsert( { id : 42, username : 'doe', foo : s.fn( 'upper', 'mixedCase2' ) } ); diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index 76c5f46490..27885d0d66 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -3809,8 +3809,8 @@ declare module "sequelize" { * Find a row that matches the query, or build (but don't save) the row if none is found. * The successfull result of the promise will be (instance, initialized) - Make sure to use .spread() */ - findOrInitialize( options : FindOrInitializeOptions ) : Promise; - findOrBuild( options : FindOrInitializeOptions ) : Promise; + findOrInitialize( options : FindOrInitializeOptions ) : Promise<[TInstance, boolean]>; + findOrBuild( options : FindOrInitializeOptions ) : Promise<[TInstance, boolean]>; /** * Find a row that matches the query, or build and save the row if none is found @@ -3823,7 +3823,7 @@ declare module "sequelize" { * an instance of sequelize.TimeoutError will be thrown instead. If a transaction is created, a savepoint * will be created instead, and any unique constraint violation will be handled internally. */ - findOrCreate( options : FindOrInitializeOptions ) : Promise; + findOrCreate( options : FindOrInitializeOptions ) : Promise<[TInstance, boolean]>; /** * A more performant findOrCreate that will not work under a transaction (at least not in postgres) From 2b7104bab0b653ebd2f247b01d51c9a210e33198 Mon Sep 17 00:00:00 2001 From: Denis Carriere Date: Thu, 29 Sep 2016 07:57:54 -0400 Subject: [PATCH 063/554] Added type Point for simplicity Comments from @vladima --- cheap-ruler/cheap-ruler-tests.ts | 19 ++++---- cheap-ruler/cheap-ruler.d.ts | 80 +++++++++++++++++--------------- 2 files changed, 54 insertions(+), 45 deletions(-) diff --git a/cheap-ruler/cheap-ruler-tests.ts b/cheap-ruler/cheap-ruler-tests.ts index 2a1bf6521d..6e2a2d45e7 100644 --- a/cheap-ruler/cheap-ruler-tests.ts +++ b/cheap-ruler/cheap-ruler-tests.ts @@ -3,6 +3,9 @@ import * as cheapRuler from 'cheap-ruler' // -- Fixtures -- +const bbox = [30.5, 50.5, 31, 51] +const point1 = [30.5, 50.5] +const point2 = [30.51, 50.49] const unit = 'miles' const lineString = { "type": "Feature", @@ -46,15 +49,15 @@ cheapRuler.units.kilometers // -- Test cheapRuler -- const ruler = cheapRuler(35.05) -ruler.distance([30.5, 50.5], [30.51, 50.49]) -ruler.bearing([30.5, 50.5], [30.51, 50.49]) -ruler.destination([30.5, 50.5], 0.1, 90) +ruler.distance(point1, point2) +ruler.bearing(point1, point2) +ruler.destination(point1, 0.1, 90) ruler.lineDistance(points) ruler.area(polygon) ruler.along(line, 2.5) -ruler.pointOnLine(line, [-67.04, 50.5]).point -ruler.lineSlice([-67.04, 50.5], [-67.05, 50.56], line) +ruler.pointOnLine(line, point1).point +ruler.lineSlice(point1, point2, line) ruler.lineSliceAlong(10, 20, line) -ruler.bufferPoint([30.5, 50.5], 0.01) -ruler.bufferBBox([30.5, 50.5, 31, 51], 0.2) -ruler.insideBBox([30.5, 50.5], [30, 50, 31, 51]) \ No newline at end of file +ruler.bufferPoint(point1, 0.01) +ruler.bufferBBox(bbox, 0.2) +ruler.insideBBox(point1, bbox) \ No newline at end of file diff --git a/cheap-ruler/cheap-ruler.d.ts b/cheap-ruler/cheap-ruler.d.ts index 187b27ea82..91f417d490 100644 --- a/cheap-ruler/cheap-ruler.d.ts +++ b/cheap-ruler/cheap-ruler.d.ts @@ -4,6 +4,12 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "cheap-ruler" { + type BBox = [number, number, number, number] | number[] + type Point = [number, number] | number[] + type Line = Array + type Points = Array + type Polygon = Array> + interface TemplateUnits { kilometers: number miles: number @@ -15,7 +21,7 @@ declare module "cheap-ruler" { inches: number } interface InterfacePointOnLine { - point: Array + point: Point index: number t: number } @@ -23,44 +29,44 @@ declare module "cheap-ruler" { /** * Given two points of the form [longitude, latitude], returns the distance. * - * @param {Array} a point [longitude, latitude] - * @param {Array} b point [longitude, latitude] + * @param {Point} a point [longitude, latitude] + * @param {Point} b point [longitude, latitude] * @returns {number} distance * @example * var distance = ruler.distance([30.5, 50.5], [30.51, 50.49]); * //=distance */ - distance(a: Array, b: Array): number; + distance(a: Point, b: Point): number; /** * Returns the bearing between two points in angles. * - * @param {Array} a point [longitude, latitude] - * @param {Array} b point [longitude, latitude] + * @param {Point} a point [longitude, latitude] + * @param {Point} b point [longitude, latitude] * @returns {number} bearing * @example * var bearing = ruler.bearing([30.5, 50.5], [30.51, 50.49]); * //=bearing */ - bearing(a: Array, b: Array): number; + bearing(a: Point, b: Point): number; /** * Returns a new point given distance and bearing from the starting point. * - * @param {Array} p point [longitude, latitude] + * @param {Point} p point [longitude, latitude] * @param {number} dist distance * @param {number} bearing - * @returns {Array} point [longitude, latitude] + * @returns {Point} point [longitude, latitude] * @example * var point = ruler.destination([30.5, 50.5], 0.1, 90); * //=point */ - destination(p: Array, dist: number, bearing: number): Array; + destination(p: Point, dist: number, bearing: number): Point; /** * Given a line (an array of points), returns the total line distance. * - * @param {Array>} points [longitude, latitude] + * @param {Points} points [longitude, latitude] * @returns {number} total line distance * @example * var length = ruler.lineDistance([ @@ -69,12 +75,12 @@ declare module "cheap-ruler" { * ]); * //=length */ - lineDistance(points: Array>): number; + lineDistance(points: Points): number; /** * Given a polygon (an array of rings, where each ring is an array of points), returns the area. * - * @param {Array>>} polygon + * @param {Polygon} polygon * @returns {number} area value in the specified units (square kilometers by default) * @example * var area = ruler.area([[ @@ -83,94 +89,94 @@ declare module "cheap-ruler" { * ]]); * //=area */ - area(polygon: Array>>): number; + area(polygon: Polygon): number; /** * Returns the point at a specified distance along the line. * - * @param {Array>} line + * @param {Line} line * @param {number} dist distance - * @returns {Array} point [longitude, latitude] + * @returns {Point} point [longitude, latitude] * @example * var point = ruler.along(line, 2.5); * //=point */ - along(line: Array>, dist: number): Array + along(line: Line, dist: number): Point /** * Returns an object of the form {point, index} where point is closest point on the line from the given point, and index is the start index of the segment with the closest point. * * @pointOnLine - * @param {Array>} line - * @param {Array} p point [longitude, latitude] + * @param {Line} line + * @param {Point} p point [longitude, latitude] * @returns {Object} {point, index} * @example * var point = ruler.pointOnLine(line, [-67.04, 50.5]).point; * //=point */ - pointOnLine(line: Array>, p: Array): InterfacePointOnLine + pointOnLine(line: Line, p: Point): InterfacePointOnLine /** * Returns a part of the given line between the start and the stop points (or their closest points on the line). * - * @param {Array} start point [longitude, latitude] - * @param {Array} stop point [longitude, latitude] - * @param {Array>} line - * @returns {Array>} line part of a line + * @param {Point} start point [longitude, latitude] + * @param {Point} stop point [longitude, latitude] + * @param {Line} line + * @returns {Line} line part of a line * @example * var line2 = ruler.lineSlice([-67.04, 50.5], [-67.05, 50.56], line1); * //=line2 */ - lineSlice(start: Array, stop: Array, line: Array>): Array> + lineSlice(start: Point, stop: Point, line: Line): Line /** * Returns a part of the given line between the start and the stop points indicated by distance along the line. * * @param {number} start distance * @param {number} stop distance - * @param {Array>} line - * @returns {Array>} line part of a line + * @param {Line} line + * @returns {Line} line part of a line * @example * var line2 = ruler.lineSliceAlong(10, 20, line1); * //=line2 */ - lineSliceAlong(start: number, stop: number, line: Array>): Array> + lineSliceAlong(start: number, stop: number, line: Line): Line /** * Given a point, returns a bounding box object ([w, s, e, n]) created from the given point buffered by a given distance. * - * @param {Array} p point [longitude, latitude] + * @param {Point} p point [longitude, latitude] * @param {number} buffer - * @returns {Array} box object ([w, s, e, n]) + * @returns {BBox} box object ([w, s, e, n]) * @example * var bbox = ruler.bufferPoint([30.5, 50.5], 0.01); * //=bbox */ - bufferPoint(p: Array, buffer: number): Array + bufferPoint(p: Point, buffer: number): BBox /** * Given a bounding box, returns the box buffered by a given distance. * - * @param {Array} box object ([w, s, e, n]) + * @param {BBox} box object ([w, s, e, n]) * @param {number} buffer - * @returns {Array} box object ([w, s, e, n]) + * @returns {BBox} box object ([w, s, e, n]) * @example * var bbox = ruler.bufferBBox([30.5, 50.5, 31, 51], 0.2); * //=bbox */ - bufferBBox(bbox: Array, buffer: number): Array + bufferBBox(bbox: BBox, buffer: number): BBox /** * Returns true if the given point is inside in the given bounding box, otherwise false. * - * @param {Array} p point [longitude, latitude] - * @param {Array} box object ([w, s, e, n]) + * @param {Point} p point [longitude, latitude] + * @param {Point} box object ([w, s, e, n]) * @returns {boolean} * @example * var inside = ruler.insideBBox([30.5, 50.5], [30, 50, 31, 51]); * //=inside */ - insideBBox(p: Array, bbox: Array): boolean + insideBBox(p: Point, bbox: BBox): boolean } /** * A collection of very fast approximations to common geodesic measurements. Useful for performance-sensitive code that measures things on a city scale. From 93a4381634e2d4d50e925b5218f63455ce4d9022 Mon Sep 17 00:00:00 2001 From: gatsbimantico Date: Thu, 29 Sep 2016 14:09:42 +0200 Subject: [PATCH 064/554] added gapi.analytics-tests and a few corrections --- gapi.analytics/gapi.analytics-tests.ts | 67 ++++++++++++++++++++++++++ gapi.analytics/gapi.analytics.d.ts | 40 +++++++-------- 2 files changed, 87 insertions(+), 20 deletions(-) create mode 100644 gapi.analytics/gapi.analytics-tests.ts diff --git a/gapi.analytics/gapi.analytics-tests.ts b/gapi.analytics/gapi.analytics-tests.ts new file mode 100644 index 0000000000..711fffeca9 --- /dev/null +++ b/gapi.analytics/gapi.analytics-tests.ts @@ -0,0 +1,67 @@ +// Type definitions for Google Analytics API + +/// +/// +/// + +function test_namespace() { + var analytics : boolean = gapi.client.analytics instanceof Object; + + var provisioning : boolean = gapi.client.analytics.provisioning.createAccountTicket instanceof Function; + analytics = analytics && provisioning; + + var data : boolean = gapi.client.analytics.data.ga.get instanceof Function; + data = data && gapi.client.analytics.data.mcf.get instanceof Function; + data = data && gapi.client.analytics.data.realtime.get instanceof Function; + analytics = analytics && data; + + interface AnalyticsParameter { + "type" ?: string; + "description" ?: string; + "default" ?: string; + "enum" ?: string[]; + "enumDescriptions" ?: string[]; + "location" ?: string; + } + var kBI : AnalyticsParameter = gapi.client.analytics.kB.parameters.alt; + var kB = !!kBI; + kBI = gapi.client.analytics.kB.parameters.fields; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.key; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.oauth_token; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.prettyPrint; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.quotaUser; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.userIP; + kB = kB && !!kBI; + analytics = analytics && kB; + + var management : boolean = gapi.client.analytics.management.accountSummaries.list instanceof Function; + management = management && gapi.client.analytics.management.accountUserLinks.list instanceof Function; + management = management && gapi.client.analytics.management.accounts.list instanceof Function; + management = management && gapi.client.analytics.management.customDataSources.list instanceof Function; + management = management && gapi.client.analytics.management.customDimensions.list instanceof Function; + management = management && gapi.client.analytics.management.customMetrics.list instanceof Function; + management = management && gapi.client.analytics.management.experiments.list instanceof Function; + management = management && gapi.client.analytics.management.filters.list instanceof Function; + management = management && gapi.client.analytics.management.goals.list instanceof Function; + management = management && gapi.client.analytics.management.profileFilterLinks.list instanceof Function; + management = management && gapi.client.analytics.management.profileUserLinks.list instanceof Function; + management = management && gapi.client.analytics.management.profiles.list instanceof Function; + management = management && gapi.client.analytics.management.remarketingAudience.list instanceof Function; + management = management && gapi.client.analytics.management.segments.list instanceof Function; + management = management && gapi.client.analytics.management.unsampledReports.list instanceof Function; + management = management && gapi.client.analytics.management.uploads.list instanceof Function; + management = management && gapi.client.analytics.management.webPropertyAdWordsLinks.list instanceof Function; + management = management && gapi.client.analytics.management.webproperties.list instanceof Function; + management = management && gapi.client.analytics.management.webpropertyUserLinks.list instanceof Function; + analytics = analytics && management; + + var metadata : boolean = gapi.client.analytics.metadata.column.list instanceof Function; + analytics = analytics && metadata; + + return analytics; +} diff --git a/gapi.analytics/gapi.analytics.d.ts b/gapi.analytics/gapi.analytics.d.ts index 36cca1263c..f89e015de8 100644 --- a/gapi.analytics/gapi.analytics.d.ts +++ b/gapi.analytics/gapi.analytics.d.ts @@ -1,5 +1,6 @@ // Type definitions for Google Analytics API +/// /// declare namespace gapi.client.analytics {} @@ -34,24 +35,23 @@ declare namespace gapi.client.analytics.data.realtime { export function get(data ?: DataQuery) : Promise; } -interface AnalyticsParameter { - "type" ?: string; - "description" ?: string; - "default" ?: string; - "enum" ?: string[]; - "enumDescriptions" ?: string[]; - "location" ?: string; -} -declare namespace gapi.client.analytics.kB { - export class parameters { - alt: AnalyticsParameter; - fields: AnalyticsParameter; - key: AnalyticsParameter; - oauth_token: AnalyticsParameter; - prettyPrint: AnalyticsParameter; - quotaUser: AnalyticsParameter; - userIP: AnalyticsParameter; - } +declare namespace gapi.client.analytics.kB {} +declare namespace gapi.client.analytics.kB.parameters { + export interface AnalyticsParameter { + "type" ?: string; + "description" ?: string; + "default" ?: string; + "enum" ?: string[]; + "enumDescriptions" ?: string[]; + "location" ?: string; + } + export class alt implements AnalyticsParameter {} + export class fields implements AnalyticsParameter {} + export class key implements AnalyticsParameter {} + export class oauth_token implements AnalyticsParameter {} + export class prettyPrint implements AnalyticsParameter {} + export class quotaUser implements AnalyticsParameter {} + export class userIP implements AnalyticsParameter {} } interface View { @@ -60,10 +60,10 @@ interface View { webViewId ?: string; } declare namespace gapi.client.analytics.management {} -declare namespace gapi.client.analytics.managementaccountSummaries { +declare namespace gapi.client.analytics.management.accountSummaries { export function list(view ?: View) : Promise; } -declare namespace gapi.client.analytics.managementaccountUserLinks { +declare namespace gapi.client.analytics.management.accountUserLinks { export function list(view ?: View) : Promise; } declare namespace gapi.client.analytics.management.accounts { From 00272360284225ccf9fae6b2b32846114862c1c4 Mon Sep 17 00:00:00 2001 From: gatsbimantico Date: Thu, 29 Sep 2016 14:12:24 +0200 Subject: [PATCH 065/554] Tested with --target es6 --- gapi.analytics/gapi.analytics-tests.ts | 1 - gapi.analytics/gapi.analytics.d.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/gapi.analytics/gapi.analytics-tests.ts b/gapi.analytics/gapi.analytics-tests.ts index 711fffeca9..a6aea00796 100644 --- a/gapi.analytics/gapi.analytics-tests.ts +++ b/gapi.analytics/gapi.analytics-tests.ts @@ -1,6 +1,5 @@ // Type definitions for Google Analytics API -/// /// /// diff --git a/gapi.analytics/gapi.analytics.d.ts b/gapi.analytics/gapi.analytics.d.ts index f89e015de8..da9b81cb68 100644 --- a/gapi.analytics/gapi.analytics.d.ts +++ b/gapi.analytics/gapi.analytics.d.ts @@ -1,6 +1,5 @@ // Type definitions for Google Analytics API -/// /// declare namespace gapi.client.analytics {} From f3c98e74a04b199ca4c6acc6ceeec5691dc2cb70 Mon Sep 17 00:00:00 2001 From: Simon Date: Thu, 29 Sep 2016 08:59:12 -0400 Subject: [PATCH 066/554] add interface for mongoose document optional properties --- mongoose/mongoose.d.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 631e9c9581..9e5600e696 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -715,7 +715,7 @@ declare module "mongoose" { * section document.js * http://mongoosejs.com/docs/api.html#document-js */ - class MongooseDocument { + class MongooseDocument implements MongooseDocumentOptionals { /** Checks if a path is set to its default. */ $isDefault(path?: string): boolean; @@ -870,8 +870,6 @@ declare module "mongoose" { /** Hash containing current validation errors. */ errors: Object; - /** The string version of this documents _id. */ - id?: string; /** This documents _id. */ _id: any; /** Boolean flag specifying if the document is new. */ @@ -880,6 +878,11 @@ declare module "mongoose" { schema: Schema; } + interface MongooseDocumentOptionals { + /** The string version of this documents _id. */ + id?: string; + } + interface DocumentToObjectOptions { /** apply all getters (path and virtual getters) */ getters?: boolean; From d7fb4e38081924e1a92acdb1fa6f196581467da5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20S=C3=A4nger?= Date: Thu, 29 Sep 2016 15:23:23 +0200 Subject: [PATCH 067/554] use correct richselect.getList() return type --- webix/webix.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/webix/webix.d.ts b/webix/webix.d.ts index 7931ef83d9..1936102a6d 100644 --- a/webix/webix.d.ts +++ b/webix/webix.d.ts @@ -5941,7 +5941,10 @@ interface richselect extends webix.ui.baseview{ getChildViews():any[]; getFormView():webix.ui.baseview; getInputNode():HTMLElement; - getList():webix.ui.baseview; + /** + * returns list view of the control + */ + getList():webix.ui.list; getNode():any; getParentView():any; getPopup():webix.ui.baseview; From 2f74c100a1b567675c9cb374fc7039d5a5ce8f13 Mon Sep 17 00:00:00 2001 From: George Edwards Date: Thu, 29 Sep 2016 16:17:37 +0100 Subject: [PATCH 068/554] optional constructor for RecurrenceRule --- node-schedule/node-schedule.d.ts | 56 ++++++++++++++++---------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/node-schedule/node-schedule.d.ts b/node-schedule/node-schedule.d.ts index 5127eafb40..1b15f9c34c 100644 --- a/node-schedule/node-schedule.d.ts +++ b/node-schedule/node-schedule.d.ts @@ -13,7 +13,7 @@ declare module 'node-schedule' { * The callback executed by a Job */ export interface JobCallback { - ():void; + (): void; } /** @@ -25,7 +25,7 @@ declare module 'node-schedule' { /** * This Job's name. read-only. */ - name:string; + name: string; /** * Use the function scheduleJob() to create new Job objects. @@ -36,7 +36,7 @@ declare module 'node-schedule' { * @param {JobCallback|Function} job either this Job's callback or an optional callback function * @param {Function} callback optional callback that is executed right before the JobCallback */ - constructor(name: string|JobCallback, job?: JobCallback|Function, callback?: Function); + constructor(name: string | JobCallback, job?: JobCallback | Function, callback?: Function); /** * Adds an Invocation to this job. For internal use. @@ -44,7 +44,7 @@ declare module 'node-schedule' { * @param {Invocation} invokation * @return {boolean} whether the invocation could be added */ - trackInvocation(invokation:Invocation):boolean; + trackInvocation(invokation: Invocation): boolean; /** * removes an Invocation from this Job's tracking list. For internal use. @@ -52,69 +52,69 @@ declare module 'node-schedule' { * @param invocation {Invocation} * @return boolean whether the invocation was successful. Removing an Invocation that doesn't exist, returns false. */ - stopTrackingInvocation(invocation:Invocation):boolean; + stopTrackingInvocation(invocation: Invocation): boolean; /** * @internal * @return {number} the number of currently running instances of this Job. */ - triggeredJobs():number; + triggeredJobs(): number; /** * set the number of currently running Jobs. * @internal * @param triggeredJobs */ - setTriggeredJobs(triggeredJobs:number):void; + setTriggeredJobs(triggeredJobs: number): void; /** * cancel all pending Invocations of this Job. * @param reschedule {boolean} whether to reschedule the canceled Invocations. */ - cancel(reschedule?:boolean):boolean; + cancel(reschedule?: boolean): boolean; /** * cancel the next Invocation of this Job. * @param reschedule {boolean} whether to reschedule the canceled Invocation. * @return {boolean} whether cancelation was successful */ - cancelNext(reschedule?:boolean):boolean; + cancelNext(reschedule?: boolean): boolean; /** * Changes the scheduling information for this Job. * @param spec {RecurrenceRule|string|number} the * @return {boolean} whether the reschedule was successful */ - reschedule(spec:RecurrenceRule|string|number):boolean; + reschedule(spec: RecurrenceRule | string | number): boolean; /** * Returns the Date on which this Job will be run next. * @return {Date} */ - nextInvocation():Date; + nextInvocation(): Date; /** * @return Invocation[] a list of all pending Invocations */ - pendingInvocations():Invocation[]; + pendingInvocations(): Invocation[]; /** * run this Job immediately. */ - invoke():void; + invoke(): void; /** * schedule this Job to be run on the specified date. * @param date {Date} */ - runOnDate(date:Date): void; + runOnDate(date: Date): void; /** * set scheduling information * @param {Date|string|number} date * @public */ - schedule(date: Date|string|number): boolean; + schedule(date: Date | string | number): boolean; } /** @@ -160,7 +160,7 @@ declare module 'node-schedule' { * @public * @type {number|Array} */ - dayOfWeek: number|Array; + dayOfWeek: number | Array; /** * Hour. @@ -202,15 +202,15 @@ declare module 'node-schedule' { */ year: number; - constructor(year:number, - month:number, - date:number, - dayOfWeek:number|Array, - hour:number, - minute:number, - second:number); + constructor(year?: number, + month?: number, + date?: number, + dayOfWeek?: number | Array, + hour?: number, + minute?: number, + second?: number); - nextInvocationDate(base:Date):Date; + nextInvocationDate(base: Date): Date; } /** @@ -269,7 +269,7 @@ declare module 'node-schedule' { * @param {RecurrenceRule|Date|string} rule either the scheduling info or the JobCallback * @param {JobCallback} callback The callback to be executed on each invocation. */ - export function scheduleJob(name:string|RecurrenceRule|Date, rule: RecurrenceRule|Date|string|JobCallback, callback?: JobCallback): Job; + export function scheduleJob(name: string | RecurrenceRule | Date, rule: RecurrenceRule | Date | string | JobCallback, callback?: JobCallback): Job; /** * Changes the timing of a Job, canceling all pending invocations. @@ -278,12 +278,12 @@ declare module 'node-schedule' { * @param spec {JobCallback} the new timing for this Job * @return {Job} if the job could be rescheduled, {null} otherwise. */ - export function rescheduleJob(job:Job|string, spec:RecurrenceRule|Date|string):Job; + export function rescheduleJob(job: Job | string, spec: RecurrenceRule | Date | string): Job; /** * Dictionary of all Jobs, accessible by name. */ - export let scheduledJobs:{[jobName:string]:Job}; + export let scheduledJobs: { [jobName: string]: Job }; /** * Cancels the job. @@ -291,5 +291,5 @@ declare module 'node-schedule' { * @param {Job} job The job. * @returns {boolean} {true} if the job has been cancelled with success, otherwise, {false}. */ - export function cancelJob(job: Job|string): boolean; + export function cancelJob(job: Job | string): boolean; } From dee341230c59586a132f045eee7eefbdd88ca542 Mon Sep 17 00:00:00 2001 From: unHealthy Date: Thu, 29 Sep 2016 23:14:43 +0800 Subject: [PATCH 069/554] fix the framework type --- passport/passport-tests.ts | 55 +++++++++++++++++++++++++------------- passport/passport.d.ts | 12 ++++++--- 2 files changed, 45 insertions(+), 22 deletions(-) diff --git a/passport/passport-tests.ts b/passport/passport-tests.ts index 423d925b4c..8b02c96c76 100644 --- a/passport/passport-tests.ts +++ b/passport/passport-tests.ts @@ -7,19 +7,34 @@ import passport = require('passport'); class TestStrategy implements passport.Strategy { public name: string = 'test'; - constructor() {} - authenticate(req: express.Request) {} + constructor() { } + authenticate(req: express.Request) { } } +const newFramework:passport.Framework = { + initialize: function () { + return function () { }; + }, + authenticate: function (passport, name, options) { + return function () { + return 'authenticate(): ' + name + ' ' + options; + }; + }, + authorize: function (passport, name, options) { + return function () { + return 'authorize(): ' + name + ' ' + options; + } + } +}; passport.use(new TestStrategy()); -passport.framework('test'); -passport.serializeUser((user, done) => {}); -passport.deserializeUser((id, done) => {}); +passport.framework(newFramework); +passport.serializeUser((user, done) => { }); +passport.deserializeUser((id, done) => { }); passport.use(new TestStrategy()) .unuse('test') .use(new TestStrategy()) - .framework('test-fw'); + .framework(newFramework); var app = express(); @@ -28,27 +43,27 @@ app.configure(() => { app.use(passport.session()); }); -app.post('/login', +app.post('/login', passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }), - function(req, res) { + function (req, res) { res.redirect('/'); }); -app.post('/login', function(req, res, next) { - passport.authenticate('local', function(err: any, user: { username: string; }, info: { message: string; }) { +app.post('/login', function (req, res, next) { + passport.authenticate('local', function (err: any, user: { username: string; }, info: { message: string; }) { if (err) { return next(err) } if (!user) { req.session['error'] = info.message; return res.redirect('/login') } - req.logIn(user, function(err) { + req.logIn(user, function (err) { if (err) { return next(err); } return res.redirect('/users/' + user.username); }); })(req, res, next); }); -app.get('/logout', function(req, res) { +app.get('/logout', function (req, res) { req.logout(); res.redirect('/'); }); @@ -66,20 +81,22 @@ function authSetting(): void { }; app.get('/auth/facebook', - passport.authenticate('facebook')); + passport.authenticate('facebook')); app.get('/auth/facebook/callback', - passport.authenticate('facebook', authOption), successCallback); + passport.authenticate('facebook', authOption), successCallback); app.get('/auth/twitter', - passport.authenticate('twitter')); + passport.authenticate('twitter')); app.get('/auth/twitter/callback', - passport.authenticate('twitter', authOption)); + passport.authenticate('twitter', authOption)); app.get('/auth/google', - passport.authenticate('google', { scope: - [ 'https://www.googleapis.com/auth/userinfo.profile' ] })); + passport.authenticate('google', { + scope: + ['https://www.googleapis.com/auth/userinfo.profile'] + })); app.get('/auth/google/callback', - passport.authenticate('google', authOption), successCallback); + passport.authenticate('google', authOption), successCallback); } diff --git a/passport/passport.d.ts b/passport/passport.d.ts index 470c0dc79c..3723176970 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -30,7 +30,7 @@ declare module 'passport' { function use(strategy: Strategy): Passport; function use(name: string, strategy: Strategy): Passport; function unuse(name: string): Passport; - function framework(fw: string): Passport; + function framework(fw: Framework): Passport; function initialize(options?: { userProperty: string; }): express.Handler; function session(options?: { pauseStream: boolean; }): express.Handler; @@ -50,7 +50,7 @@ declare module 'passport' { use(strategy: Strategy): Passport; use(name: string, strategy: Strategy): Passport; unuse(name: string): Passport; - framework(fw: string): Passport; + framework(fw: Framework): Passport; initialize(options?: { userProperty: string; }): express.Handler; session(options?: { pauseStream: boolean; }): express.Handler; @@ -76,7 +76,7 @@ declare module 'passport' { provider: string; id: string; displayName: string; - name? : { + name?: { familyName: string; givenName: string; middleName?: string; @@ -89,4 +89,10 @@ declare module 'passport' { value: string; }[]; } + + interface Framework { + initialize(): Function; + authenticate(passport: Passport, name: string, options?: Object):Function; + authorize(passport: Passport, name: string, options?: Object):Function; + } } From 6a78378d1722551c35ba0584261963b572b288cd Mon Sep 17 00:00:00 2001 From: unHealthy Date: Thu, 29 Sep 2016 23:47:32 +0800 Subject: [PATCH 070/554] add parameter support in initialize() --- passport/passport.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/passport/passport.d.ts b/passport/passport.d.ts index 3723176970..6c3e755974 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -91,8 +91,8 @@ declare module 'passport' { } interface Framework { - initialize(): Function; - authenticate(passport: Passport, name: string, options?: Object):Function; - authorize(passport: Passport, name: string, options?: Object):Function; + initialize(passport: Passport, options?: Object): Function; + authenticate(passport: Passport, name: string, options?: Object): Function; + authorize(passport: Passport, name: string, options?: Object): Function; } } From 30e0200d506cd785c971680d80bc8eb11b296b49 Mon Sep 17 00:00:00 2001 From: unHealthy Date: Thu, 29 Sep 2016 23:50:04 +0800 Subject: [PATCH 071/554] add callback parameter --- passport/passport.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/passport/passport.d.ts b/passport/passport.d.ts index 6c3e755974..536cb27d3b 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -92,7 +92,7 @@ declare module 'passport' { interface Framework { initialize(passport: Passport, options?: Object): Function; - authenticate(passport: Passport, name: string, options?: Object): Function; - authorize(passport: Passport, name: string, options?: Object): Function; + authenticate(passport: Passport, name: string, options?: Object, callback?: Function): Function; + authorize(passport: Passport, name: string, options?: Object, callback?: Function): Function; } } From c8a69b0b0c71cc00d4ada94a4420fb037b3cc9cd Mon Sep 17 00:00:00 2001 From: dan-def Date: Thu, 29 Sep 2016 17:29:22 +0100 Subject: [PATCH 072/554] Added promise() to the JQueryPromise interface jQuery allows calling a promise() function on a Promise object. Updated the interface to reflect this. --- jquery/jquery.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index b08598cc53..f8af62caba 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -344,6 +344,13 @@ interface JQueryPromise extends JQueryGenericPromise { // Deprecated - given no typings pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; + + /** + * Return a Deferred's Promise object. + * + * @param target Object onto which the promise methods have to be attached + */ + promise(target?: any): JQueryPromise; } /** From 819954b127f4aa5abfad43965270858a0ec5ea93 Mon Sep 17 00:00:00 2001 From: unHealthy Date: Fri, 30 Sep 2016 02:10:29 +0800 Subject: [PATCH 073/554] optional authorize --- passport/passport.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/passport/passport.d.ts b/passport/passport.d.ts index 536cb27d3b..088156b2d3 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -93,6 +93,6 @@ declare module 'passport' { interface Framework { initialize(passport: Passport, options?: Object): Function; authenticate(passport: Passport, name: string, options?: Object, callback?: Function): Function; - authorize(passport: Passport, name: string, options?: Object, callback?: Function): Function; + authorize?(passport: Passport, name: string, options?: Object, callback?: Function): Function; } } From 71ae898a05164dc2a583ab75541ee67bee697b1d Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Thu, 29 Sep 2016 22:56:24 +0300 Subject: [PATCH 074/554] add contains fn --- ip/ip.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ip/ip.d.ts b/ip/ip.d.ts index 0542ae0785..1c00f1320e 100644 --- a/ip/ip.d.ts +++ b/ip/ip.d.ts @@ -14,6 +14,7 @@ interface SubnetInfo { subnetMaskLength: number; numHosts: number; length: number; + contains(ip: string): boolean; } declare module "ip" { @@ -112,4 +113,4 @@ declare module "ip" { * @param cidr CIDR address. */ export function cidrSubnet(cidr: string): SubnetInfo; -} \ No newline at end of file +} From 43d17ebbfe625e339cdf4b30dcca5dc2cef51292 Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Thu, 29 Sep 2016 22:57:17 +0300 Subject: [PATCH 075/554] Update ip-tests.ts --- ip/ip-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/ip/ip-tests.ts b/ip/ip-tests.ts index 338c2bc040..3210871ee0 100644 --- a/ip/ip-tests.ts +++ b/ip/ip-tests.ts @@ -19,3 +19,4 @@ var buff:any = ip.toBuffer(myIP); ip.toString(buff); ip.subnet('192.168.1.134', '255.255.255.192'); ip.cidrSubnet('192.168.1.134/26'); +ip.cidrSubnet('192.168.1.134/26').contains('192.168.1.134'); From c4e9d77c1899652d9ed320f35ccd85bd7b6f5e29 Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Thu, 29 Sep 2016 23:48:42 +0300 Subject: [PATCH 076/554] add id --- express-session/express-session.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/express-session/express-session.d.ts b/express-session/express-session.d.ts index 90e1ed07cc..0320ff1aed 100644 --- a/express-session/express-session.d.ts +++ b/express-session/express-session.d.ts @@ -10,11 +10,14 @@ declare namespace Express { export interface Request { session?: Session; + readonly sessionId: string; } export interface Session { [key: string]: any; + readonly id: string; + regenerate: (callback: (err: any) => void) => void; destroy: (callback: (err: any) => void) => void; reload: (callback: (err: any) => void) => void; From 9c8c07801e8c65631d9dc563d3ef1604ac009d4d Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Fri, 30 Sep 2016 00:00:15 +0300 Subject: [PATCH 077/554] remove readonly --- express-session/express-session.d.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/express-session/express-session.d.ts b/express-session/express-session.d.ts index 0320ff1aed..c685c8a1bb 100644 --- a/express-session/express-session.d.ts +++ b/express-session/express-session.d.ts @@ -10,13 +10,12 @@ declare namespace Express { export interface Request { session?: Session; - readonly sessionId: string; + sessionId?: string; } export interface Session { [key: string]: any; - - readonly id: string; + id: string; regenerate: (callback: (err: any) => void) => void; destroy: (callback: (err: any) => void) => void; From 5a0b946a42315f58b3f5fdd3de6dc70e9f24cfea Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Fri, 30 Sep 2016 01:16:45 +0300 Subject: [PATCH 078/554] add touch after --- connect-mongo/connect-mongo.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/connect-mongo/connect-mongo.d.ts b/connect-mongo/connect-mongo.d.ts index 49f93e2d46..7c779e2d07 100644 --- a/connect-mongo/connect-mongo.d.ts +++ b/connect-mongo/connect-mongo.d.ts @@ -78,6 +78,12 @@ declare module "connect-mongo" { * (Default: 10) */ autoRemoveInterval?: number; + + + /** + * don't save session if unmodified + */ + touchAfter?: number; } export interface MongoUrlOptions extends DefaultOptions { From 30b38b4e5a16967e9f4c07b4be5da58c04213700 Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Fri, 30 Sep 2016 06:49:17 +0300 Subject: [PATCH 079/554] fix typo --- express-session/express-session.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/express-session/express-session.d.ts b/express-session/express-session.d.ts index c685c8a1bb..9af409ddc5 100644 --- a/express-session/express-session.d.ts +++ b/express-session/express-session.d.ts @@ -10,7 +10,7 @@ declare namespace Express { export interface Request { session?: Session; - sessionId?: string; + sessionID?: string; } export interface Session { From 4f1c124243f852aa86942f82bac8b723f47c38d5 Mon Sep 17 00:00:00 2001 From: Alex Kankov Date: Fri, 30 Sep 2016 14:26:12 +0700 Subject: [PATCH 080/554] Object with themes --- amcharts/AmCharts.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/amcharts/AmCharts.d.ts b/amcharts/AmCharts.d.ts index 4f5dbe90f7..ae5baad50e 100644 --- a/amcharts/AmCharts.d.ts +++ b/amcharts/AmCharts.d.ts @@ -23,6 +23,9 @@ declare namespace AmCharts { /** Set it to true if you want UTC time to be used instead of local time. */ var useUTC: boolean; + + /** Object with themes */ + var themes: any; /** Clears all the charts on page, removes listeners and intervals. */ function clear(); From 10940d2b423df0e8f5d32402dddea000fb492a1c Mon Sep 17 00:00:00 2001 From: dan-def Date: Fri, 30 Sep 2016 08:49:00 +0100 Subject: [PATCH 081/554] Added tests for the promise() method on jqXHR Ensures that the jqXHR object exposes a standard promise because it implements the JQueryPromise interface. --- jquery/jquery-tests.ts | 44 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index d031535184..c5ee51df15 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -209,6 +209,50 @@ function test_ajax() { url: "test.js" }); jqXHR.abort('aborting because I can'); + + //Test the promise exposed by the jqXHR object + + // done method + $.ajax({ + url: "test.js" + }).promise().done((data, textStatus, jqXHR) => { + console.log(data, textStatus, jqXHR); + }); + + // fail method + $.ajax({ + url: "test.js" + }).promise().fail((jqXHR, textStatus, errorThrown) => { + console.log(jqXHR, textStatus, errorThrown); + }); + + // always method with successful request + $.ajax({ + url: "test.js" + }).promise().always((data, textStatus, jqXHR) => { + console.log(data, textStatus, jqXHR); + }); + + // always method with failed request + $.ajax({ + url: "test.js" + }).promise().always((jqXHR, textStatus, errorThrown) => { + console.log(jqXHR, textStatus, errorThrown); + }); + + // then method (as of 1.8) + $.ajax({ + url: "test.js" + }).promise().then((data, textStatus, jqXHR) => { + console.log(data, textStatus, jqXHR); + }, (jqXHR, textStatus, errorThrown) => { + console.log(jqXHR, textStatus, errorThrown); + }); + + // generic then method + var p: JQueryPromise = $.ajax({ url: "test.js" }).promise() + .then(() => "Hello") + .then((x) => x.length); } function test_ajaxComplete() { From 62566b86d7e7f23ab88cd3ec8ede5448c57b94c0 Mon Sep 17 00:00:00 2001 From: JulienBourgain Date: Fri, 30 Sep 2016 14:05:41 +0200 Subject: [PATCH 082/554] angular-dynamic-local Add "storageKey" definition (#11566) Add "storageKey" definition cf : https://github.com/lgalfaso/angular-dynamic-locale/blob/master/src/tmhDynamicLocale.js#L197 --- angular-dynamic-locale/angular-dynamic-locale.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angular-dynamic-locale/angular-dynamic-locale.d.ts b/angular-dynamic-locale/angular-dynamic-locale.d.ts index 4b7a1f9656..210a50f4aa 100644 --- a/angular-dynamic-locale/angular-dynamic-locale.d.ts +++ b/angular-dynamic-locale/angular-dynamic-locale.d.ts @@ -20,6 +20,7 @@ declare namespace angular.dynamicLocale { interface tmhDynamicLocaleProvider extends angular.IServiceProvider { localeLocationPattern(location: string): tmhDynamicLocaleProvider; localeLocationPattern(): string; + storageKey(storageKey: string): void; useStorage(storageName: string): void; useCookieStorage(): void; } From 67205ae0907a7bd1e9e11259c6c18abb0d71e8b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niko=20Kova=C4=8Di=C4=8D?= Date: Fri, 30 Sep 2016 14:05:53 +0200 Subject: [PATCH 083/554] Added declare module for easier including. (#11562) --- angular-signalr-hub/angular-signalr-hub-tests.ts | 2 +- angular-signalr-hub/angular-signalr-hub.d.ts | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/angular-signalr-hub/angular-signalr-hub-tests.ts b/angular-signalr-hub/angular-signalr-hub-tests.ts index d20457bcdc..1e7c90c962 100644 --- a/angular-signalr-hub/angular-signalr-hub-tests.ts +++ b/angular-signalr-hub/angular-signalr-hub-tests.ts @@ -1,5 +1,5 @@ -/// /// +/// angular .module('app', ['SignalR']) diff --git a/angular-signalr-hub/angular-signalr-hub.d.ts b/angular-signalr-hub/angular-signalr-hub.d.ts index 03fa6427eb..8d331ffd75 100644 --- a/angular-signalr-hub/angular-signalr-hub.d.ts +++ b/angular-signalr-hub/angular-signalr-hub.d.ts @@ -3,8 +3,14 @@ // Definitions by: Adam Santaniello // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// /// +declare module "angular-signalr-hub" { + let _: string; + export = _; +} + declare namespace ngSignalr { interface HubFactory { /** From 96e0dfcf7c1d7328eb9c3c1a210358fd2c6086f9 Mon Sep 17 00:00:00 2001 From: iskandersierra Date: Fri, 30 Sep 2016 14:07:58 +0200 Subject: [PATCH 084/554] Adding recompose@0.20.2 typings (#11577) * Added typings for change-emitter@0.1.2 * Adding recompose@0.20.2 typings --- recompose/recompose-tests.tsx | 171 +++++++++++++++++ recompose/recompose.d.ts | 334 ++++++++++++++++++++++++++++++++++ 2 files changed, 505 insertions(+) create mode 100644 recompose/recompose-tests.tsx create mode 100644 recompose/recompose.d.ts diff --git a/recompose/recompose-tests.tsx b/recompose/recompose-tests.tsx new file mode 100644 index 0000000000..714ce83d66 --- /dev/null +++ b/recompose/recompose-tests.tsx @@ -0,0 +1,171 @@ +/// + +import * as React from "react"; +import { + Component, + // Higher-order components + mapProps, withProps, withPropsOnChange, withHandlers, + defaultProps, renameProp, renameProps, flattenProp, + withState, withReducer, branch, renderComponent, + renderNothing, shouldUpdate, pure, onlyUpdateForKeys, + onlyUpdateForPropTypes, withContext, getContext, + lifecycle, toClass, + // Static property helpers + setStatic, setPropTypes, setDisplayName, + // Utilities + compose, getDisplayName, wrapDisplayName, shallowEqual, + isClassComponent, createEagerElement, createEagerFactory, + createSink, componentFromProp, nest, hoistStatics, + // Observable utilities + componentFromStream, mapPropsStream, createEventHandler, + setObservableConfig, +} from "recompose"; +import rxjsconfig from "recompose/rxjsObservableConfig"; +import rxjs4config from "recompose/rxjs4ObservableConfig"; +import mostConfig from "recompose/mostObservableConfig"; +import xstreamConfig from "recompose/xstreamObservableConfig"; +import baconConfig from "recompose/baconObservableConfig"; +import kefirConfig from "recompose/kefirObservableConfig"; + +function testMapProps() { + interface InnerProps { inn: number } + interface OutterProps { out: string } + const innerComponent = ({inn}: InnerProps) =>
{inn}
; + + const enhancer = mapProps((props: OutterProps) => ({ inn: 123 } as InnerProps)); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + +function testWithProps() { + interface InnerProps { inn: number } + interface OutterProps { out: string } + const innerComponent = ({inn}: InnerProps) =>
{inn}
; + + const enhancer = withProps((props: OutterProps) => ({ inn: 123 } as InnerProps)); + const enhanced: React.ComponentClass = enhancer(innerComponent); + + const enhancer2 = withProps({ inn: 123 } as InnerProps); + const enhanced2: React.ComponentClass = enhancer2(innerComponent); +} + +function testWithPropsOnChange() { + interface InnerProps { inn: number } + interface OutterProps { out: string } + const innerComponent = ({inn}: InnerProps) =>
{inn}
; + + const enhancer = withPropsOnChange( + (props: OutterProps, nextProps: OutterProps) => true, + (props: OutterProps) => ({ inn: 123 } as InnerProps)); + const enhanced: React.ComponentClass = enhancer(innerComponent); + + const enhancer2 = withPropsOnChange( + [ "out" ], + (props: OutterProps) => ({ inn: 123 } as InnerProps)); + const enhanced2: React.ComponentClass = enhancer2(innerComponent); +} + +function testWithHandlers() { + interface InnerProps { onSubmit: Function; onChange: Function; } + interface OutterProps { out: string } + const innerComponent = ({onChange, onSubmit}: InnerProps) => +
; + + const enhancer = withHandlers({ + onChange: (props: OutterProps) => (e: any) => {}, + onSubmit: (props: OutterProps) => (e: any) => {}, + }); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + +function testDefaultProps() { + interface Props { a?: string; b?: number; } + const innerComponent = ({a, b}: Props) =>
{a}, {b}
; + + const enhancer = defaultProps({ a: "answer", b: 42 }); + const enhanced: React.StatelessComponent = enhancer(innerComponent); +} + +function testRenameProp() { + interface InnerProps { c: string; b: number; } + interface OutterProps { a: string; b: number; } + const innerComponent: React.StatelessComponent = ({c, b}: InnerProps) =>
{c}, {b}
; + + const enhancer = renameProp("a", "c"); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + +function testRenameProps() { + interface InnerProps { c: string; d: number; } + interface OutterProps { a: string; b: number; } + const innerComponent: React.StatelessComponent = ({c, d}: InnerProps) =>
{c}, {d}
; + + const enhancer = renameProps({ a:"c", b: "d" }); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + +function testFlattenProp() { + interface InnerProps { a: string; b: string; y: {c: string; d: number;} } + interface OutterProps { x: {a: string; b: number;}; y: {c: string; d: number;} } + const innerComponent: React.StatelessComponent = (props: InnerProps) =>
; + + const enhancer = flattenProp("x"); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + +function testWithState() { + interface InnerProps { count: number; setCount: (count: number) => void } + interface OutterProps { title: string } + const innerComponent: React.StatelessComponent = (props) => +
props.setCount(0)}>
; + + const enhancer = withState("count", "setCount", 0); + const enhanced: React.ComponentClass = enhancer(innerComponent); + + const enhancer2 = withState("count", "setCount", + (p: OutterProps) => p.title.length); + const enhanced2: React.ComponentClass = enhancer2(innerComponent); +} + +function testWithReducer() { + interface State { count: number } + interface Action { type: string } + interface InnerProps { title: string; count: number; dispatch: (a: Action) => void; } + interface OutterProps { title: string; } + const innerComponent: React.StatelessComponent = (props: InnerProps) => +
props.dispatch({type: "INCREMENT"})}>
; + + const enhancer = withReducer("count", "dispatch", + (s: number, a: Action) => s + 1, 0); + const enhanced: React.ComponentClass = enhancer(innerComponent); + + const enhancer2 = withReducer("count", "dispatch", + (s: number, a: Action) => s + 1, + (props: OutterProps) => props.title.length); + const enhanced2: React.ComponentClass = enhancer2(innerComponent); +} + +function testBranch() { + interface InnerProps { count: number; update: () => void; } + interface OutterProps { toggled: boolean } + + const innerComponent: React.StatelessComponent = (props: InnerProps) => +
props.update()}>{props.count}
; + + const enhancer = branch( + (props: OutterProps) => props.toggled, + withState("count", "update", 0), + withState("count", "update", 100) + ); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + +function testRenderComponent() { + interface InnerProps { count: number; update: () => void; } + interface OutterProps { toggled: boolean } + + const innerComponent = () =>
Hello
; + + const enhancer = renderComponent(() => Nop!); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + diff --git a/recompose/recompose.d.ts b/recompose/recompose.d.ts new file mode 100644 index 0000000000..cef352dc7c --- /dev/null +++ b/recompose/recompose.d.ts @@ -0,0 +1,334 @@ +// Type definitions for Recompose v0.20.2 +// Project: https://github.com/acdlite/recompose +// Definitions by: Iskander Sierra +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'recompose' { + + import * as React from 'react'; + import { ComponentClass, StatelessComponent, ValidationMap } from 'react'; + + type Component

= ComponentClass

| StatelessComponent

; + type mapper = (input: TInner) => TOutter; + type predicate = mapper; + type predicateDiff = (current: T, next: T) => boolean + interface Subscribable { + subscribe: Function; + } + + interface ComponentEnhancer { + (component: Component): ComponentClass; + } + interface InferableComponentEnhancer { + )>(component: TComp): TComp; + } + + + // Higher-order components: https://github.com/acdlite/recompose/blob/master/docs/API.md#higher-order-components + + // mapProps: https://github.com/acdlite/recompose/blob/master/docs/API.md#mapprops + export function mapProps( + propsMapper: mapper + ): ComponentEnhancer; + + // withProps: https://github.com/acdlite/recompose/blob/master/docs/API.md#withprops + export function withProps( + createProps: TInner | mapper + ): ComponentEnhancer; + + // withPropsOnChange: https://github.com/acdlite/recompose/blob/master/docs/API.md#withpropsonchange + export function withPropsOnChange( + shouldMapOrKeys: string[] | predicateDiff, + createProps: mapper + ): ComponentEnhancer; + + // withHandlers: https://github.com/acdlite/recompose/blob/master/docs/API.md#withhandlers + type EventHandler = Function; + type HandleCreators = { + [handlerName: string]: mapper; + }; + export function withHandlers( + handlerCreators: HandleCreators + ): ComponentEnhancer; + + // defaultProps: https://github.com/acdlite/recompose/blob/master/docs/API.md#defaultprops + export function defaultProps( + props: Object + ): InferableComponentEnhancer; + + // renameProp: https://github.com/acdlite/recompose/blob/master/docs/API.md#renameProp + export function renameProp( + outterName: string, innerName: string + ): ComponentEnhancer; + + // renameProps: https://github.com/acdlite/recompose/blob/master/docs/API.md#renameProps + type NameMap = { + [outterName: string]: string; + }; + export function renameProps( + nameMap: NameMap + ): ComponentEnhancer; + + // flattenProp: https://github.com/acdlite/recompose/blob/master/docs/API.md#flattenProp + export function flattenProp( + propName: string + ): ComponentEnhancer; + + // withState: https://github.com/acdlite/recompose/blob/master/docs/API.md#withState + export function withState( + stateName: string, + stateUpdaterName: string, + initialState: any | mapper + ): ComponentEnhancer void }*/, TOutter>; + + // withReducer: https://github.com/acdlite/recompose/blob/master/docs/API.md#withReducer + type reducer = (s: TState, a: TAction) => TState; + export function withReducer( + stateName: string, + dispatchName: string, + reducer: reducer, + initialState: TState + ): ComponentEnhancer; + export function withReducer( + stateName: string, + dispatchName: string, + reducer: reducer, + initialState: (props: TOutter) => TState + ): ComponentEnhancer; + + // branch: https://github.com/acdlite/recompose/blob/master/docs/API.md#branch + export function branch( + test: predicate, + trueEnhancer: InferableComponentEnhancer, + falseEnhancer: InferableComponentEnhancer + ): ComponentEnhancer; + + // renderComponent: https://github.com/acdlite/recompose/blob/master/docs/API.md#renderComponent + export function renderComponent( + component: string | Component + ): ComponentEnhancer; + + // renderNothing: https://github.com/acdlite/recompose/blob/master/docs/API.md#renderNothing + export const renderNothing: InferableComponentEnhancer; + + // shouldUpdate: https://github.com/acdlite/recompose/blob/master/docs/API.md#shouldUpdate + export function shouldUpdate( + test: predicateDiff + ): InferableComponentEnhancer; + + // pure: https://github.com/acdlite/recompose/blob/master/docs/API.md#pure + export function pure)> + (component: TComp): TComp; + + // onlyUpdateForKeys: https://github.com/acdlite/recompose/blob/master/docs/API.md#onlyUpdateForKeys + export function onlyUpdateForKeys( + propKeys: Array + ) : InferableComponentEnhancer; + + // onlyUpdateForPropTypes: https://github.com/acdlite/recompose/blob/master/docs/API.md#onlyUpdateForPropTypes + export const onlyUpdateForPropTypes: InferableComponentEnhancer; + + // withContext: https://github.com/acdlite/recompose/blob/master/docs/API.md#withContext + export function withContext( + childContextTypes: ValidationMap, + getChildContext: mapper + ) : InferableComponentEnhancer; + + // getContext: https://github.com/acdlite/recompose/blob/master/docs/API.md#getContext + export function getContext( + contextTypes: ValidationMap + ) : InferableComponentEnhancer; + + // lifecycle: https://github.com/acdlite/recompose/blob/master/docs/API.md#lifecycle + interface ReactLifeCycleFunctions { + componentWillMount?: Function; + componentDidMount?: Function; + componentWillReceiveProps?: Function; + shouldComponentUpdate?: Function; + componentWillUpdate?: Function; + componentDidUpdate?: Function; + componentWillUnmount?: Function; + } + export function lifecycle( + spec: ReactLifeCycleFunctions + ): InferableComponentEnhancer; + + // toClass: https://github.com/acdlite/recompose/blob/master/docs/API.md#toClass + export const toClass: InferableComponentEnhancer; + + + // Static property helpers: https://github.com/acdlite/recompose/blob/master/docs/API.md#static-property-helpers + + // setStatic: https://github.com/acdlite/recompose/blob/master/docs/API.md#setStatic + export function setStatic( + key: string, value: any + ): ComponentEnhancer; + + // setPropTypes: https://github.com/acdlite/recompose/blob/master/docs/API.md#setPropTypes + export function setPropTypes( + propTypes: ValidationMap + ): ComponentEnhancer; + + // setDisplayName: https://github.com/acdlite/recompose/blob/master/docs/API.md#setDisplayName + export function setDisplayName( + displayName: string + ): ComponentEnhancer; + + + // Utilities: https://github.com/acdlite/recompose/blob/master/docs/API.md#utilities + + // compose: https://github.com/acdlite/recompose/blob/master/docs/API.md#compose + export function compose( + ...functions: Function[] + ): ComponentEnhancer; + // export function compose( + // ...functions: Array + // ): ComponentEnhancer; + // export function compose( + // ...functions: Array + // ): ComponentEnhancer; + + // getDisplayName: https://github.com/acdlite/recompose/blob/master/docs/API.md#getDisplayName + export function getDisplayName( + component: Component + ): string; + + // wrapDisplayName: https://github.com/acdlite/recompose/blob/master/docs/API.md#wrapDisplayName + export function wrapDisplayName( + component: Component, + wrapperName: string + ): string; + + // shallowEqual: https://github.com/acdlite/recompose/blob/master/docs/API.md#shallowEqual + export function shallowEqual( + a: Object, b: Object + ): boolean; + + // isClassComponent: https://github.com/acdlite/recompose/blob/master/docs/API.md#isClassComponent + export function isClassComponent( + value: any + ): boolean; + + // createEagerElement: https://github.com/acdlite/recompose/blob/master/docs/API.md#createEagerElement + export function createEagerElement( + type: Component | string, + props?: Object, + children?: React.ReactNode + ): React.ReactElement; + + // createEagerFactory: https://github.com/acdlite/recompose/blob/master/docs/API.md#createEagerFactory + type componentFactory = (props?: Object, children?: React.ReactNode) => React.ReactElement; + export function createEagerFactory( + type: Component | string + ): componentFactory; + + // createSink: https://github.com/acdlite/recompose/blob/master/docs/API.md#createSink + export function createSink( + callback: (props: Object) => void + ): React.ComponentClass; // ??? + + // componentFromProp: https://github.com/acdlite/recompose/blob/master/docs/API.md#componentFromProp + export function componentFromProp( + propName: string + ): StatelessComponent; + + // nest: https://github.com/acdlite/recompose/blob/master/docs/API.md#nest + export function nest( + ...Components: (string | Component)[] + ): React.ComponentClass; // ??? + + // hoistStatics: https://github.com/acdlite/recompose/blob/master/docs/API.md#hoistStatics + export function hoistStatics( + hoc: InferableComponentEnhancer + ): InferableComponentEnhancer; + + + + // Observable utilities: https://github.com/acdlite/recompose/blob/master/docs/API.md#observable-utilities + + // componentFromStream: https://github.com/acdlite/recompose/blob/master/docs/API.md#componentFromStream + export function componentFromStream( + propsToReactNode: mapper, Subscribable> + ): Component; // ??? + + // mapPropsStream: https://github.com/acdlite/recompose/blob/master/docs/API.md#mapPropsStream + export function mapPropsStream( + transform: mapper, Subscribable> + ): ComponentEnhancer; + + // createEventHandler: https://github.com/acdlite/recompose/blob/master/docs/API.md#createEventHandler + type EventHandlerOf> = { + handler: (value: T) => void; + stream: TSubs; + }; + export function createEventHandler>(): EventHandlerOf; + + // setObservableConfig: https://github.com/acdlite/recompose/blob/master/docs/API.md#setObservableConfig + type ObservableConfig = { + fromESObservable?: (observable: Subscribable) => any; + toESObservable?: (stream: any) => Subscribable; + }; + export function setObservableConfig(config: ObservableConfig): void; +} + +// https://github.com/acdlite/recompose/blob/master/docs/API.md#rxjs +declare module 'recompose/rxjsObservableConfig' { + + import { ObservableConfig } from 'recompose'; + + const rxjsconfig: ObservableConfig; + + export default rxjsconfig; +} + +// https://github.com/acdlite/recompose/blob/master/docs/API.md#rxjs-4-legacy +declare module 'recompose/rxjs4ObservableConfig' { + + import { ObservableConfig } from 'recompose'; + + const rxjs4config: ObservableConfig; + + export default rxjs4config; +} + +// https://github.com/acdlite/recompose/blob/master/docs/API.md#most +declare module 'recompose/mostObservableConfig' { + + import { ObservableConfig } from 'recompose'; + + const mostConfig: ObservableConfig; + + export default mostConfig; +} + +// https://github.com/acdlite/recompose/blob/master/docs/API.md#xstream +declare module 'recompose/xstreamObservableConfig' { + + import { ObservableConfig } from 'recompose'; + + const xstreamConfig: ObservableConfig; + + export default xstreamConfig; +} + +// https://github.com/acdlite/recompose/blob/master/docs/API.md#bacon +declare module 'recompose/baconObservableConfig' { + + import { ObservableConfig } from 'recompose'; + + const baconConfig: ObservableConfig; + + export default baconConfig; +} + +// https://github.com/acdlite/recompose/blob/master/docs/API.md#kefir +declare module 'recompose/kefirObservableConfig' { + + import { ObservableConfig } from 'recompose'; + + const kefirConfig: ObservableConfig; + + export default kefirConfig; +} From 07453cbf8e99a21f978f9cc35d8eb3fa648f2c93 Mon Sep 17 00:00:00 2001 From: Natalie Date: Fri, 30 Sep 2016 14:09:56 +0200 Subject: [PATCH 085/554] Update typescript definition for selectize to 0.12.13 (#11570) --- selectize/selectize.d.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/selectize/selectize.d.ts b/selectize/selectize.d.ts index b593fa73dd..cea529e07f 100644 --- a/selectize/selectize.d.ts +++ b/selectize/selectize.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Selectize 0.11.2 +// Type definitions for Selectize 0.12.13 // Project: https://github.com/brianreavis/selectize.js -// Definitions by: Adi Dahiya +// Definitions by: Adi Dahiya , Natalie Bausch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -562,6 +562,11 @@ declare namespace Selectize { * Clears the render cache. Takes an optional template argument (e.g. "option", "item") to clear only that cache. */ clearCache(template?: string): void; + + /** + * When the `settings.placeholder` value is changed, the new placeholder will be displayed. + */ + updatePlaceholder(): void; } interface ISearchToken { @@ -609,4 +614,3 @@ interface JQuery { interface HTMLElement { selectize: Selectize.IApi; } - From da9bf4d701ded823f1a98fce9b7d2fcc2ef98922 Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Fri, 30 Sep 2016 15:11:07 +0300 Subject: [PATCH 086/554] [react-router-redux] Update action payload type (#11559) The payload for React Redux Router action is a location object. For more information look at the source code [here](https://github.com/reactjs/react-router-redux/blob/master/src/sync.js#L95) --- react-router-redux/react-router-redux.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react-router-redux/react-router-redux.d.ts b/react-router-redux/react-router-redux.d.ts index 6a9d499b1f..a781fed663 100644 --- a/react-router-redux/react-router-redux.d.ts +++ b/react-router-redux/react-router-redux.d.ts @@ -29,7 +29,7 @@ declare namespace ReactRouterRedux { type RouterAction = { type: string - payload?: any + payload?: LocationDescriptor } interface RouteActions { From 2b68598bb60edab2a65c60c3efcae9552aa1fcbc Mon Sep 17 00:00:00 2001 From: osechet Date: Fri, 30 Sep 2016 14:15:16 +0200 Subject: [PATCH 087/554] [openlayers] Rewrite for openlayers 3.18.2 (#11339) --- openlayers/openlayers-3.6.0-tests.ts | 563 + openlayers/openlayers-3.6.0.d.ts | 5403 +++++++ openlayers/openlayers-tests.ts | 286 +- openlayers/openlayers.d.ts | 18792 ++++++++++++++++++------- 4 files changed, 19740 insertions(+), 5304 deletions(-) create mode 100644 openlayers/openlayers-3.6.0-tests.ts create mode 100644 openlayers/openlayers-3.6.0.d.ts diff --git a/openlayers/openlayers-3.6.0-tests.ts b/openlayers/openlayers-3.6.0-tests.ts new file mode 100644 index 0000000000..52d7535710 --- /dev/null +++ b/openlayers/openlayers-3.6.0-tests.ts @@ -0,0 +1,563 @@ +/// + +// Basic type variables for test functions +var voidValue: void; +var numberValue: number; +var booleanValue: boolean; +var stringValue: string; +var jsonValue: JSON; + +// Callback predefinitions for OpenLayers +var preRenderFunction: ol.PreRenderFunction; +var transformFunction: ol.TransformFunction; +var coordinateFormatType: ol.CoordinateFormatType; +var featureStyleFunction: ol.FeatureStyleFunction; +var featureLoader: ol.FeatureLoader; +var easingFunction: (t: number) => number; + +// Type variables for OpenLayers +var circle: ol.geom.Circle; +var color: ol.Color; +var coordinate: ol.Coordinate; +var coordinatesArray: Array; +var coordinatesArrayDim2: Array>; +var extent: ol.Extent; +var boundingCoordinates: Array; +var size: ol.Size; +var style: ol.style.Style; +var styleArray: Array; +var feature: ol.Feature; +var featureArray: Array; +var graticule: ol.Graticule +var geometry: ol.geom.Geometry; +var geometriesArray: Array; +var feature: ol.Feature; +var featureArray: Array; +var featureFormat: ol.format.Feature; +var geometry: ol.geom.Geometry; +var geometryCollection: ol.geom.GeometryCollection; +var geometryLayout: ol.geom.GeometryLayout; +var geometryType: ol.geom.GeometryType; +var linearRing: ol.geom.LinearRing; +var lineString: ol.geom.LineString; +var loadingstrategy: ol.LoadingStrategy; +var multiLineString: ol.geom.MultiLineString; +var multiPoint: ol.geom.MultiPoint; +var multiPolygon: ol.geom.MultiPolygon; +var point: ol.geom.Point; +var polygon: ol.geom.Polygon; +var simpleGeometry: ol.geom.SimpleGeometry; +var tilegrid: ol.tilegrid.TileGrid; +var vector: ol.source.Vector; +var projection: ol.proj.Projection; +var projectionLike: ol.proj.ProjectionLike; +var transformFn: ol.TransformFunction; + +// +// ol.Attribution +// + +var attribution: ol.Attribution = new ol.Attribution({ + html: stringValue, +}); + +// +// ol.color +// +color = ol.color.asArray(color); +color = ol.color.asArray(stringValue); +stringValue = ol.color.asString(color); +stringValue = ol.color.asString(stringValue); + +// +// ol.extent +// +transformFunction = function (input: number[]) { + var returnData: number[]; + return returnData; +}; +transformFunction = function (input: number[], output: number[]) { + var returnData: number[]; + return returnData; +}; +transformFunction = function (input: number[], output: number[], dimension: number) { + var returnData: number[]; + return returnData; +} +extent = ol.extent.applyTransform(extent, transformFunction); +ol.extent.applyTransform(extent, transformFunction, extent); +extent = ol.extent.boundingExtent(boundingCoordinates) +extent = ol.extent.buffer(extent, numberValue); +ol.extent.buffer(extent, numberValue, extent); +booleanValue = ol.extent.containsCoordinate(extent, coordinate); +booleanValue = ol.extent.containsExtent(extent, extent); +booleanValue = ol.extent.containsXY(extent, numberValue, numberValue); +extent = ol.extent.createEmpty(); +booleanValue = ol.extent.equals(extent, extent); +extent = ol.extent.extend(extent, extent); +coordinate = ol.extent.getBottomLeft(extent); +coordinate = ol.extent.getBottomRight(extent); +coordinate = ol.extent.getCenter(extent); +numberValue = ol.extent.getHeight(extent); +extent = ol.extent.getIntersection(extent, extent); +ol.extent.getIntersection(extent, extent, extent); +size = ol.extent.getSize(extent); +coordinate = ol.extent.getTopLeft(extent); +coordinate = ol.extent.getTopRight(extent); +numberValue = ol.extent.getWidth(extent); +booleanValue = ol.extent.intersects(extent, extent); +booleanValue = ol.extent.isEmpty(extent); + +// +// ol.featureloader +// +featureLoader = ol.featureloader.xhr(stringValue, featureFormat); + +// +// ol.loadingstrategy +// +loadingstrategy = ol.loadingstrategy.all; +loadingstrategy = ol.loadingstrategy.bbox; +loadingstrategy = ol.loadingstrategy.tile(tilegrid); + +// +// +// ol.geom.Circle +// +booleanValue = circle.intersectsExtent(extent); +circle = circle.transform(projectionLike, projectionLike); + +// +// +// ol.geom.Geometry +// +var geometryResult: ol.geom.Geometry; +coordinate = geometryResult.getClosestPoint(coordinate); +geometryResult.getClosestPoint(coordinate, coordinate); +extent = geometryResult.getExtent(); +geometryResult.getExtent(extent); +geometryResult.transform(projection, projection); + +// +// +// ol.geom.GeometryCollection +// +geometryCollection = new ol.geom.GeometryCollection(geometriesArray) +geometryCollection = new ol.geom.GeometryCollection(); +voidValue = geometryCollection.applyTransform(transformFn); +geometryCollection = geometryCollection.clone(); +geometriesArray = geometryCollection.getGeometries(); +geometryType = geometryCollection.getType(); +booleanValue = geometryCollection.intersectsExtent(extent); +voidValue = geometryCollection.setGeometries(geometriesArray); + +// +// +// ol.geom.LinearRing +// +linearRing = new ol.geom.LinearRing(coordinatesArray); +linearRing = new ol.geom.LinearRing(coordinatesArray, geometryLayout); +linearRing = linearRing.clone(); +numberValue = linearRing.getArea(); +coordinatesArray = linearRing.getCoordinates(); +geometryType = linearRing.getType(); +voidValue = linearRing.setCoordinates(coordinatesArray); +voidValue = linearRing.setCoordinates(coordinatesArray, geometryLayout); + +// +// +// ol.geom.LineString +// +lineString = new ol.geom.LineString(coordinatesArray); +lineString = new ol.geom.LineString(coordinatesArray, geometryLayout); +voidValue = lineString.appendCoordinate(coordinate); +lineString = lineString.clone(); +coordinate = lineString.getCoordinateAtM(numberValue); +coordinate = lineString.getCoordinateAtM(numberValue, booleanValue); +coordinatesArray = lineString.getCoordinates(); +numberValue = lineString.getLength(); +geometryType = lineString.getType(); +booleanValue = lineString.intersectsExtent(extent); +voidValue = lineString.setCoordinates(coordinatesArray); +voidValue = lineString.setCoordinates(coordinatesArray, geometryLayout); + +// +// +// ol.geom.MultiLineString +// +var lineStringsArray: Array; + +multiLineString = new ol.geom.MultiLineString(coordinatesArrayDim2); +multiLineString = new ol.geom.MultiLineString(coordinatesArrayDim2, geometryLayout); +voidValue = multiLineString.appendLineString(lineString); +multiLineString = multiLineString.clone(); +coordinate = multiLineString.getCoordinateAtM(numberValue); +coordinate = multiLineString.getCoordinateAtM(numberValue, booleanValue); +coordinate = multiLineString.getCoordinateAtM(numberValue, booleanValue, booleanValue); +coordinatesArrayDim2 = multiLineString.getCoordinates(); +lineString = multiLineString.getLineString(numberValue); +lineStringsArray = multiLineString.getLineStrings(); +geometryType = multiLineString.getType(); +booleanValue = multiLineString.intersectsExtent(extent); +voidValue = multiLineString.setCoordinates(coordinatesArrayDim2); +voidValue = multiLineString.setCoordinates(coordinatesArrayDim2, geometryLayout); + +// +// +// ol.geom.MultiPoint +// +var pointsArray: Array; + +multiPoint = new ol.geom.MultiPoint(coordinatesArray); +multiPoint = new ol.geom.MultiPoint(coordinatesArray, geometryLayout); +voidValue = multiPoint.appendPoint(point); +multiPoint = multiPoint.clone(); +coordinatesArray = multiPoint.getCoordinates(); +point = multiPoint.getPoint(numberValue); +pointsArray = multiPoint.getPoints(); +geometryType = multiPoint.getType(); +booleanValue = multiPoint.intersectsExtent(extent); +voidValue = multiPoint.setCoordinates(coordinatesArray); +voidValue = multiPoint.setCoordinates(coordinatesArray, geometryLayout); + +// +// +// ol.geom.MultiPolygon +// +var coordinatesArrayDim3: Array>>; +var polygonsArray: Array; + +multiPolygon = new ol.geom.MultiPolygon(coordinatesArrayDim3); +multiPolygon = new ol.geom.MultiPolygon(coordinatesArrayDim3, geometryLayout); +voidValue = multiPolygon.appendPolygon(polygon); +multiPolygon = multiPolygon.clone(); +numberValue = multiPolygon.getArea(); +coordinatesArrayDim3 = multiPolygon.getCoordinates(); +coordinatesArrayDim3 = multiPolygon.getCoordinates(booleanValue); +multiPoint = multiPolygon.getInteriorPoints(); +polygon = multiPolygon.getPolygon(numberValue); +polygonsArray = multiPolygon.getPolygons(); +geometryType = multiPolygon.getType(); +booleanValue = multiPolygon.intersectsExtent(extent); +voidValue = multiPolygon.setCoordinates(coordinatesArrayDim3); +voidValue = multiPolygon.setCoordinates(coordinatesArrayDim3, geometryLayout); + +// +// +// ol.geom.Point +// +point = new ol.geom.Point(coordinate); +point = new ol.geom.Point(coordinate, geometryLayout); +point = point.clone(); +coordinate = point.getCoordinates(); +geometryType = point.getType(); +booleanValue = point.intersectsExtent(extent); +voidValue = point.setCoordinates(coordinate); +voidValue = point.setCoordinates(coordinate, geometryLayout); + +// +// +// ol.geom.Polygon +// +var localSphere: ol.Sphere; +var linearRingsArray: Array; + +polygon = new ol.geom.Polygon(coordinatesArrayDim2); +polygon = new ol.geom.Polygon(coordinatesArrayDim2, geometryLayout); +polygon = ol.geom.Polygon.circular(localSphere, coordinate, numberValue); +polygon = ol.geom.Polygon.circular(localSphere, coordinate, numberValue, numberValue); +voidValue = polygon.appendLinearRing(linearRing); +polygon = polygon.clone(); +numberValue = polygon.getArea(); +coordinatesArrayDim2 = polygon.getCoordinates(); +coordinatesArrayDim2 = polygon.getCoordinates(booleanValue); +point = polygon.getInteriorPoint(); +linearRing = polygon.getLinearRing(numberValue); +linearRingsArray = polygon.getLinearRings(); +geometryType = polygon.getType(); +booleanValue = polygon.intersectsExtent(extent); + +// +// +// ol.geom.SimpleGeometry +// +simpleGeometry.applyTransform(transformFn); +coordinate = simpleGeometry.getFirstCoordinate(); +coordinate = simpleGeometry.getLastCoordinate(); +geometryLayout = simpleGeometry.getLayout(); +voidValue = simpleGeometry.translate(numberValue, numberValue); + +// +// ol.source +// +vector = new ol.source.Vector({ + features: [feature] +}); + +// +// ol.Feature +// +feature = new ol.Feature(); +feature = new ol.Feature(geometry); +feature = new ol.Feature({ + geometry: geometry +}); +feature = feature.clone(); +geometry = feature.getGeometry(); +stringValue = feature.getGeometryName(); +var featureGetId: string | number = feature.getId(); +var featureGetStyle: ol.style.Style | Array | ol.FeatureStyleFunction = feature.getStyle(); +featureStyleFunction = feature.getStyleFunction(); +voidValue = feature.setGeometry(geometry); +voidValue = feature.setGeometryName(stringValue); +voidValue = feature.setId(stringValue); +voidValue = feature.setId(numberValue); +voidValue = feature.setStyle(style); +voidValue = feature.setStyle(styleArray); +voidValue = feature.setStyle(featureStyleFunction); + +// +// ol.View +// + +var view: ol.View = new ol.View({ + center: [0, 0], + zoom: numberValue, +}); + +// +// ol.layer.Tile +// +var tileLayer: ol.layer.Tile = new ol.layer.Tile({ + source: new ol.source.MapQuest({ layer: 'osm' }) +}); + +// +// ol.proj +// +projection = new ol.proj.Projection({ + code:stringValue, +}); +projection.setExtent(projection.getExtent()); + +// +// ol.Map +// + +var map: ol.Map = new ol.Map({ + view: view, + layers: [tileLayer], + target: stringValue +}); +map.beforeRender(preRenderFunction); + +// +// ol.source.ImageWMS +// +var imageWMS: ol.source.ImageWMS = new ol.source.ImageWMS({ + serverType: stringValue, + url:stringValue +}); + +// +// ol.source.Source +// +const source = imageWMS as ol.source.Source; +voidValue = source.refresh(); +projection = source.getProjection(); + +// +// ol.source.TileWMS +// +var tileWMS: ol.source.TileWMS = new ol.source.TileWMS({ + params: {}, + serverType: stringValue, + url:stringValue +}); + +tileWMS.updateParams(tileWMS.getParams()); +stringValue = tileWMS.getGetFeatureInfoUrl([0, 0], 1, "EPSG:4326", {}); + +// +// ol.source.WMTS +// +var wmts: ol.source.WMTS = new ol.source.WMTS({ + tileGrid: new ol.tilegrid.WMTS({}), + layer: "", + style: "", + matrixSet: "", + wrapX: true +}); + +// +// ol.animation +// +var bounceOptions: olx.animation.BounceOptions; +bounceOptions.duration = numberValue; +bounceOptions.start = numberValue; +bounceOptions.resolution = numberValue; +bounceOptions.easing = easingFunction; +preRenderFunction = ol.animation.bounce(bounceOptions); + +var panOptions: olx.animation.PanOptions; +panOptions.duration = numberValue; +panOptions.start = numberValue; +panOptions.source = coordinate; +panOptions.easing = easingFunction; +preRenderFunction = ol.animation.pan(panOptions); + +var rotateOptions: olx.animation.RotateOptions; +rotateOptions.duration = numberValue; +rotateOptions.start = numberValue; +rotateOptions.anchor = coordinate; +rotateOptions.rotation = numberValue; +rotateOptions.easing = easingFunction; +preRenderFunction = ol.animation.rotate(rotateOptions); + +var zoomOptions: olx.animation.ZoomOptions; +zoomOptions.duration = numberValue; +zoomOptions.start = numberValue; +zoomOptions.resolution = numberValue; +zoomOptions.easing = easingFunction; +preRenderFunction = ol.animation.zoom(zoomOptions); +map.beforeRender(preRenderFunction); + +// +// ol.coordinate +// +coordinate = ol.coordinate.add(coordinate, coordinate); +coordinateFormatType = ol.coordinate.createStringXY(); +coordinateFormatType = ol.coordinate.createStringXY(numberValue); +stringValue = ol.coordinate.format(coordinate, stringValue); +stringValue = ol.coordinate.format(coordinate, stringValue, numberValue); +coordinate = ol.coordinate.rotate(coordinate, numberValue); +stringValue = ol.coordinate.toStringHDMS(); +stringValue = ol.coordinate.toStringHDMS(coordinate); +stringValue = ol.coordinate.toStringXY(); +stringValue = ol.coordinate.toStringXY(coordinate); +stringValue = ol.coordinate.toStringXY(coordinate, numberValue); + +// +// ol.easing +// +easingFunction = ol.easing.easeIn; +easingFunction = ol.easing.easeOut; +easingFunction = ol.easing.inAndOut; +easingFunction = ol.easing.linear; +easingFunction = ol.easing.upAndDown; + +// +// ol.Geolocation +// +var geolocation: ol.Geolocation = new ol.Geolocation({ + projection: projection +}); +geolocation.on('change', function (evt) { + window.console.log(geolocation.getPosition()); +}); + +// +// ol.Graticule +// + +graticule = new ol.Graticule(); +graticule = new ol.Graticule({ + map: map, +}); +var graticuleMap: ol.Map = graticule.getMap(); +var graticuleMeridians: Array = graticule.getMeridians(); +var graticuleParallels: Array = graticule.getParallels(); +graticule.setMap(graticuleMap); + +// +// ol.DeviceOrientation +// + +var deviceOrientation: ol.DeviceOrientation = new ol.DeviceOrientation({ + tracking: true, +}); +deviceOrientation.on('change', function (evt) { + window.console.log(deviceOrientation.getHeading()); +}); + +// +// ol.Overlay +// + +var popup: ol.Overlay = new ol.Overlay({ + element: document.getElementById('popup') +}); +map.addOverlay(popup); +var popupElement: Element = popup.getElement(); +var popupMap: ol.Map = popup.getMap(); +var popupOffset: Array = popup.getOffset(); +coordinate = popup.getPosition(); +var popupPositioning: ol.OverlayPositioning = popup.getPositioning(); +popup.setElement(popupElement); +popup.setMap(popupMap); +popup.setOffset(popupOffset); +popup.setPosition(coordinate); +popup.setPositioning(popupPositioning); + + +// +// ol.format.GeoJSON +// + +var geojsonOptions: olx.format.GeoJSONOptions; +geojsonOptions.defaultDataProjection = "EPSG"; +geojsonOptions.defaultDataProjection = projection; +geojsonOptions.geometryName = "geom"; + +var geojsonFormat: ol.format.GeoJSON; +geojsonFormat = new ol.format.GeoJSON(); +geojsonFormat = new ol.format.GeoJSON(geojsonOptions); + +// Test options +var readOptions: olx.format.ReadOptions; +readOptions.dataProjection = "EPSG"; +readOptions.dataProjection = projection; +readOptions.featureProjection = "EPSG"; +readOptions.featureProjection = projection; + +var writeOptions: olx.format.WriteOptions; +writeOptions.dataProjection = "EPSG"; +writeOptions.dataProjection = projection; +writeOptions.featureProjection = "EPSG"; +writeOptions.featureProjection = projection; +writeOptions.rightHanded = false; + +// Test functions +feature = geojsonFormat.readFeature("json"); +feature = geojsonFormat.readFeature("json", readOptions); +featureArray = geojsonFormat.readFeatures("json"); +featureArray = geojsonFormat.readFeatures("json", readOptions); +geometry = geojsonFormat.readGeometry("geometry"); +geometry = geojsonFormat.readGeometry("geometry", readOptions); +stringValue = geojsonFormat.writeFeature(feature); +stringValue = geojsonFormat.writeFeature(feature, writeOptions); +stringValue = geojsonFormat.writeFeatures(featureArray); +stringValue = geojsonFormat.writeFeatures(featureArray, writeOptions); +stringValue = geojsonFormat.writeGeometry(geometry); +stringValue = geojsonFormat.writeGeometry(geometry, writeOptions); +jsonValue = geojsonFormat.writeFeatureObject(feature); +jsonValue = geojsonFormat.writeFeatureObject(feature, writeOptions); +jsonValue = geojsonFormat.writeFeaturesObject(featureArray); +jsonValue = geojsonFormat.writeFeaturesObject(featureArray, writeOptions); +jsonValue = geojsonFormat.writeGeometryObject(geometry); +jsonValue = geojsonFormat.writeGeometryObject(geometry, writeOptions); + +// +// ol.interactions +// +var modify: ol.interaction.Modify = new ol.interaction.Modify({ + features: new ol.Collection(featureArray) +}); + +var draw: ol.interaction.Draw = new ol.interaction.Draw({ + type: "Point" +}) + +const select: ol.interaction.Select = new ol.interaction.Select({ + layers: (layer: ol.layer.Layer) => true, +}); diff --git a/openlayers/openlayers-3.6.0.d.ts b/openlayers/openlayers-3.6.0.d.ts new file mode 100644 index 0000000000..91b822d6b6 --- /dev/null +++ b/openlayers/openlayers-3.6.0.d.ts @@ -0,0 +1,5403 @@ +// Type definitions for OpenLayers v3.6.0 +// Project: http://openlayers.org/ +// Definitions by: Wouter Goedhart +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace olx { + interface StaticImageOptions { + + /** Attributions */ + attributions?: Array + + /*** The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail. */ + crossOrigin?: string + + /*** Extent of the image in map coordinates. This is the [left, bottom, right, top] map coordinates of your image.*/ + imageExtent: ol.Extent; + + /*** Size of the image in pixels.*/ + imageSize?: ol.Size; + + /*** experimental Optional function to load an image given a URL.*/ + imageLoadFunction?: ol.TileLoadFunctionType; + + /*** Optional logo.*/ + logo?: olx.LogoOptions; + + /*** experimental Projection.*/ + projection: ol.proj.Projection; + + /*** Image URL.*/ + url: string; + } + + interface ZoomToExtentOptions { + /*** Class name. Default is ol-zoom-extent.*/ + className?: string; + + /*** Target.*/ + target?: Element; + + /*** Text label to use for the button. Default is E. Instead of text, also a Node (e.g. a span element) can be used.*/ + label?: string | Node; + + /*** Text label to use for the button tip. Default is Zoom to extent.*/ + tipLabel?: string; + + /*** The extent to zoom to. If undefined the validity extent of the view projection is used.*/ + extent: ol.Extent; + } + + interface OverviewMapOptions { + /*** Whether the control should start collapsed or not (expanded). Default to true.*/ + collapsed?: boolean; + /*** Text label to use for the expanded overviewmap button. Default is «. Instead of text, also a Node (e.g. a span element) can be used.*/ + collapseLabel? :string | Node; + /*** Whether the control can be collapsed or not. Default to true.*/ + collapsible?: boolean; + /*** Text label to use for the collapsed overviewmap button. Default is ». Instead of text, also a Node (e.g. a span element) can be used.*/ + label?: string | Node; + /*** Layers for the overview map. If not set, then all main map layers are used instead.*/ + layers?: ol.layer.Layer[] | ol.Collection; + /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ + render?: Function; + /*** Specify a target if you want the control to be rendered outside of the map's viewport.*/ + target?: Element; + /*** Text label to use for the button tip. Default is Overview map*/ + tipLabel?: string; + /*** Custom view for the overview map. If not provided, a default view with an EPSG:3857 projection will be used.*/ + view?: ol.View; + } + + interface RotateOptions { + /*** CSS class name. Default is ol-rotate.*/ + className?: string; + /*** Text label to use for the rotate button. Default is ⇧. Instead of text, also a Node (e.g. a span element) can be used.*/ + label?: string | Element; + /*** Text label to use for the rotate tip. Default is Reset rotation.*/ + tipLabel?: string; + /*** Animation duration in milliseconds. Default is 250.*/ + duration?: number; + /*** Hide the control when rotation is 0. Default is true.*/ + autoHide?: boolean; + /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ + render?: Function; + /*** Function called when the control is clicked. This will override the default resetNorth.*/ + resetNorth?: Function; + /*** Target.*/ + target?: Element; + } + + interface AttributionOptions { + + /** HTML markup for this attribution. */ + html: string; + } + + interface DeviceOrientationOptions { + + /** + * Start tracking. Default is false. + */ + tracking?: boolean; + } + + interface FrameState { + + /** + * + */ + pixelRatio: number; + + /** + * + */ + time: number; + + /** + * + */ + viewState: olx.ViewState; + } + + interface FeatureOverlayOptions { + + /** + * Features + */ + features?: Array | ol.Collection | ol.style.StyleFunction; + + /** + * Map + */ + map: ol.Map; + + /** + * Style + */ + style: ol.style.Style | Array; + } + + interface GeolocationOptions { + + /** + * Start Tracking. Default is false. + */ + tracking?: boolean; + + /** + * Tracking options. See http://www.w3.org/TR/geolocation-API/#position_options_interface. + */ + trackingOptions?: PositionOptions; + + /** + * The projection the position is reported in. + */ + projection?: ol.proj.ProjectionLike | ol.proj.Projection; + } + + interface GraticuleOptions { + + /** Reference to an ol.Map object. */ + map?: ol.Map; + + /** The maximum number of meridians and parallels from the center of the map. The default value is 100, which means that at most 200 meridians and 200 parallels will be displayed. The default value is appropriate for conformal projections like Spherical Mercator. If you increase the value more lines will be drawn and the drawing performance will decrease. */ + maxLines?: number; + + /** The stroke style to use for drawing the graticule. If not provided, the lines will be drawn with rgba(0,0,0,0.2), a not fully opaque black. */ + strokeStyle?: ol.style.Stroke; + + /** The target size of the graticule cells, in pixels. Default value is 100 pixels. */ + targetSize?: number; + } + + interface BaseWMSOptions { + + /** Attributions. */ + attributions?: Array; + + /** WMS request parameters. At least a LAYERS param is required. STYLES is '' by default. VERSION is 1.3.0 by default. WIDTH, HEIGHT, BBOX and CRS (SRS for WMS version < 1.3.0) will be set dynamically. */ + params?: any; + + /** The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail. */ + crossOrigin?: string; + + /** experimental Use the ol.Map#pixelRatio value when requesting the image from the remote server. Default is true. */ + hidpi?: boolean; + + /** experimental The type of the remote WMS server: mapserver, geoserver or qgis. Only needed if hidpi is true. Default is undefined. */ + serverType?: ol.source.wms.ServerType; + + /** WMS service URL. */ + url?: string; + + /** Logo. */ + logo?: olx.LogoOptions; + + /** experimental Projection. */ + projection?: ol.proj.ProjectionLike; + } + + interface ImageWMSOptions extends BaseWMSOptions { + + /** experimental Optional function to load an image given a URL. */ + imageLoadFunction?: ol.ImageLoadFunctionType; + + /** Ratio. 1 means image requests are the size of the map viewport, 2 means twice the width and height of the map viewport, and so on. Must be 1 or higher. Default is 1.5. */ + ratio?: number; + + /** Resolutions. If specified, requests will be made for these resolutions only. */ + resolutions?: Array; + } + + interface TileWMSOptions { + + attributions?: Array; + + /**WMS request parameters. At least a LAYERS param is required. STYLES is '' by default. VERSION is 1.3.0 by default. WIDTH, HEIGHT, BBOX and CRS (SRS for WMS version < 1.3.0) will be set dynamically. Required.*/ + params: Object; + /**The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.*/ + crossOrigin?: string; + + /** The size in pixels of the gutter around image tiles to ignore. By setting this property to a non-zero value, images will be requested that are wider and taller than the tile size by a value of 2 x gutter. Defaults to zero. Using a non-zero value allows artifacts of rendering at tile edges to be ignored. If you control the WMS service it is recommended to address "artifacts at tile edges" issues by properly configuring the WMS service. For example, MapServer has a tile_map_edge_buffer configuration parameter for this. See http://mapserver.org/output/tile_mode.html. */ + gutter?: number; + + /** Use the ol.Map#pixelRatio value when requesting the image from the remote server. Default is true.*/ + hidpi?: boolean; + + logo?: string | olx.LogoOptions; + + /** Tile grid. Base this on the resolutions, tilesize and extent supported by the server. If this is not defined, a default grid will be used: if there is a projection extent, the grid will be based on that; if not, a grid based on a global extent with origin at 0,0 will be used. */ + tileGrid?: ol.tilegrid.TileGrid; + + /** experimental Maximum zoom. */ + maxZoom?: number; + + projection?: ol.proj.ProjectionLike; + reprojectionErrorThreshold?: number; + + /** experimental Optional function to load a tile given a URL. */ + tileLoadFunction?: ol.TileLoadFunctionType; + + /** WMS service URL. */ + url?: string; + + /** WMS service urls. Use this instead of url when the WMS supports multiple urls for GetMap requests. */ + urls?: Array; + + /** experimental The type of the remote WMS server. Currently only used when hidpi is true. Default is undefined. */ + serverType?: ol.source.wms.ServerType; + + /** experimental Whether to wrap the world horizontally. When set to false, only one world will be rendered. When true, tiles will be requested for one world only, but they will be wrapped horizontally to render multiple worlds. The default is true. */ + wrapX?: boolean; + } + interface OSMOptions { + /** Attributions */ + attributions?: ol.AttributionLike; + /** Cache size. Default is 2048. */ + cacheSize?: number; + /** + * The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL + * renderer or if you want to access pixel data with the Canvas renderer. + * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail. Default is anonymous. + */ + crossOrigin?: string; + /** Max zoom. Default is 19. */ + maxZoom?: number; + /** Whether the layer is opaque. Default is true. */ + opaque?: boolean; + /** Maximum allowed reprojection error (in pixels). Default is 0.5. Higher values can increase reprojection performance, but decrease precision. */ + reprojectionErrorThreshold?: number; + /** Optional function to load a tile given a URL. */ + tileLoadFunction?: ol.TileLoadFunctionType; + /** URL template. Must include {x}, {y} or {-y}, and {z} placeholders. Default is https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png. */ + url?: string; + /** Whether to wrap the world horizontally. Default is true. */ + wrapX?: boolean; + } + /** + * Object literal with config options for the map logo. + */ + interface LogoOptions { + /** + * Link url for the logo. Will be followed when the logo is clicked. + */ + href: string; + + /** + * Image src for the logo + */ + src: string; + + } + + interface MapOptions { + + /** Controls initially added to the map. If not specified, ol.control.defaults() is used. */ + controls?: any; + + /** The ratio between physical pixels and device-independent pixels (dips) on the device. If undefined then it gets set by using window.devicePixelRatio. */ + pixelRatio?: number; + + /** Interactions that are initially added to the map. If not specified, ol.interaction.defaults() is used. */ + interactions?: any; + + /** The element to listen to keyboard events on. This determines when the KeyboardPan and KeyboardZoom interactions trigger. For example, if this option is set to document the keyboard interactions will always trigger. If this option is not specified, the element the library listens to keyboard events on is the map target (i.e. the user-provided div for the map). If this is not document the target element needs to be focused for key events to be emitted, requiring that the target element has a tabindex attribute. */ + keyboardEventTarget?: any; + + /** Layers. If this is not defined, a map with no layers will be rendered. Note that layers are rendered in the order supplied, so if you want, for example, a vector layer to appear on top of a tile layer, it must come after the tile layer. */ + layers?: Array + + /** When set to true, tiles will be loaded during animations. This may improve the user experience, but can also make animations stutter on devices with slow memory. Default is false. */ + loadTilesWhileAnimating?: boolean; + + /** When set to true, tiles will be loaded while interacting with the map. This may improve the user experience, but can also make map panning and zooming choppy on devices with slow memory. Default is false. */ + loadTilesWhileInteracting?: boolean; + + /** The map logo. A logo to be displayed on the map at all times. If a string is provided, it will be set as the image source of the logo. If an object is provided, the src property should be the URL for an image and the href property should be a URL for creating a link. To disable the map logo, set the option to false. By default, the OpenLayers 3 logo is shown. */ + logo?: any; + + /** Overlays initially added to the map. By default, no overlays are added. */ + overlays?: any; + + /** Renderer. By default, Canvas, DOM and WebGL renderers are tested for support in that order, and the first supported used. Specify a ol.RendererType here to use a specific renderer. Note that at present only the Canvas renderer supports vector data. */ + renderer?: any; + + /** The container for the map, either the element itself or the id of the element. If not specified at construction time, ol.Map#setTarget must be called for the map to be rendered. */ + target?: any; + + /** The map's view. No layer sources will be fetched unless this is specified at construction time or through ol.Map#setView. */ + view?: ViewOptions; + } + + interface OverlayOptions { + + /** + * The overlay element. + */ + element?: Element; + + /** + * Offsets in pixels used when positioning the overlay. The fist element in the array is the horizontal offset. A positive value shifts the overlay right. The second element in the array is the vertical offset. A positive value shifts the overlay down. Default is [0, 0]. + */ + offset?: Array; + + /** + * The overlay position in map projection. + */ + position?: ol.Coordinate; + + /** + * Defines how the overlay is actually positioned with respect to its position property. Possible values are 'bottom-left', 'bottom-center', 'bottom-right', 'center-left', 'center-center', 'center-right', 'top-left', 'top-center', and 'top-right'. Default is 'top-left'. + */ + positioning?: ol.OverlayPositioning; + + /** + * Whether event propagation to the map viewport should be stopped. Default is true. If true the overlay is placed in the same container as that of the controls (CSS class name ol-overlaycontainer-stopevent); if false it is placed in the container with CSS class name ol-overlaycontainer. + */ + stopEvent?: boolean; + + /** + * Whether the overlay is inserted first in the overlay container, or appended. Default is true. If the overlay is placed in the same container as that of the controls (see the stopEvent option) you will probably set insertFirst to true so the overlay is displayed below the controls. + */ + insertFirst?: boolean; + + /** + * If set to true the map is panned when calling setPosition, so that the overlay is entirely visible in the current viewport. The default is false. + */ + autoPan?: boolean; + + /** + * The options used to create a ol.animation.pan animation. This animation is only used when autoPan is enabled. By default the default options for ol.animation.pan are used. If set to null the panning is not animated. + */ + autoPanAnimation?: olx.animation.PanOptions; + + /** + * The margin (in pixels) between the overlay and the borders of the map when autopanning. The default is 20. + */ + autoPanMargin?: number; + } + + interface ViewOptions { + + /** The initial center for the view. The coordinate system for the center is specified with the projection option. Default is undefined, and layer sources will not be fetched if this is not set. */ + center?: ol.Coordinate; + + /** Rotation constraint. false means no constraint. true means no constraint, but snap to zero near zero. A number constrains the rotation to that number of values. For example, 4 will constrain the rotation to 0, 90, 180, and 270 degrees. The default is true. */ + constrainRotation?: boolean; + + /** Enable rotation. Default is true. If false a rotation constraint that always sets the rotation to zero is used. The constrainRotation option has no effect if enableRotation is false. */ + enableRotation?: boolean; + + /**The extent that constrains the center, in other words, center cannot be set outside this extent. Default is undefined. */ + extent?: ol.Extent; + + /** The maximum resolution used to determine the resolution constraint. It is used together with minResolution (or maxZoom) and zoomFactor. If unspecified it is calculated in such a way that the projection's validity extent fits in a 256x256 px tile. If the projection is Spherical Mercator (the default) then maxResolution defaults to 40075016.68557849 / 256 = 156543.03392804097. */ + maxResolution?: number; + + /** The minimum resolution used to determine the resolution constraint. It is used together with maxResolution (or minZoom) and zoomFactor. If unspecified it is calculated assuming 29 zoom levels (with a factor of 2). If the projection is Spherical Mercator (the default) then minResolution defaults to 40075016.68557849 / 256 / Math.pow(2, 28) = 0.0005831682455839253. */ + minResolution?: number; + + /** The maximum zoom level used to determine the resolution constraint. It is used together with minZoom (or maxResolution) and zoomFactor. Default is 28. Note that if minResolution is also provided, it is given precedence over maxZoom. */ + maxZoom?: number; + + /** The minimum zoom level used to determine the resolution constraint. It is used together with maxZoom (or minResolution) and zoomFactor. Default is 0. Note that if maxResolution is also provided, it is given precedence over minZoom. */ + minZoom?: number; + + /** The projection. Default is EPSG:3857 (Spherical Mercator). */ + projection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** The initial resolution for the view. The units are projection units per pixel (e.g. meters per pixel). An alternative to setting this is to set zoom. Default is undefined, and layer sources will not be fetched if neither this nor zoom are defined. */ + resolution?: number; + + /** Resolutions to determine the resolution constraint. If set the maxResolution, minResolution, minZoom, maxZoom, and zoomFactor options are ignored. */ + resolutions?: Array; + + /** The initial rotation for the view in radians (positive rotation clockwise). Default is 0. */ + rotation?: number; + + /** Only used if resolution is not defined. Zoom level used to calculate the initial resolution for the view. The initial resolution is determined using the ol.View#constrainResolution method. */ + zoom?: number; + + /** The zoom factor used to determine the resolution constraint. Default is 2. */ + zoomFactor?: number; + } + + interface ViewState { + + /** + * + */ + center: ol.Coordinate; + + /** + * + */ + projection: ol.proj.Projection; + + /** + * + */ + resolution: number; + + /** + * + */ + rotation: number; + } + + interface Projection { + /** + * The SRS identifier code, e.g. EPSG:4326. + */ + code: string; + + /** + * Units. Required unless a proj4 projection is defined for code. + */ + units?: ol.proj.Units; + + /** + * The validity extent for the SRS. + */ + extent?: Array; + + /** + * The axis orientation as specified in Proj4. The default is enu. + */ + axisOrientation?: string; + + /** + * Whether the projection is valid for the whole globe. Default is false. + */ + global?: boolean; + + /** + * experimental The world extent for the SRS. + */ + worldExtent?: ol.Extent; + + /** + * experimental Function to determine resolution at a point. The function is called with + * a {number} view resolution and an {ol.Coordinate} as arguments, and returns the {number} + * resolution at the passed coordinate. + */ + getPointResolution?: (resolution: number, coordinate: ol.Coordinate) => number; + } + + namespace animation { + + interface BounceOptions { + + /** + * The resolution to start the bounce from, typically map.getView().getResolution(). + */ + resolution: number; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number; + } + + interface PanOptions { + + /** + * The resolution to start the bounce from, typically map.getView().getResolution(). + */ + source: ol.Coordinate; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number; + } + + interface RotateOptions { + + /** + * The rotation value (in radians) to begin rotating from, typically map.getView().getRotation(). If undefined then 0 is assumed. + */ + rotation?: number; + + /** + * The rotation center/anchor. The map rotates around the center of the view if unspecified. + */ + anchor?: ol.Coordinate; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number + } + + interface ZoomOptions { + + /** + * The resolution to begin zooming from, typically map.getView().getResolution(). + */ + resolution: number; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number + } + } + + namespace control { + + interface DefaultsOptions { + + /** + * Attribution. Default is true. + */ + attribution?: boolean; + + /** + * Attribution options. + */ + //TODO: Replace with olx.control.AttributionOptions + attributionOptions?: any; + + /** + * Rotate. Default is true; + */ + rotate?: boolean; + + /** + * Rotate options + */ + //TODO: Replace with olx.control.RotateOptions + rotateOptions?: any; + + /** + * Zoom. Default is true + */ + zoom?: boolean; + + /** + * + */ + //TODO: Replace with olx.control.ZoomOptions + zoomOptions?: any; + } + } + + namespace interaction { + interface DefaultsOptions { + /*** Whether Alt-Shift-drag rotate is desired. Default is true.*/ + altShiftDragRotate?: boolean; + /*** Whether double click zoom is desired. Default is true.*/ + doubleClickZoom?: boolean; + /*** Whether keyboard interaction is desired. Default is true.*/ + keyboard?: boolean; + /*** Whether mousewheel zoom is desired. Default is true.*/ + mouseWheelZoom?: boolean; + /*** Whether Shift-drag zoom is desired. Default is true.*/ + shiftDragZoom?: boolean; + /*** Whether drag pan is desired. Default is true.*/ + dragPan?: boolean; + /*** Whether pinch rotate is desired. Default is true.*/ + pinchRotate?: boolean; + /*** Whether pinch zoom is desired. Default is true.*/ + pinchZoom?: boolean; + /*** Zoom delta*/ + zoomDelta?: number; + /*** Zoom duration*/ + zoomDuration?: number; + } + interface InteractionOptions { + /** + * Method called by the map to notify the interaction that a browser event was dispatched to the map. + * The function may return false to prevent the propagation of the event to other interactions in + * the map's interactions chain. Required. + */ + handleEvent: Function; + } + interface ModifyOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event will + * be considered to add or move a vertex to the sketch. Default is ol.events.condition.primaryAction. + */ + condition?: ol.events.ConditionType; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should + * be handled. By default, ol.events.condition.singleClick with ol.events.condition.noModifierKeys results + * in a vertex deletion. + */ + deleteCondition?: ol.events.ConditionType; + /*** Pixel tolerance for considering the pointer close enough to a segment or vertex for editing. Default is 10.*/ + pixelTolerance?: number; + /*** Style used for the features being modified. By default the default edit style is used (see ol.style).*/ + style?: ol.style.Style | Array | ol.style.StyleFunction; + /*** The features the interaction works on. Required.*/ + features: ol.Collection; + /*** Wrap the world horizontally on the sketch overlay. Default is false.*/ + wrapX?: boolean; + } + interface DragBoxOptions { + /*** CSS class name for styling the box. The default is ol-dragbox.*/ + className?: string; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.always. + */ + condition?: ol.events.ConditionType; + /*** A function that takes a ol.MapBrowserEvent and two ol.Pixels to indicate whether a boxend event should be fired.*/ + boxEndCondition?: ol.interaction.DragBoxEndConditionType; + } + interface DrawOptions { + /** + * The maximum distance in pixels between "down" and "up" for a "up" event to be considered a "click" event and actually + * add a point/vertex to the geometry being drawn. Default is 6 pixels. That value was chosen for the draw interaction + * to behave correctly on mouse as well as on touch devices. + */ + clickTolerance?: number; + /** + * Destination collection for the drawn features. + */ + features?: ol.Collection; + /** + * Destination source for the drawn features. + */ + source?: ol.source.Vector; + /** + * Pixel distance for snapping to the drawing finish. Default is 12. + */ + snapTolerance?: number; + /** + * Drawing type ('Point', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon' or 'Circle'). Required. + */ + type: ol.geom.GeometryType; + /** + * The number of points that can be drawn before a polygon ring or line string is finished. The default is no restriction. + */ + maxPoints?: number; + /** + * The number of points that must be drawn before a polygon ring or line string can be finished. Default is 3 for polygon + * rings and 2 for line strings. + */ + minPoints?: number; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether the drawing can be finished. + */ + finishCondition?: ol.events.ConditionType; + /** + * Style for sketch features. + */ + style?: ol.style.Style | Array | ol.style.StyleFunction; + /** + * Function that is called when a geometry's coordinates are updated. + */ + geometryFunction?: ol.interaction.DrawGeometryFunctionType; + /** + * Geometry name to use for features created by the draw interaction. + */ + geometryName?: string; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * By default ol.events.condition.noModifierKeys, i.e. a click, adds a vertex or deactivates freehand drawing. + */ + condition?: ol.events.ConditionType; + /** + * Condition that activates freehand drawing for lines and polygons. This function takes an ol.MapBrowserEvent and returns + * a boolean to indicate whether that event should be handled. The default is ol.events.condition.shiftKeyOnly, meaning that + * the Shift key activates freehand drawing. + */ + freehandCondition?: ol.events.ConditionType; + /** + * Wrap the world horizontally on the sketch overlay. Default is false. + */ + wrapX?: boolean; + } + interface DoubleClickZoomOptions { + /** + * Animation duration in milliseconds. Default is 250. + */ + duration?: number; + /** + * The zoom delta applied on each double click, default is 1. + */ + delta?: number; + } + interface DragAndDropOptions { + /** + * Format constructors. + */ + formatConstructors?: Array; + /** + * Target projection. By default, the map's view's projection is used. + */ + projection: ol.proj.ProjectionLike; + /** + * The element that is used as the drop target, default is the viewport element. + */ + target?: Element; + } + interface DragPanOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.noModifierKeys. + */ + condition?: ol.events.ConditionType; + /** + * Kinetic inertia to apply to the pan. + */ + kinetic?: ol.Kinetic; + } + interface DragRotateOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.altShiftKeysOnly. + */ + condition?: ol.events.ConditionType; + /** + * Animation duration in milliseconds. Default is 250. + */ + duration?: number; + } + interface DragRotateAndZoomOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.shiftKeyOnly. + */ + condition?: ol.events.ConditionType; + /** + * Animation duration in milliseconds. Default is 400. + */ + duration?: number; + } + interface DragZoomOptions { + /** + * CSS class name for styling the box. The default is ol-dragzoom. + */ + className?: string; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.shiftKeyOnly. + */ + condition?: ol.events.ConditionType; + /** + * Animation duration in milliseconds. Default is 200. + */ + duration?: number; + /** + * Use interaction for zooming out. Default is false. + */ + out?: boolean; + } + interface KeyboardPanOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.noModifierKeys and ol.events.condition.targetNotEditable. + */ + condition?: ol.events.ConditionType; + /** + * Animation duration in milliseconds. Default is 100. + */ + duration?: number; + /** + * Pixel The amount to pan on each key press. Default is 128 pixels. + */ + pixelDelta?: number; + } + interface KeyboardZoomOptions { + /** + * Animation duration in milliseconds. Default is 100. + */ + duration?: number; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.targetNotEditable. + */ + condition?: ol.events.ConditionType; + /** + * The amount to zoom on each key press. Default is 1. + */ + delta?: number; + } + interface MouseWheelZoomOptions { + /** + * Animation duration in milliseconds. Default is 250. + */ + duration?: number; + /** + * Enable zooming using the mouse's location as the anchor. Default is true. + * When set to false, zooming in and out will zoom to the center of the screen instead of zooming on the mouse's location. + */ + useAnchor?: boolean; + } + interface PinchRotateOptions { + /** + * The duration of the animation in milliseconds. Default is 250. + */ + duration?: number; + /** + * Minimal angle in radians to start a rotation. Default is 0.3. + */ + threshold?: number; + } + interface PinchZoomOptions { + /** + * Animation duration in milliseconds. Default is 400. + */ + duration?: number; + } + interface PointerOptions { + /** + * Function handling "down" events. If the function returns true then a drag sequence is started. + */ + handleDownEvent?: Function; + /** + * Function handling "drag" events. This function is called on "move" events during a drag sequence. + */ + handleDragEvent?: Function; + /** + * Method called by the map to notify the interaction that a browser event was dispatched to the map. + * The function may return false to prevent the propagation of the event to other interactions in the map's interactions chain. + */ + handleEvent?: Function; + /** + * Function handling "move" events. This function is called on "move" events, also during a drag sequence + * (so during a drag sequence both the handleDragEvent function and this function are called). + */ + handleMoveEvent?: Function; + /** + * Function handling "up" events. If the function returns false then the current drag sequence is stopped. + */ + handleUpEvent?: Function; + } + interface SnapOptions { + /** + * Snap to these features. Either this option or source should be provided. + */ + features?: ol.Collection; + /** + * Snap to edges. Default is true. + */ + edge?: boolean; + /** + * Snap to vertices. Default is true. + */ + vertex?: boolean; + /** + * Pixel tolerance for considering the pointer close enough to a segment or vertex for snapping. Default is 10 pixels. + */ + pixelTolerance?: number; + /** + * Snap to features from this source. Either this option or features should be provided. + */ + source?: ol.source.Vector; + } + interface SelectOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * By default, this is ol.events.condition.never. + * Use this if you want to use different events for add and remove instead of toggle. + */ + addCondition?: ol.events.ConditionType; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * This is the event for the selected features as a whole. By default, this is ol.events.condition.singleClick. + * Clicking on a feature selects that feature and removes any that were in the selection. + * Clicking outside any feature removes all from the selection. + * See toggle, add, remove options for adding/removing extra features to/ from the selection. + */ + condition?: ol.events.ConditionType; + /** + * A list of layers from which features should be selected. Alternatively, a filter function can be provided. + * The function will be called for each layer in the map and should return true for layers that you want to be selectable. + * If the option is absent, all visible layers will be considered selectable. + */ + layers?: Array | ((layer: ol.layer.Layer) => boolean); + /** + * Style for the selected features. By default the default edit style is used (see ol.style). + */ + style?: ol.style.Style | Array | ol.style.StyleFunction; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * By default, this is ol.events.condition.never. + * Use this if you want to use different events for add and remove instead of toggle. + */ + removeCondition?: ol.events.ConditionType; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * This is in addition to the condition event. By default, ol.events.condition.shiftKeyOnly, + * i.e. pressing shift as well as the condition event, adds that feature to the current selection if it is not currently + * selected, and removes it if it is. See add and remove if you want to use different events instead of a toggle. + */ + toggleCondition?: ol.events.ConditionType; + /** + * A boolean that determines if the default behaviour should select only single features or all (overlapping) + * features at the clicked map position. Default is false i.e single select + */ + multi?: boolean; + /** + * Collection where the interaction will place selected features. Optional. If not set the interaction will create a collection. + * In any case the collection used by the interaction is returned by ol.interaction.Select#getFeatures. + */ + features?: ol.Collection; + /** + * A function that takes an ol.Feature and an ol.layer.Layer and returns true if the feature may be selected or false otherwise. + */ + filter?: ol.interaction.SelectFilterFunction; + /** + * Wrap the world horizontally on the selection overlay. Default is true. + */ + wrapX?: boolean; + } + } + + namespace layer { + + interface BaseOptions { + /** + * Opacity (0, 1). Default is 1. + */ + opacity?: number; + + /** + * Visibility. Default is true. + */ + visible?: boolean; + + /** + * The bounding extent for layer rendering. The layer will not be rendered outside of this extent. + */ + extent?: ol.Extent; + + zIndex?: number; + /** + * The minimum resolution (inclusive) at which this layer will be visible. + */ + minResolution?: number; + + /** + * The maximum resolution (exclusive) below which this layer will be visible. + */ + maxResolution?: number; + } + + interface GroupOptions extends BaseOptions { + + /** + * Child layers + */ + layers?: Array | ol.Collection; + } + + interface HeatmapOptions extends VectorOptions { + + /** + * The color gradient of the heatmap, specified as an array of CSS color strings. Default is ['#00f', '#0ff', '#0f0', '#ff0', '#f00']. + */ + gradient?: Array; + + /** + * Radius size in pixels. Default is 8. + */ + radius?: number; + + /** + * Blur size in pixels. Default is 15. + */ + blur?: number; + + /** + * Shadow size in pixels. Default is 250. + */ + shadow?: number; + } + + interface ImageOptions extends LayerOptions { + } + + interface LayerOptions extends BaseOptions { + + /** + * The layer source (or null if not yet set). + */ + source?: ol.source.Source; + } + + interface TileOptions extends LayerOptions { + + /** + * Preload. Load low-resolution tiles up to preload levels. By default preload is 0, which means no preloading. + */ + preload?: number; + + /** + * Source for this layer. + */ + source?: ol.source.Tile; + + /** + * Use interim tiles on error. Default is true. + */ + useInterimTilesOnError?: boolean; + } + + interface VectorOptions extends LayerOptions { + + /** + * When set to true, feature batches will be recreated during animations. This means that no vectors will be shown clipped, but the setting will have a performance impact for large amounts of vector data. When set to false, batches will be recreated when no animation is active. Default is false. + */ + updateWhileAnimating?: boolean; + + /** + * When set to true, feature batches will be recreated during interactions. See also updateWhileInteracting. Default is false. + */ + updateWhileInteracting?: boolean; + + /** + * Render order. Function to be used when sorting features before rendering. By default features are drawn in the order that they are created. Use null to avoid the sort, but get an undefined draw order. + */ + // TODO: replace any with the expected function, unclear in documentation what the parameters are + renderOrder?: any; + + /** + * The buffer around the viewport extent used by the renderer when getting features from the vector source for the rendering or hit-detection. Recommended value: the size of the largest symbol, line width or label. Default is 100 pixels. + */ + renderBuffer?: number; + + /** + * Source. + */ + source?: ol.source.Vector; + + /** + * Layer style. See ol.style for default style which will be used if this is not defined. + */ + style?: ol.style.Style | Array | any; + } + } + + namespace source { + + interface VectorOptions { + /** + * Attributions. + */ + attributions?: Array; + + /** + * Features. If provided as {@link ol.Collection}, the features in the source + * and the collection will stay in sync. + */ + features?: Array | ol.Collection; + + /** + * The feature format used by the XHR feature loader when `url` is set. + * Required if `url` is set, otherwise ignored. Default is `undefined`. + */ + format?: ol.format.Feature; + + /** + * The loader function used to load features, from a remote source for example. + * Note that the source will create and use an XHR feature loader when `url` is + * set. + */ + loader?: ol.FeatureLoader; + + /** + * Logo. + */ + logo?: string | olx.LogoOptions; + + /** + * The loading strategy to use. By default an {@link ol.loadingstrategy.all} + * strategy is used, a one-off strategy which loads all features at once. + */ + strategy?: ol.LoadingStrategy; + + /** + * Setting this option instructs the source to use an XHR loader (see + * {@link ol.featureloader.xhr}) and an {@link ol.loadingstrategy.all} for a + * one-off download of all features from that URL. + * Requires `format` to be set as well. + */ + url?: string; + + /** + * By default, an RTree is used as spatial index. When features are removed and + * added frequently, and the total number of features is low, setting this to + * `false` may improve performance. + */ + useSpatialIndex?: boolean; + + /** + * Wrap the world horizontally. Default is `true`. For vector editing across the + * -180° and 180° meridians to work properly, this should be set to `false`. The + * resulting geometry coordinates will then exceed the world bounds. + */ + wrapX?: boolean; + } + + interface ClusterOptions extends VectorOptions{ + + /** + * Minimum distance in pixels between clusters. Default is 20. + */ + distance?: number; + + extent?: ol.Extent; + + geometryFunction?: any; + + projection?: ol.proj.ProjectionLike; + + source: ol.source.Vector; + + } + + interface WMTSOptions { + attributions?: Array; + crossOrigin?: string; + logo?: string | olx.LogoOptions; + tileGrid: ol.tilegrid.WMTS; // REQUIRED ! + projection?: ol.proj.ProjectionLike; + reprojectionErrorThreshold?: number; + requestEncoding?: ol.source.WMTSRequestEncoding; + layer: string; //REQUIRED + style: string; //REQUIRED + tileClass?: Function; + tilePixelRatio?: number; + version?: string; + format?: string; + matrixSet: string; //REQUIRED + dimensions?: Object; + url?: string; + maxZoom?: number; + tileLoadFunction?: ol.TileLoadFunctionType; + urls?: Array; + wrapX: boolean; + } + } + + namespace style { + + interface FillOptions { + color?: ol.Color | string; + } + + interface StyleOptions { + geometry?: string | ol.geom.Geometry | ol.style.GeometryFunction; + fill?: ol.style.Fill; + image?: ol.style.Image; + stroke?: ol.style.Stroke; + text?: ol.style.Text; + zIndex?: number; + } + + interface TextOptions { + font?: string; + offsetX?: number; + offsetY?: number; + scale?: number; + rotation?: number; + text?: string; + textAlign?: string; + textBaseline?: string; + fill?: ol.style.Fill; + stroke?: ol.style.Stroke; + } + interface StrokeOptions { + color?: ol.Color | string; + lineCap?: string; + lineJoin?: string; + lineDash?: Array; + miterLimit?: number; + width?: number; + } + interface IconOptions { + anchor?: Array; + anchorOrigin?: string; + anchorXUnits?: string; + anchorYUnits?: string; + crossOrigin?: string; + img?: ol.Image | HTMLCanvasElement; + offset?: Array; + offsetOrigin?: string; + opacity?: number; + scale?: number; + snapToPixel?: boolean; + rotateWithView?: boolean; + rotation?: number; + size?: ol.Size; + imgSize?: ol.Size; + src?: string; + } + interface CircleOptions { + fill?: ol.style.Fill; + radius: number; + snapToPixel?: boolean; + stroke?: ol.style.Stroke; + } + } + + namespace tilegrid { + + interface TileGridOptions { + + /** + * Extent for the tile grid. No tiles outside this extent will be requested by ol.source.Tile sources. When no origin or origins are configured, the origin will be set to the bottom-left corner of the extent. When no sizes are configured, they will be calculated from the extent. + */ + extent?: ol.Extent; + + /** + * Minimum zoom. Default is 0. + */ + minZoom?: number; + + /** + * Origin, i.e. the bottom-left corner of the grid. Default is null. + */ + origin?: ol.Coordinate; + + /** + * Origins, i.e. the bottom-left corners of the grid for each zoom level. If given, the array length should match the length of the resolutions array, i.e. each resolution can have a different origin. + */ + origins?: Array; + + /** + * Resolutions. The array index of each resolution needs to match the zoom level. This means that even if a minZoom is configured, the resolutions array will have a length of maxZoom + 1. + */ + resolutions?: Array; + + /** + * Tile size. Default is [256, 256]. + */ + tileSize?: number | ol.Size; + + /** + * Tile sizes. If given, the array length should match the length of the resolutions array, i.e. each resolution can have a different tile size. + */ + tileSizes?: Array; + } + + interface WMTSOptions { + + /** + * Extent for the tile grid. No tiles outside this extent will be requested by ol.source.WMTS sources. When no origin or origins are configured, the origin will be calculated from the extent. When no sizes are configured, they will be calculated from the extent. + */ + extent?: ol.Extent; + + /** + * Origin, i.e. the top-left corner of the grid. + */ + origin?: ol.Coordinate; + + /** + * Origins, i.e. the top-left corners of the grid for each zoom level. The length of this array needs to match the length of the resolutions array. + */ + origins?: Array; + + /** + * Resolutions. The array index of each resolution needs to match the zoom level. This means that even if a minZoom is configured, the resolutions array will have a length of maxZoom + 1 + */ + resolutions?: Array; + + /** + * matrix IDs. The length of this array needs to match the length of the resolutions array. + */ + matrixIds?: Array; + + /** + * Number of tile rows and columns of the grid for each zoom level. The values here are the TileMatrixWidth and TileMatrixHeight advertised in the GetCapabilities response of the WMTS, and define the grid's extent together with the origin. An extent can be configured in addition, and will further limit the extent for which tile requests are made by sources. + */ + sizes?: Array; + + /** + * Tile size. + */ + tileSize?: number | ol.Size; + + /** + * Tile sizes. The length of this array needs to match the length of the resolutions array. + */ + tileSizes?: Array; + + /** + * Number of tile columns that cover the grid's extent for each zoom level. Only required when used with a source that has wrapX set to true, and only when the grid's origin differs from the one of the projection's extent. The array length has to match the length of the resolutions array, i.e. each resolution will have a matching entry here. + */ + widths?: Array; + } + + interface XYZOptions { + + /** + * Extent for the tile grid. The origin for an XYZ tile grid is the top-left corner of the extent. The zero level of the grid is defined by the resolution at which one tile fits in the provided extent. If not provided, the extent of the EPSG:3857 projection is used. + */ + extent?: ol.Extent; + + /** + * Maximum zoom. The default is ol.DEFAULT_MAX_ZOOM. This determines the number of levels in the grid set. For example, a maxZoom of 21 means there are 22 levels in the grid set. + */ + maxZoom?: number; + + /** + * Minimum zoom. Default is 0. + */ + minZoom?: number; + + /** + * Tile size in pixels. Default is [256, 256]. + */ + tileSize?: number | ol.Size; + } + + interface ZoomifyOptions { + + /** + * Resolutions + */ + resolutions: Array; + } + } + + namespace view { + + interface FitGeometryOptions { + + /** + * Padding (in pixels) to be cleared inside the view. Values in the array are top, right, bottom and left padding. Default is [0, 0, 0, 0]. + */ + padding?: Array; + + /** + * Constrain the resolution. Default is true. + */ + constrainResolution?: boolean; + + /** + * Get the nearest extent. Default is false. + */ + nearest?: boolean; + + /** + * Minimum resolution that we zoom to. Default is 0. + */ + minResolution?: number; + + /** + * Maximum zoom level that we zoom to. If minResolution is given, this property is ignored. + */ + maxZoom?: number; + } + } + + namespace format { + interface WKTOptions { + /** + * Whether to split GeometryCollections into multiple features on reading. Default is false. + */ + splitCollection?: boolean; + } + + interface GeoJSONOptions { + + /** + * Default data projection. + */ + defaultDataProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * Geometry name to use when creating features + */ + geometryName?: string; + } + + interface ReadOptions { + + /** + * Projection of the data we are reading. If not provided, the projection will be derived from the data (where possible) or the defaultDataProjection of the format is assigned (where set). If the projection can not be derived from the data and if no defaultDataProjection is set for a format, the features will not be reprojected. + */ + dataProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * Projection of the feature geometries created by the format reader. If not provided, features will be returned in the dataProjection. + */ + featureProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + } + + interface WriteOptions { + + /** + * Projection of the data we are writing. If not provided, the defaultDataProjection of the format is assigned (where set). If no defaultDataProjection is set for a format, the features will be returned in the featureProjection. + */ + dataProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * Projection of the feature geometries that will be serialized by the format writer. + */ + featureProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * When writing geometries, follow the right-hand rule for linear ring orientation. This means that polygons will have counter-clockwise exterior rings and clockwise interior rings. By default, coordinates are serialized as they are provided at construction. If true, the right-hand rule will be applied. If false, the left-hand rule will be applied (clockwise for exterior and counter-clockwise for interior rings). Note that not all formats support this. The GeoJSON format does use this property when writing geometries. + */ + rightHanded?: boolean; + } + } + + namespace control { + interface ControlOptions { + /** + * The element is the control's container element. This only needs to be specified if you're developing a custom control. + */ + element?: Element; + + /** + * Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback. + */ + render?: any; + + /** + * Specify a target if you want the control to be rendered outside of the map's viewport. + */ + target?: Element | string; + } + } +} + +/** + * A high-performance, feature-packed library for all your mapping needs. + */ +declare namespace ol { + + interface TileLoadFunctionType { (image: ol.Image, url: string): void } + + interface ImageLoadFunctionType { (image: ol.Image, url: string): void } + + type AttributionLike = string | Array | ol.Attribution | Array + + /** + * An attribution for a layer source. + */ + class Attribution { + /** + * @constructor + * @param options Attribution options. + */ + constructor(options: olx.AttributionOptions); + + /** + * Get the attribution markup. + * @returns The attribution HTML. + */ + getHTML(): string; + } + + /** + * An expanded version of standard JS Array, adding convenience methods for manipulation. Add and remove changes to the Collection trigger a Collection event. Note that this does not cover changes to the objects within the Collection; they trigger events on the appropriate object, not on the Collection as a whole. + */ + class Collection extends ol.Object { + + /** + * @constructor + * @param values Array. + */ + constructor(values: Array) + + /** + * Remove all elements from the collection. + */ + clear(): void; + + /** + * Add elements to the collection. This pushes each item in the provided array to the end of the collection. + * @param arr Array. + * @returns This collection. + */ + extend(arr: Array): Collection; + + /** + * Iterate over each element, calling the provided callback. + * @param f The function to call for every element. This function takes 3 arguments (the element, the index and the array). + * @param ref The object to use as this in f. + */ + forEach(f: (element: T, index: number, array: Array) => void, ref?: any): void; + + /** + * Get a reference to the underlying Array object. Warning: if the array is mutated, no events will be dispatched by the collection, and the collection's "length" property won't be in sync with the actual length of the array. + * @returns Array. + */ + getArray(): Array; + + /** + * Get the length of this collection. + * @returns The length of the array. + */ + getLength(): number; + + /** + * Insert an element at the provided index. + * @param index Index. + * @param elem Element. + */ + insertAt(index: number, elem: T): void; + + /** + * Get the element at the provided index. + * @param index Index. + * @returns Element. + */ + item(index: number): T; + + /** + * Remove the last element of the collection and return it. Return undefined if the collection is empty. + * @returns Element + */ + pop(): T; + + /** + * Insert the provided element at the end of the collection. + * @param Element. + * @returns Length. + */ + push(elem: T): number; + + /** + * Remove the first occurrence of an element from the collection. + * @param elem Element. + * @returns The removed element or undefined if none found. + */ + remove(elem: T): T; + + /** + * Remove the element at the provided index and return it. Return undefined if the collection does not contain this index. + * @param index Index. + * @returns Value. + */ + removeAt(index: number): T; + + /** + * Set the element at the provided index. + * @param index Index. + * @param elem Element. + */ + setAt(index: number, elem: T): void; + } + + /** + * Events emitted by ol.Collection instances are instances of this type. + */ + class CollectionEvent extends ol.events.Event { + + /** + * The element that is added to or removed from the collection. + */ + element: T; + } + + /** + * The ol.DeviceOrientation class provides access to information from DeviceOrientation events. + */ + class DeviceOrientation extends ol.Object { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.DeviceOrientationOptions); + + /** + * Rotation around the device z-axis (in radians). + * @returns The euler angle in radians of the device from the standard Z axis. + */ + getAlpha(): number; + + /** + * Rotation around the device x-axis (in radians). + * @returns The euler angle in radians of the device from the planar X axis. + */ + getBeta(): number; + + /** + * Rotation around the device y-axis (in radians). + * @returns The euler angle in radians of the device from the planar Y axis. + */ + getGamma(): number; + + /** + * The heading of the device relative to north (in radians). + * @returns The heading of the device relative to north, in radians, normalizing for different browser behavior. + */ + getHeading(): number; + + /** + * Determine if orientation is being tracked. + * @returns Changes in device orientation are being tracked. + */ + getTracking(): boolean; + + /** + * Enable or disable tracking of device orientation events. + * @param tracking The status of tracking changes to alpha, beta and gamma. If true, changes are tracked and reported immediately. + */ + setTracking(tracking: boolean): void; + } + + /** + * Events emitted by ol.interaction.DragBox instances are instances of this type. + */ + class DragBoxEvent extends ol.events.Event { + + /** + * The coordinate of the drag event. + */ + coordinate: ol.Coordinate; + } + + /** + * A vector object for geographic features with a geometry and other attribute properties, similar to the features in vector file formats like GeoJSON. + */ + class Feature extends ol.Object { + + /** + * @constructor + * @param geometry Geometry. + */ + // TODO: replace any with Object + constructor(geometryOrProperties?: ol.geom.Geometry | any); + + /** + * Clone this feature. If the original feature has a geometry it is also cloned. The feature id is not set in the clone. + * @returns The clone. + */ + clone(): Feature; + + /** + * Get the feature's default geometry. A feature may have any number of named geometries. The "default" geometry (the one that is rendered by default) is set when calling ol.Feature#setGeometry. + * @returns The default geometry for the feature. + */ + getGeometry(): ol.geom.Geometry; + + /** + * Get the name of the feature's default geometry. By default, the default geometry is named geometry. + * @returns Get the property name associated with the default geometry for this feature. + */ + getGeometryName(): string; + + /** + * @returns Id. + */ + getId(): string | number; + + /** + * Get the feature's style. This return for this method depends on what was provided to the ol.Feature#setStyle method. + * The feature style. + */ + getStyle(): ol.style.Style | Array | ol.FeatureStyleFunction; + + /** + * Get the feature's style function. + * @returns Return a function representing the current style of this feature. + */ + getStyleFunction(): ol.FeatureStyleFunction; + + /** + * Set the default geometry for the feature. This will update the property with the name returned by ol.Feature#getGeometryName. + * @param geometry The new geometry. + */ + setGeometry(geometry: ol.geom.Geometry): void; + + /** + * Set the property name to be used when getting the feature's default geometry. When calling ol.Feature#getGeometry, the value of the property with this name will be returned. + * @param name The property name of the default geometry. + */ + setGeometryName(name: string): void; + + /** + * Set the feature id. The feature id is considered stable and may be used when requesting features or comparing identifiers returned from a remote source. The feature id can be used with the ol.source.Vector#getFeatureById method. + * @param id The feature id. + */ + setId(id: string | number): void; + + /** + * Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a resolution and returns an array of styles. If it is null the feature has no style (a null style). + * @param style Style for this feature. + */ + setStyle(style: ol.style.Style): void; + + /** + * Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a resolution and returns an array of styles. If it is null the feature has no style (a null style). + * @param style Style for this feature. + */ + setStyle(style: Array): void; + + /** + * Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a resolution and returns an array of styles. If it is null the feature has no style (a null style). + * @param style Style for this feature. + */ + setStyle(style: ol.FeatureStyleFunction): void; + } + + /** + * A mechanism for changing the style of a small number of features on a temporary basis, for example highlighting. + */ + class FeatureOverlay { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.FeatureOverlayOptions); + + /** + * Add a feature to the overlay. + * @param feature Feature. + */ + addFeature(feature: ol.Feature): void; + + /** + * Get the features on the overlay. + * @returns Features collection. + */ + getFeatures: ol.Collection; + + /** + * Get the map associated with the overlay. + * @returns The map with which this feature overlay is associated. + */ + getMap(): ol.Map; + + /** + * Get the style for features. This returns whatever was passed to the style option at construction or to the setStyle method. + * @returns Overlay style. + */ + getStyle(): ol.style.Style | Array | ol.style.StyleFunction; + + /** + * Get the style function + * @returns Style function + */ + getStyleFunction(): ol.style.StyleFunction; + + /** + * Remove a feature from the overlay. + * @param feature The feature to be removed. + */ + removeFeature(feature: ol.Feature): void; + + /** + * Set the features for the overlay. + * @param features Features collection. + */ + setFeatures(features: ol.Collection): void; + + /** + * Set the map for the overlay. + * @param map Map. + */ + setMap(map: ol.Map): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. + * @param style Overlay style + */ + setStyle(style: ol.style.Style): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. + * @param style Overlay style + */ + setStyle(style: Array): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. + * @param style Overlay style + */ + setStyle(style: ol.style.StyleFunction): void; + } + + /** + * Helper class for providing HTML5 Geolocation capabilities. The Geolocation API is used to locate a user's position. + */ + class Geolocation extends ol.Object { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.GeolocationOptions); + + /** + * Get the accuracy of the position in meters. + * @returns The accuracy of the position measurement in meters. + */ + getAccuracy(): number; + + /** + * Get a geometry of the position accuracy. + * @returns A geometry of the position accuracy. + */ + getAccuracyGeometry(): ol.geom.Geometry; + + /** + * Get the altitude associated with the position. + * @returns The altitude of the position in meters above mean sea level. + */ + getAltitude(): number; + + /** + * Get the altitude accuracy of the position. + * @returns The accuracy of the altitude measurement in meters. + */ + getAltitudeAccuracy(): number; + + /** + * Get the heading as radians clockwise from North. + * @returns The heading of the device in radians from north. + */ + getHeading(): number; + + /** + * Get the position of the device. + * @returns The current position of the device reported in the current projection. + */ + getPosition(): ol.Coordinate; + + /** + * Get the projection associated with the position. + * @returns The projection the position is reported in. + */ + getProjection(): ol.proj.Projection; + + /** + * Get the speed in meters per second. + * @returns The instantaneous speed of the device in meters per second. + */ + getSpeed(): number; + + /** + * Determine if the device location is being tracked. + * @returns The device location is being tracked. + */ + getTracking(): boolean; + + /** + * Get the tracking options. + * @returns PositionOptions as defined by the HTML5 Geolocation spec. + */ + getTrackingOptions(): PositionOptions; + + /** + * Set the projection to use for transforming the coordinates. + * @param projection The projection the position is reported in. + */ + setProjection(projection: ol.proj.Projection): void; + + /** + * Enable or disable tracking. + * @param tracking Enable tracking + */ + setTracking(tracking: boolean): void; + + /** + * Set the tracking options. + * @param PositionOptions as defined by the HTML5 Geolocation spec. + */ + setTrackingOptions(options: PositionOptions): void; + } + + /** + * Render a grid for a coordinate system on a map. + */ + class Graticule { + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.GraticuleOptions); + + /** + * Get the map associated with this graticule. + * @returns The map. + */ + getMap(): Map; + + /** + * Get the list of meridians. Meridians are lines of equal longitude. + * @returns The meridians. + */ + getMeridians(): Array; + + /** + * Get the list of parallels. Pallels are lines of equal latitude. + * @returns The parallels. + */ + getParallels(): Array; + + /** + * Set the map for this graticule.The graticule will be rendered on the provided map. + * @param map Map + */ + setMap(map: Map): void; + } + + /** + * + */ + class Image extends ol.ImageBase { + + /** + * Get the HTML image element (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLCanvasElement): Image; + + /** + * Get the HTML image element (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLImageElement): Image; + + /** + * Get the HTML image element (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLVideoElement): Image; + } + + /** + * + */ + class ImageBase { + } + + /** + * + */ + class ImageTile extends ol.Tile { + + /** + * Get the HTML image element for this tile (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLCanvasElement): Image; + + /** + * Get the HTML image element for this tile (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLImageElement): Image; + + /** + * Get the HTML image element for this tile (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLVideoElement): Image; + + } + + /** + * Implementation of inertial deceleration for map movement. + */ + class Kinetic { + + /** + * @constructor + * @param decay Rate of decay (must be negative). + * @param Minimum velocity (pixels/millisecond). + * @param Delay to consider to calculate the kinetic initial values (milliseconds). + */ + constructor(decay: number, minVelocity: number, delay: number); + } + + /** + * The map is the core component of OpenLayers. For a map to render, a view, one or more layers, and a target container are needed. + */ + class Map extends ol.Object { + + /** + * @constructor + * @params options Options. + */ + constructor(options: olx.MapOptions); + + /** + * Add the given control to the map. + * @param control Control. + */ + addControl(control: ol.control.Control): void; + + /** + * Add the given interaction to the map. + * @param interaction Interaction to add. + */ + addInteraction(interaction: ol.interaction.Interaction): void; + + /** + * Adds the given layer to the top of this map. If you want to add a layer elsewhere in the stack, use getLayers() and the methods available on ol.Collection. + * @param Layer. + */ + addLayer(layer: ol.layer.Base): void; + + /** + * Add the given overlay to the map. + * @param overlay Overlay. + */ + addOverlay(overlay: ol.Overlay): void; + + /** + * Add functions to be called before rendering. This can be used for attaching animations before updating the map's view. The ol.animation namespace provides several static methods for creating prerender functions. + * @param var_args Any number of pre-render functions. + */ + beforeRender(var_args: ol.PreRenderFunction): void; + + /** + * Detect features that intersect a pixel on the viewport, and execute a callback with each intersecting feature. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. + * @param pixel Pixel. + * @param callback Feature callback. The callback will be called with two arguments. The first argument is one feature at the pixel, the second is the layer of the feature. If the detected feature is not on a layer, but on a ol.FeatureOverlay, then the second argument to this function will be null. To stop detection, callback functions can return a truthy value. + * @param ref Value to use as this when executing callback. + * @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested. + * @param ref2 Value to use as this when executing layerFilter. + * @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value. + */ + forEachFeatureAtPixel(pixel: ol.Pixel, callback: (feature: ol.Feature, layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): void; + + /** + * Detect layers that have a color value at a pixel on the viewport, and execute a callback with each matching layer. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. + * @param pixel Pixel. + * @param callback Layer callback. Will receive one argument, the layer that contains the color pixel. If the detected color value is not from a layer, but from a ol.FeatureOverlay, then the argument to this function will be null. To stop detection, callback functions can return a truthy value. + * @param ref Value to use as this when executing callback. + * @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested. + * @param ref2 Value to use as this when executing layerFilter. + * @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value. + */ + forEachLayerAtPixel(pixel: ol.Pixel, callback: (layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): void; + + /** + * Get the map controls. Modifying this collection changes the controls associated with the map. + * @returns Controls. + */ + getControls(): ol.Collection; + + /** + * Get the coordinate for a given pixel. This returns a coordinate in the map view projection. + * @param pixel Pixel position in the map viewport. + * @returns The coordinate for the pixel position. + */ + getCoordinateFromPixel(pixel: ol.Pixel): ol.Coordinate; + + /** + * Returns the geographical coordinate for a browser event. + * @param event Event. + * @returns Coordinate. + */ + getEventCoordinate(event: Event): ol.Coordinate; + + /** + * Returns the map pixel position for a browser event relative to the viewport. + * @param event Event. + * @returns Pixel. + */ + getEventPixel(event: Event): ol.Pixel; + + /** + * Get the map interactions. Modifying this collection changes the interactions associated with the map. + * @returns Interactions + */ + getInteractions(): ol.Collection; + + /** + * Get the layergroup associated with this map. + * @returns A layer group containing the layers in this map. + */ + getLayerGroup(): ol.layer.Group; + + /** + * Get the collection of layers associated with this map. + * @returns Layers. + */ + getLayers(): ol.Collection; + + /** + * Get the map overlays. Modifying this collection changes the overlays associated with the map. + * @returns Overlays. + */ + getOverlays(): ol.Collection; + + /** + * Get the pixel for a coordinate. This takes a coordinate in the map view projection and returns the corresponding pixel. + * @param coordinate A map coordinate. + * @returns A pixel position in the map viewport. + */ + getPixelFromCoordinate(coordinate: ol.Coordinate): ol.Pixel; + + /** + * Get the size of this map. + * @returns The size in pixels of the map in the DOM. + */ + getSize(): ol.Size; + + /** + * Get the target in which this map is rendered. Note that this returns what is entered as an option or in setTarget: if that was an element, it returns an element; if a string, it returns that. + * @returns The Element or id of the Element that the map is rendered in. + */ + getTarget(): Element | string; + + /** + * Get the DOM element into which this map is rendered. In contrast to getTarget this method always return an Element, or null if the map has no target. + * @returns The element that the map is rendered in. + */ + getTargetElement(): Element; + + /** + * Get the view associated with this map. A view manages properties such as center and resolution. + * @returns The view that controls this map. + */ + getView(): View; + + /** + * Get the element that serves as the map viewport. + * @returns Viewport. + */ + getViewport(): Element; + + /** + * Detect if features intersect a pixel on the viewport. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. + * @param pixel Pixel. + * @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested. + * @param ref Value to use as this when executing layerFilter. + * @returns Is there a feature at the given pixel? + */ + hasFeatureAtPixel(pixel: ol.Pixel, layerFilter?: (layer: ol.layer.Layer) => boolean, ref?: any): boolean; + + /** + * Remove the given control from the map. + * @param Control. + * @returns The removed control (or undefined if the control was not found). + */ + removeControl(control: ol.control.Control): ol.control.Control; + + /** + * Remove the given interaction from the map. + * @param interaction Interaction to remove. + * @returns The removed interaction (or undefined if the interaction was not found). + */ + removeInteraction(interaction: ol.interaction.Interaction): ol.interaction.Interaction; + + /** + * Removes the given layer from the map. + * @param Layer. + * @returns The removed layer (or undefined if the layer was not found). + */ + removeLayer(layer: ol.layer.Base): ol.layer.Base; + + /** + * Remove the given overlay from the map. + * @param Overlay. + * @returns The removed overlay (or undefined if the overlay was not found). + */ + removeOverlay(overlay: ol.Overlay): ol.Overlay; + + /** + * Request a map rendering (at the next animation frame). + */ + render(): void; + + /** + * Requests an immediate render in a synchronous manner. + */ + renderSync(): void; + + /** + * Sets the layergroup of this map. + * @param layerGroup A layer group containing the layers in this map. + */ + setLayerGroup(layerGroup: ol.layer.Group): void; + + /** + * Set the size of this map. + * @param size The size in pixels of the map in the DOM. + */ + setSize(size: ol.Size): void; + + /** + * Set the target element to render this map into. + * @param target The Element that the map is rendered in. + */ + setTarget(target: Element): void; + + /** + * Set the target element to render this map into. + * @param target The id of the element that the map is rendered in. + */ + setTarget(target: string): void; + + /** + * Set the view for this map. + * @param view The view that controls this map. + */ + setView(view: View): void; + + /** + * Force a recalculation of the map viewport size. This should be called when third-party code changes the size of the map viewport. + * */ + updateSize(): void; + } + + /** + * Events emitted as map browser events are instances of this type. See ol.Map for which events trigger a map browser event. + */ + class MapBrowserEvent extends MapEvent { + + /** + * The coordinate of the original browser event + */ + coordinate: Coordinate; + + /** + * Indicates if the map is currently being dragged. Only set for POINTERDRAG and POINTERMOVE events. Default is false. + */ + dragging: boolean; + + /** + * The frame state at the time of the event + */ + frameState: olx.FrameState; + + /** + * The map where the event occured + */ + map: Map; + + /** + * The original browser event + */ + originalEvent: Event; + + /** + * The pixel of the original browser event. + */ + pixel: Pixel; + + + // Methods + + /** + * Prevents the default browser action. + */ + preventDefault(): void; + + /** + * Prevents further propagation of the current event. + */ + stopPropagation(): void; + } + + /** + * Events emitted as map events are instances of this type. See ol.Map for which events trigger a map event. + */ + class MapEvent extends ol.events.Event { + + /** + * The frame state at the time of the event. + */ + frameState: olx.FrameState; + + /** + * The map where the event occurred. + */ + map: Map; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. Most non-trivial classes inherit from this. + */ + class Object extends Observable { + + /** + * @constructor + * @param values An object with key-value pairs. + */ + constructor(values?: Object); + + /** + * Gets a value. + * @param key Key name. + * @returns Value. + */ + get(key: string): any; + + /** + * Get a list of object property names. + * @returns List of property names. + */ + getKeys(): Array; + + /** + * Get an object of all property names and values. + * @returns Object. + */ + getProperties(): Object; + + /** + * @returns Revision. + */ + getRevision(): number; + + /** + * Sets a value. + * @param key Key name. + * @param value Value. + */ + set(key: string, value: any): void; + + /** + * Sets a collection of key-value pairs. Note that this changes any existing properties and adds new ones (it does not remove any existing properties). + * @param Values. + */ + setProperties(values: Object): void; + + /** + * Unsets a property. + */ + unset(key: string): void; + } + + /** + * Events emitted by ol.Object instances are instances of this type. + */ + class ObjectEvent extends ol.events.Event { + + /** + * The name of the property whose value is changing. + */ + key: string; + + /** + * The old value. To get the new value use e.target.get(e.key) where e is the event object. + */ + oldValue: any; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. An event target providing convenient methods for listener registration and unregistration. A generic change event is always available through ol.Observable#changed. + */ + class Observable { + + /** + * Removes an event listener using the key returned by on() or once(). + */ + unByKey(key: any): void; + + /** + * Increases the revision counter and dispatches a 'change' event. + */ + changed(): void; + + /** + * @returns Revision. + */ + getRevision(): number; + + /** + * Listen for a certain type of event. + * @param type The event type. + * @param listener The listener function. + * @param ref The object to use as this in listener. + * @returns Unique key for the listener. + */ + on(type: string, listener: (event: ol.events.Event) => void, ref?: any): any; + + /** + * Listen for a certain type of event. + * @param type The array of event types. + * @param listener The listener function. + * @param ref The object to use as this in listener. + * @returns Unique key for the listener. + */ + on(type: Array, listener: (event: ol.events.Event) => void, ref?: any): any; + + /** + * Listen once for a certain type of event. + * @param type The event type. + * @param listener The listener function. + * @param ref The object to use as this in listener. + * @returns Unique key for the listener. + */ + once(type: string, listener: (event: ol.events.Event) => void, ref?: any): any; + + /** + * Listen once for a certain type of event. + * @param type The array of event types. + * @param listener The listener function. + * @param ref The object to use as this in listener. + * @returns Unique key for the listener. + */ + once(type: Array, listener: (event: ol.events.Event) => void, ref?: any): any; + + /** + * Unlisten for a certain type of event. + * @param type The array of event types. + * @param listener The listener function. + * @param ref The object to use as this in listener. + * @returns Unique key for the listener. + */ + un(type: Array, listener: (event: ol.events.Event) => void, ref?: any): any; + + /** + * Removes an event listener using the key returned by on() or once(). Note that using the ol.Observable.unByKey static function is to be preferred. + * @param key The key returned by on() or once() + */ + unByKey(key: any): void; + } + + /** + * An element to be displayed over the map and attached to a single map location. + */ + class Overlay extends ol.Object { + + /** + * @constructor + * @param options Overlay options. + */ + constructor(options: olx.OverlayOptions); + + /** + * Get the DOM element of this overlay. + * @returns The Element containing the overlay. + */ + getElement(): Element; + + /** + * Get the map associated with this overlay. + * @returns The map that the overlay is part of. + */ + getMap(): ol.Map; + + /** + * Get the offset of this overlay. + * @returns The offset. + */ + getOffset(): Array; + + /** + * Get the current position of this overlay. + * @returns The spatial point that the overlay is anchored at. + */ + getPosition(): ol.Coordinate; + + /** + * Get the current positioning of this overlay. + * @returns How the overlay is positioned relative to its point on the map. + */ + getPositioning(): ol.OverlayPositioning; + + /** + * Set the DOM element to be associated with this overlay. + * @param element The element containing the overlay. + */ + setElement(element: Element): void; + + /** + * Set the map to be associated with this overlay. + * @param map The map that the overlay is part of. + */ + setMap(map: Map): void; + + /** + * Set the offset for this overlay. + * @param offset Offset. + */ + setOffset(offset: Array): void; + + /** + * Set the position for this overlay. If the position is undefined the overlay is hidden. + * @param position The spatial point that the overlay is anchored at. + */ + setPosition(position: ol.Coordinate): void; + + /** + * Set the positioning for this overlay. + * @param How the overlay is positioned relative to its point on the map. + */ + setPositioning(positioning: ol.OverlayPositioning): void; + } + + /** + * Events emitted by ol.interaction.Select instances are instances of this type. + */ + class SelectEvent extends ol.events.Event { + + /** + * Deselected features array. + */ + deselected: Array; + + /** + * Associated ol.MapBrowserEvent; + */ + mapBrowserEvent: ol.MapBrowserEvent; + + /** + * Selected features array. + */ + selected: Array + } + + /** + * Class to create objects that can be used with ol.geom.Polygon.circular. + */ + class Sphere { + + /** + * @constructor + * @param radius Radius. + */ + constructor(radius: number); + + /** + * Returns the geodesic area for a list of coordinates. + * @param coordinates List of coordinates of a linear ring. If the ring is oriented clockwise, the area will be positive, otherwise it will be negative. + * @returns Area. + */ + geodesicArea(coordinates: Array): number; + + /** + * Returns the distance from c1 to c2 using the haversine formula. + * @param c1 Coordinate 1. + * @param c2 Coordinate 2. + * @returns Haversine distance. + */ + haversineDistance(c1: ol.Coordinate, c2: ol.Coordinate): number; + } + + /** + * Base class for tiles. + */ + class Tile { + + /** + * Get the tile coordinate for this tile. + * @returns TileCoord. + */ + getTileCoord(): ol.TileCoord; + } + + /** + * An ol.View object represents a simple 2D view of the map. + */ + class View extends ol.Object { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.ViewOptions); + + /** + * Calculate the extent for the current view state and the passed size. The size is the pixel dimensions of the box into which the calculated extent should fit. In most cases you want to get the extent of the entire map, that is map.getSize(). + * @param size Box pixel size + * @returns Extent. + */ + calculateExtent(size: ol.Size): ol.Extent; + + /** + * Center on coordinate and view position. + * @param coordinate Coordinate. + * @param size Box pixel size + * @param position Position on the view to center on + */ + centerOn(coordinate: ol.Coordinate, size: ol.Size, position: ol.Pixel): void; + + /** + * Get the constrained center of this view. + * @param center Center. + * @returns Constrained center. + */ + constrainCenter(center: ol.Coordinate): ol.Coordinate; + + /** + * Get the constrained resolution of this view. + * @param resolution: Resolution. + * @param delta Delta. Default is 0. + * @param direction Direction. Default is 0. + * @returns Constrained resolution + */ + constrainResolution(resolution: number, delta?: number, direction?: number): number; + + /** + * Fit the map view to the passed extent and size. The size is pixel dimensions of the box to fit the extent into. In most cases you will want to use the map size, that is map.getSize(). + * @param extent Extent. + * @param size Box pixel size. + * @param options Options + */ + fit(geometry: ol.geom.SimpleGeometry | ol.Extent, size: ol.Size, opt_options?: olx.view.FitGeometryOptions): void; + + /** + * Get the view center. + * @returns The center of the view. + */ + getCenter(): ol.Coordinate; + + /** + * Get the view projection + * @returns The projection of the view. + */ + getProjection(): ol.proj.Projection; + + /** + * Get the view resolution + * @returns The resolution of the view. + */ + getResolution(): number; + + /** + * Get the view rotation + * @returns The rotation of the view in radians + */ + getRotation(): number; + + /** + * Get the current zoom level. Return undefined if the current resolution is undefined or not a "constrained resolution". + * @returns Zoom. + */ + getZoom(): number; + + /** + * Rotate the view around a given coordinate. + * @param rotation New rotation value for the view. + * @param anchor The rotation center. + */ + rotate(rotation: number, anchor: ol.Coordinate): void; + + /** + * Set the center of the current view. + * @param center The center of the view. + */ + setCenter(center: ol.Coordinate): void; + + /** + * Set the resolution for this view. + * @param resolution The resolution of the view. + */ + setResolution(resolution: number): void; + + /** + * Set the rotation for this view. + * @param rotation The rotation of the view in radians. + */ + setRotation(rotation: number): void; + + /** + * Zoom to a specific zoom level. + * @param zoom Zoom level. + */ + setZoom(zoom: number): void; + } + + // NAMESPACES + + /** + * The animation static methods are designed to be used with the ol.Map#beforeRender method. + */ + namespace animation { + + /** + * Generate an animated transition that will "bounce" the resolution as it approaches the final value. + * @param options Bounce options. + */ + function bounce(options: olx.animation.BounceOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view center. + * @param options Pan options. + */ + function pan(options: olx.animation.PanOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view rotation. + * @param options Rotate options. + */ + function rotate(options: olx.animation.RotateOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view resolution. + * @param options Zoom options. + */ + function zoom(options: olx.animation.ZoomOptions): ol.PreRenderFunction; + } + + /** + * Return the color as an array. This function maintains a cache of calculated arrays which means the result should not be modified. + */ + namespace color { + + /** + * Return the color as an array. This function maintains a cache of calculated arrays which means the result should not be modified. + * @param color Color. + */ + function asArray(color: ol.Color): ol.Color; + + /** + * Return the color as an array. This function maintains a cache of calculated arrays which means the result should not be modified. + * @param color Color. + */ + function asArray(color: string): ol.Color; + + /** + * Return the color as an rgba string. + * @param color Color. + */ + function asString(color: ol.Color): string; + + /** + * Return the color as an rgba string. + * @param color Color. + */ + function asString(color: string): string; + } + + namespace control { + + /** + * Set of controls included in maps by default. Unless configured otherwise, this returns a collection containing an instance of each of the following controls: ol.control.Zoom, ol.control.Rotate, ol.control.Attribution + * @param options Defaults options + * @returns Control.s + */ + function defaults(options?: olx.control.DefaultsOptions): ol.Collection; + + namespace ScaleLine { + + /** + * Units for the scale line. Supported values are 'degrees', 'imperial', 'nautical', 'metric', 'us'. + */ + type Units = 'degrees' | 'imperial' | 'nautical' | 'metric' | 'us'; + } + + class Control extends ol.Object{ + constructor(options: olx.control.ControlOptions); + + /** + * Get the map associated with this control. + */ + getMap():ol.Map; + + /** + * Remove the control from its current map and attach it to the new map. + * Subclasses may set up event handlers to get notified about changes to the map here. + */ + setMap(map: ol.Map):void; + + /** + * This function is used to set a target element for the control. + * It has no effect if it is called after the control has been added to the map (i.e. after setMap is called on the control). + * If no target is set in the options passed to the control constructor and if setTarget is not called then the control is + * added to the map's overlay container. + */ + setTarget(target: Element | string):void; + + + } + + class Attribution extends Control { + } + + class FullScreen extends Control { + } + + class MousePosition extends Control { + } + + class OverviewMap extends Control { + constructor(options?: olx.OverviewMapOptions); + + /** + * Update the overview map element. + * @param mapEvent + */ + render(mapEvent: ol.MapEvent): void; + + /** + * Determine if the overview map is collapsed. + */ + getCollapsed(): boolean; + + /** + * Return true if the overview map is collapsible, false otherwise. + */ + getCollapsible(): boolean; + + /** + * Return the overview map. + */ + getOverviewMap(): ol.Map; + + /** + * Collapse or expand the overview map according to the passed parameter. Will not do anything if the overview map isn't collapsible or if the current collapsed state is already the one requested. + * @param collapsed + */ + setCollapsed(collapsed: boolean): void; + + /** + * Set whether the overview map should be collapsible. + * @param collapsible + */ + setCollapsible(collapsible: boolean): void; + } + + class Rotate extends Control { + constructor(opt_options?: olx.RotateOptions); + } + + class ScaleLine extends Control { + + /** + * Return the units to use in the scale line. + */ + getUnits(): ScaleLine.Units; + + /** + * Set the units to use in the scale line. + */ + setUnits(units: ScaleLine.Units): void; + + } + + class Zoom extends Control{ + } + + class ZoomSlider extends Control{ + } + + class ZoomToExtent extends Control{ + constructor(options?: olx.ZoomToExtentOptions); + } + } + + namespace coordinate { + + /** + * Add delta to coordinate. coordinate is modified in place and returned by the function. + * @param coordinate Coordinate + * @param delta Delta + * @returns The input coordinate adjusted by the given delta. + */ + function add(coordinate: ol.Coordinate, delta: ol.Coordinate): ol.Coordinate; + + /** + * Returns a ol.CoordinateFormatType function that can be used to format a {ol.Coordinate} to a string. + * @param fractionDigits The number of digits to include after the decimal point. Default is 0. + * @returns Coordinate format + */ + function createStringXY(fractionDigits?: number): ol.CoordinateFormatType; + + /** + * Transforms the given ol.Coordinate to a string using the given string template. The strings {x} and {y} in the template will be replaced with the first and second coordinate values respectively. + * @param coordinate Coordinate + * @param template A template string with {x} and {y} placeholders that will be replaced by first and second coordinate values. + * @param fractionDigits The number of digits to include after the decimal point. Default is 0. + * @returns Formatted coordinate + */ + function format(coordinate: ol.Coordinate, template: string, fractionDigits?: number): string; + + /** + * Rotate coordinate by angle. coordinate is modified in place and returned by the function. + * @param coordinate Coordinate + * @param angle Angle in radian + * @returns Coordinatee + */ + function rotate(coordinate: ol.Coordinate, angle: number): ol.Coordinate; + + /** + * Format a geographic coordinate with the hemisphere, degrees, minutes, and seconds. + * @param coordinate COordinate + * @returns Hemisphere, degrees, minutes and seconds. + */ + function toStringHDMS(coordinate?: ol.Coordinate): string; + + /** + * Format a coordinate as a comma delimited string. + * @param coordinate Coordinate + * @param fractionDigits The number of digits to include after the decimal point. Default is 0. + * @returns XY + */ + function toStringXY(coordinate?: ol.Coordinate, fractionDigits?: number): string; + } + + /** + * Easing functions for ol.animation. + */ + namespace easing { + + /** + * Start slow and speed up. + * @param number Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function easeIn(t: number): number; + + /** + * Start fast and slow down. + * @param number Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function easeOut(t: number): number; + + /** + * Start slow, speed up, and then slow down again. + * @param number Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function inAndOut(t: number): number; + + /** + * Maintain a constant speed over time. + * @param number Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function linear(t: number): number; + + /** + * Start slow, speed up, and at the very end slow down again. This has the same general behavior as ol.easing.inAndOut, but the final slowdown is delayed. + * @param number Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function upAndDown(t: number): number; + } + + namespace events { + namespace condition { + function altKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function altShiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function always(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function click(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function doubleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function mouseOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function never(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function noModifierKeys(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function platformModifierKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function pointerMove(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function shiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function singleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function targetNotEditable(mapBrowserEvent: ol.MapBrowserEvent): boolean; + } + interface ConditionType { (mapBrowseEvent: ol.MapBrowserEvent): boolean; } + class Event { + target: any; + type: string; + preventDefault(): void; + stopPropagation(): void; + } + } + + namespace extent { + + /** + * Apply a transform function to the extent. + * @param extent Extent + * @param transformFn Transform function. Called with [minX, minY, maxX, maxY] extent coordinates. + * @param destinationExtent Destination Extent + * @returns Extent + */ + function applyTransform(extent: ol.Extent, transformFn: ol.TransformFunction, destinationExtent?: ol.Extent): ol.Extent; + + /** + * Build an extent that includes all given coordinates. + * @param coordinates Coordinates + * @returns Bounding extent + */ + function boundingExtent(coordinates: Array): ol.Extent; + + /** + * Return extent increased by the provided value. + * @param extent Extent + * @param value The amount by which the extent should be buffered. + * @param destinationExtent Destination Extent + * @returns Extent + */ + function buffer(extent: ol.Extent, value: number, destinationExtent?: ol.Extent): ol.Extent; + + /** + * Check if the passed coordinate is contained or on the edge of the extent. + * @param extent Extent + * @param coordinate Coordinate + * @returns The coordinate is contained in the extent + */ + function containsCoordinate(extent: ol.Extent, coordinate: ol.Coordinate): boolean; + + /** + * Check if one extent contains another. An extent is deemed contained if it lies completely within the other extent, including if they share one or more edges. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @returns The second extent is contained by or on the edge of the first + */ + function containsExtent(extent1: ol.Extent, extent2: ol.Extent): boolean; + + /** + * Check if the passed coordinate is contained or on the edge of the extent. + * @param extent Extent + * @param x X coordinate + * @param y Y coordinate + * @returns The x, y values are contained in the extent. + */ + function containsXY(extent: ol.Extent, x: number, y: number): boolean; + + /** + * Create an empty extent. + * @returns Empty extent + */ + function createEmpty(): ol.Extent; + + /** + * Determine if two extents are equivalent. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @returns The two extents are equivalent + */ + function equals(extent1: ol.Extent, extent2: ol.Extent): boolean; + + /** + * Modify an extent to include another extent. + * @param extent1 The extent to be modified. + * @param extent2 The extent that will be included in the first. + * @returns A reference to the first (extended) extent. + */ + function extend(extent1: ol.Extent, extent2: ol.Extent): ol.Extent; + + /** + * Get the bottom left coordinate of an extent. + * @param extent Extent + * @returns Bottom left coordinate + */ + function getBottomLeft(extent: ol.Extent): ol.Coordinate; + + /** + * Get the bottom right coordinate of an extent. + * @param extent Extent + * @returns Bottom right coordinate + */ + function getBottomRight(extent: ol.Extent): ol.Coordinate; + + /** + * Get the center coordinate of an extent. + * @param extent Extent + * @returns Center + */ + function getCenter(extent: ol.Extent): ol.Coordinate; + + /** + * Get the height of an extent. + * @param extent Extent + * @returns Height + */ + function getHeight(extent: ol.Extent): number; + + /** + * Get the intersection of two extents. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @param extent Optional extent to populate with intersection. + * @returns Intersecting extent + */ + function getIntersection(extent1: ol.Extent, extent2: ol.Extent, extent?: ol.Extent): ol.Extent; + + /** + * Get the size (width, height) of an extent. + * @param extent Extent + * @returns The extent size + */ + function getSize(extent: ol.Extent): ol.Size; + + /** + * Get the top left coordinate of an extent. + * @param extent Extent + * @returns Top left coordinate + */ + function getTopLeft(extent: ol.Extent): ol.Coordinate; + + /** + * Get the top right coordinate of an extent. + * @param extent Extent + * @returns Top right coordinate + */ + function getTopRight(extent: ol.Extent): ol.Coordinate; + + /** + * Get the width of an extent. + * @param extent Extent + * @returns Width + */ + function getWidth(extent: ol.Extent): number; + + /** + * Determine if one extent intersects another. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @returns The two extents intersects + */ + function intersects(extent1: ol.Extent, extent2: ol.Extent): boolean; + + /** + * Determine if an extent is empty. + * @param extent Extent + * @returns Is empty + */ + function isEmpty(extent: ol.Extent): boolean; + } + + /** + * Loading mechanisms for vector data. + */ + namespace featureloader { + + /** + * Create an XHR feature loader for a url and format. The feature loader loads features (with XHR), parses the features, and adds them to the vector source. + * @param url Feature URL Service + * @param format Feature format + * @returns The feature loader + */ + function xhr(url: string, format: ol.format.Feature): ol.FeatureLoader; + } + + namespace format { + + // Type definitions + interface IGCZ extends String { } + + // Classes + class EsriJSON { + } + + class Feature { + } + + /** + * Feature format for reading and writing data in the GeoJSON format. + */ + class GeoJSON extends ol.format.JSONFeature { + + /** + * @constructor + * @param Options + */ + constructor(options?: olx.format.GeoJSONOptions); + + /** + * Read a feature from a GeoJSON Feature source. Only works for Feature, use readFeatures to read FeatureCollection source. + * @param source Source + * @param options Read options + * @returns Feature + */ + readFeature(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): ol.Feature; + + /** + * Read all features from a GeoJSON source. Works with both Feature and FeatureCollection sources. + * @param source Source + * @param options Read options + * @returns Features + */ + readFeatures(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): Array; + + /** + * Read a geometry from a GeoJSON source. + * @param source Source + * @param options Read options + * @returns Geometry + */ + readGeometry(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): ol.geom.Geometry; + + /** + * Read the projection from a GeoJSON source. + * @param Source + * @returns Projection + */ + readProjection(source: Document | Node | JSON | string): ol.proj.Projection; + + /** + * Encode a feature as a GeoJSON Feature string. + * @param feature Feature + * @param options Write options + * @returns GeoJSON + */ + writeFeature(feature: ol.Feature, options?: olx.format.WriteOptions): string; + + /** + * Encode a feature as a GeoJSON Feature object. + * @param feature Feature + * @param options Write options + * @returns GeoJSON object + */ + writeFeatureObject(feature: ol.Feature, options?: olx.format.WriteOptions): JSON; + + /** + * Encode an array of features as GeoJSON. + * @param features Features + * @param options Write options + * @returns GeoJSON + */ + writeFeatures(features: Array, options?: olx.format.WriteOptions): string; + + /** + * Encode an array of features as a GeoJSON object. + * @param features Features + * @param options Write options + * @returns GeoJSON object + */ + writeFeaturesObject(features: Array, options?: olx.format.WriteOptions): JSON; + + /** + * Encode a geometry as a GeoJSON string. + * @param geometry Geometry + * @param options Write options + * @returns GeoJSON + */ + writeGeometry(geometry: ol.geom.Geometry, options?: olx.format.WriteOptions): string; + + /** + * Encode a geometry as a GeoJSON object. + * @param geometry Geometry + * @options Write options + * @returns GeoJSON object + */ + writeGeometryObject(geometry: ol.geom.Geometry, options?: olx.format.WriteOptions): JSON; + } + + class GML { + } + + class GML2 { + } + + class GML3 { + } + + class GMLBase { + } + + class GPX { + } + + class IGC { + } + + class JSONFeature { + } + + class KML { + } + + class OSMXML { + } + + class Polyline { + } + + class TextFeature { + } + + class TopoJSON { + } + + class WFS { + readFeatures(source: Document | Node | Object | string, option?: olx.format.ReadOptions): Array; + } + + class WKT { + constructor(opt_options?: olx.format.WKTOptions); + + /** + * Read a feature from a WKT source. + * @param source Source + * @param options Read options + * @returns Feature + */ + readFeature(source: Document | Node | JSON | string, opt_options?: olx.format.ReadOptions): ol.Feature; + + /** + * Read all features from a WKT source. + * @param source Source + * @param options Read options + * @returns Features + */ + readFeatures(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): Array; + + /** + * Read a geometry from a GeoJSON source. + * @param source Source + * @param options Read options + * @returns Geometry + */ + readGeometry(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): ol.geom.Geometry; + + /** + * Encode a feature as a WKT string. + * @param feature Feature + * @param options Write options + * @returns GeoJSON + */ + writeFeature(feature: ol.Feature, options?: olx.format.WriteOptions): string; + + /** + * Encode an array of features as a WKT string. + * @param features Features + * @param options Write options + * @returns GeoJSON + */ + writeFeatures(features: Array, options?: olx.format.WriteOptions): string; + + /** + * Write a single geometry as a WKT string. + * @param geometry Geometry + * @param options Write options + * @returns GeoJSON + */ + writeGeometry(geometry: ol.geom.Geometry, options?: olx.format.WriteOptions): string; + } + + class WMSCapabilities { + } + + class WMSGetFeatureInfo { + } + + class WMTSCapabilities { + } + + class XML { + } + + class XMLFeature { + } + } + + namespace geom { + + // Type definitions + interface GeometryLayout extends String { } + interface GeometryType extends String { } + + /** + * Abstract base class; only used for creating subclasses; do not instantiate + * in apps, as cannot be rendered. + */ + class Circle extends ol.geom.SimpleGeometry { + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Transform each coordinate of the circle from one coordinate reference system + * to another. The geometry is modified in place. + * If you do not want the geometry modified in place, first clone() it and + * then use this function on the clone. + * + * Internally a circle is currently represented by two points: the center of + * the circle `[cx, cy]`, and the point to the right of the circle + * `[cx + r, cy]`. This `transform` function just transforms these two points. + * So the resulting geometry is also a circle, and that circle does not + * correspond to the shape that would be obtained by transforming every point + * of the original circle. + * @param source The current projection. Can be a string identifier or a {@link ol.proj.Projection} object. + * @param destination The desired projection. Can be a string identifier or a {@link ol.proj.Projection} object. + * @returns This geometry. Note that original geometry is modified in place. + */ + transform(source: ol.proj.ProjectionLike, destination: ol.proj.ProjectionLike): ol.geom.Circle; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. Base class for vector geometries. + */ + class Geometry extends ol.Object { + + /** + * Return the closest point of the geometry to the passed point as coordinate. + * @param point Point + * @param closestPoint Closest Point + * @returns Closest Point + */ + getClosestPoint(point: ol.Coordinate, closestPoint?: ol.Coordinate): ol.Coordinate; + + /** + * Get the extent of the geometry. + * @param Extent + * @returns Extent + */ + getExtent(extent?: ol.Extent): ol.Extent; + + /** + * Transform each coordinate of the geometry from one coordinate reference system to another. + * The geometry is modified in place. For example, a line will be transformed to a line and a + * circle to a circle. If you do not want the geometry modified in place, first clone() it and + * then use this function on the clone. + * @param source The current projection. Can be a string identifier or a ol.proj.Projection object. + * @param destination The desired projection. Can be a string identifier or a ol.proj.Projection object. + * @return This geometry. Note that original geometry is modified in place. + */ + transform(source: ol.proj.ProjectionLike | ol.proj.Projection, destination: ol.proj.ProjectionLike | ol.proj.Projection): ol.geom.Geometry; + } + + /** + * An array of ol.geom.Geometry objects. + */ + class GeometryCollection extends ol.geom.Geometry { + + /** + * constructor + * @param geometries Geometries. + */ + constructor(geometries?: Array); + + /** + * Apply a transform function to each coordinate of the geometry. The geometry is modified in place. + * If you do not want the geometry modified in place, first clone() it and then use this function on the clone. + * @param transformFn TransformFunction + */ + applyTransform(transformFn: ol.TransformFunction): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.GeometryCollection; + + /** + * Return the geometries that make up this geometry collection. + * @returns Geometries. + */ + getGeometries(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the geometries that make up this geometry collection. + * @param geometries Geometries. + */ + setGeometries(geometries: Array): void; + + } + + /** + * Linear ring geometry. Only used as part of polygon; cannot be rendered + * on its own. + */ + class LinearRing extends SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array, layout?: ol.geom.GeometryLayout); + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.LinearRing; + + /** + * Return the area of the linear ring on projected plane. + * @returns Area (on projected plane). + */ + getArea(): number; + + /** + * Return the coordinates of the linear ring. + * @returns Coordinates. + */ + getCoordinates(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * @Set the coordinates of the linear ring + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array, layout?: any): void; + + } + + /** + * Linestring geometry. + */ + class LineString extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed coordinate to the coordinates of the linestring. + * @param coordinate Coordinate. + */ + appendCoordinate(coordinate: ol.Coordinate): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.LineString; + + /** + * Returns the coordinate at `m` using linear interpolation, or `null` if no + * such coordinate exists. + * + * `extrapolate` controls extrapolation beyond the range of Ms in the + * MultiLineString. If `extrapolate` is `true` then Ms less than the first + * M will return the first coordinate and Ms greater than the last M will + * return the last coordinate. + * + * @param m M. + * @param extrapolate Extrapolate. Default is `false`. + * @returns Coordinate. + */ + getCoordinateAtM(m: number, extrapolate?: boolean): ol.Coordinate; + + /** + * Return the coordinates of the linestring. + * @returns Coordinates. + */ + getCoordinates(): Array; + + /** + * Return the length of the linestring on projected plane. + * @returns Length (on projected plane). + */ + getLength(): number; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the linestring. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Multi-linestring geometry. + */ + class MultiLineString extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array>, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed linestring to the multilinestring. + * @param lineString LineString. + */ + appendLineString(lineString: ol.geom.LineString): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.MultiLineString; + + /** + * Returns the coordinate at `m` using linear interpolation, or `null` if no + * such coordinate exists. + * + * `extrapolate` controls extrapolation beyond the range of Ms in the + * MultiLineString. If `extrapolate` is `true` then Ms less than the first + * M will return the first coordinate and Ms greater than the last M will + * return the last coordinate. + * + * `interpolate` controls interpolation between consecutive LineStrings + * within the MultiLineString. If `interpolate` is `true` the coordinates + * will be linearly interpolated between the last coordinate of one LineString + * and the first coordinate of the next LineString. If `interpolate` is + * `false` then the function will return `null` for Ms falling between + * LineStrings. + * + * @param m M. + * @param extrapolate Extrapolate. Default is `false`. + * @param interpolate Interpolate. Default is `false`. + * @returns Coordinate. + */ + getCoordinateAtM(m: number, extrapolate?: boolean, interpolate?: boolean): ol.Coordinate; + + /** + * Return the coordinates of the multilinestring. + * @returns Coordinates. + */ + getCoordinates(): Array>; + + /** + * Return the linestring at the specified index. + * @param index Index. + * @returns LineString. + */ + getLineString(index: number): ol.geom.LineString; + + /** + * Return the linestrings of this multilinestring. + * @returns LineStrings. + */ + getLineStrings(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the multilinestring. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array>, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Multi-point geometry. + */ + class MultiPoint extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed point to this multipoint. + * @param {ol.geom.Point} point Point. + */ + appendPoint(point: ol.geom.Point): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.MultiPoint; + + /** + * Return the coordinates of the multipoint. + * @returns Coordinates. + */ + getCoordinates(): Array; + + /** + * Return the point at the specified index. + * @param index Index. + * @returns Point. + */ + getPoint(index: number): ol.geom.Point; + + /** + * Return the points of this multipoint. + * @returns Points. + */ + getPoints(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the multipoint. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Multi-polygon geometry. + */ + class MultiPolygon extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array>>, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed polygon to this multipolygon. + * @param polygon Polygon. + */ + appendPolygon(polygon: ol.geom.Polygon): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.MultiPolygon; + + /** + * Return the area of the multipolygon on projected plane. + * @returns Area (on projected plane). + */ + getArea(): number; + + /** + * Get the coordinate array for this geometry. This array has the structure + * of a GeoJSON coordinate array for multi-polygons. + * + * @param right Orient coordinates according to the right-hand + * rule (counter-clockwise for exterior and clockwise for interior rings). + * If `false`, coordinates will be oriented according to the left-hand rule + * (clockwise for exterior and counter-clockwise for interior rings). + * By default, coordinate orientation will depend on how the geometry was + * constructed. + * @returns Coordinates. + */ + getCoordinates(right?: boolean): Array>>; + + /** + * Return the interior points as {@link ol.geom.MultiPoint multipoint}. + * @returns Interior points. + */ + getInteriorPoints(): ol.geom.MultiPoint; + + /** + * Return the polygon at the specified index. + * @param index Index. + * @returns Polygon. + */ + getPolygon(index: number): ol.geom.Polygon; + + /** + * Return the polygons of this multipolygon. + * @returns Polygons. + */ + getPolygons(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the multipolygon. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array>>, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Point geometry. + */ + class Point extends SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: ol.Coordinate, layout?: ol.geom.GeometryLayout); + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.Point; + + /** + * Return the coordinate of the point. + * @returns Coordinates. + */ + getCoordinates(): ol.Coordinate; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinate of the point. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: ol.Coordinate, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Polygon geometry. + */ + class Polygon extends SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array>, layout?: ol.geom.GeometryLayout); + + /** + * Create an approximation of a circle on the surface of a sphere. + * @param sphere The sphere. + * @param center Center (`[lon, lat]` in degrees). + * @param radius The great-circle distance from the center to the polygon vertices. + * @param n Optional number of vertices for the resulting polygon. Default is `32`. + * @returns The "circular" polygon. + */ + static circular(sphere: ol.Sphere, center: ol.Coordinate, radius: number, n?: number): ol.geom.Polygon; + + /** + * Append the passed linear ring to this polygon. + * @param linearRing Linear ring. + */ + appendLinearRing(linearRing: ol.geom.LinearRing): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.Polygon; + + /** + * Return the area of the polygon on projected plane. + * @returns Area (on projected plane). + */ + getArea(): number; + + /** + * Get the coordinate array for this geometry. This array has the structure + * of a GeoJSON coordinate array for polygons. + * + * @param right Orient coordinates according to the right-hand + * rule (counter-clockwise for exterior and clockwise for interior rings). + * If `false`, coordinates will be oriented according to the left-hand rule + * (clockwise for exterior and counter-clockwise for interior rings). + * By default, coordinate orientation will depend on how the geometry was + * constructed. + * @returns Coordinates. + */ + getCoordinates(right?: boolean): Array>; + + /** + * Return an interior point of the polygon. + * @returns Interior point. + */ + getInteriorPoint(): ol.geom.Point; + + /** + * Return the Nth linear ring of the polygon geometry. Return `null` if the + * given index is out of range. + * The exterior linear ring is available at index `0` and the interior rings + * at index `1` and beyond. + * + * @param index Index. + * @returns Linear ring. + */ + getLinearRing(index: number): ol.geom.LinearRing; + + /** + * Return the linear rings of the polygon. + * @returns Linear rings. + */ + getLinearRings(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the polygon. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array>, layout?: ol.geom.GeometryLayout): void; + } + /** + * Abstract base class; only used for creating subclasses; do not instantiate + * in apps, as cannot be rendered. + */ + class SimpleGeometry extends ol.geom.Geometry { + + /** + * Apply a transform function to each coordinate of the geometry. The geometry is modified in place. + * If you do not want the geometry modified in place, first clone() it and then use this function on the clone. + * @param transformFn TransformFunction + */ + applyTransform(transformFn: ol.TransformFunction): void; + + /** + * Return the first coordinate of the geometry. + * @returns First coordinate. + */ + getFirstCoordinate(): ol.Coordinate; + + /** + * Return the last coordinate of the geometry. + * @returns Last point. + */ + getLastCoordinate(): ol.Coordinate; + + /** + * Return the {@link ol.geom.GeometryLayout layout} of the geometry. + * @returns Layout. + */ + getLayout(): ol.geom.GeometryLayout; + + /** + * Translate the geometry. This modifies the geometry coordinates in place. + * If instead you want a new geometry, first clone() this geometry. + * @param deltaX Delta X + * @param deltaY Delta Y + */ + translate(deltaX: number, deltaY: number): void; + } + } + + namespace has { + } + + namespace interaction { + /** + * Allows the user to zoom by double-clicking on the map. + */ + class DoubleClickZoom extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.DoubleClickZoomOptions); + } + /** + * Handles input of vector data by drag and drop. + */ + class DragAndDrop extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.DragAndDropOptions); + } + /** + * Events emitted by ol.interaction.DragAndDrop instances are instances of this type. + */ + class DragAndDropEvent extends ol.events.Event { + } + /** + * Allows the user to draw a vector box by clicking and dragging on the map, + * normally combined with an ol.events.condition that limits it to when the shift or other key is held down. + * This is used, for example, for zooming to a specific area of the map + * (see ol.interaction.DragZoom and ol.interaction.DragRotateAndZoom). + * + * This interaction is only supported for mouse devices. + */ + class DragBox extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DragBoxOptions); + /** + * Returns geometry of last drawn box. + */ + getGeometry(): ol.geom.Polygon; + } + /** + * Allows the user to pan the map by dragging the map. + */ + class DragPan extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DragPanOptions); + } + /** + * Allows the user to rotate the map by clicking and dragging on the map, + * normally combined with an ol.events.condition that limits it to when the alt and shift keys are held down. + * + * This interaction is only supported for mouse devices. + */ + class DragRotate extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DragRotateOptions); + } + /** + * Allows the user to zoom and rotate the map by clicking and dragging on the map. + * By default, this interaction is limited to when the shift key is held down. + * + * This interaction is only supported for mouse devices. + * + * And this interaction is not included in the default interactions. + */ + class DragRotateAndZoom extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DragRotateAndZoomOptions); + } + /** + * Allows the user to zoom the map by clicking and dragging on the map, + * normally combined with an ol.events.condition that limits it to when a key, shift by default, is held down. + * + * To change the style of the box, use CSS and the .ol-dragzoom selector, or your custom one configured with className. + */ + class DragZoom extends ol.interaction.DragBox { + constructor(opt_options?: olx.interaction.DragZoomOptions); + } + /** + * Interaction for drawing feature geometries. + */ + class Draw extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DrawOptions); + } + /** + * Events emitted by ol.interaction.Draw instances are instances of this type. + */ + class DrawEvent extends ol.events.Event { + /** + * The feature being drawn. + */ + feature: ol.Feature; + /** + * The event target. + */ + target: ol.Object; + /** + * The event type. + */ + type: string; + } + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. + * User actions that change the state of the map. Some are similar to controls, but are not associated with a DOM element. + * For example, ol.interaction.KeyboardZoom is functionally the same as ol.control.Zoom, but triggered by a keyboard event + * not a button element event. Although interactions do not have a DOM element, + * some of them do render vectors and so are visible on the screen. + */ + class Interaction extends ol.Object { + constructor (options: olx.interaction.InteractionOptions) + /** + * Return whether the interaction is currently active. + */ + getActive (): boolean; + /** + * Get the map associated with this interaction. + */ + getMap (): ol.Map; + /** + * Activate or deactivate the interaction. + */ + setActive (active: boolean): void; + } + /** + * Allows the user to pan the map using keyboard arrows. Note that, although this interaction is by default included in maps, + * the keys can only be used when browser focus is on the element to which the keyboard events are attached. + * By default, this is the map div, though you can change this with the keyboardEventTarget in ol.Map. + * document never loses focus but, for any other element, focus will have to be on, and returned to, + * this element if the keys are to function. See also ol.interaction.KeyboardZoom. + */ + class KeyboardPan extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.KeyboardPanOptions); + } + /** + * Allows the user to zoom the map using keyboard + and -. Note that, although this interaction is by default included in maps, + * the keys can only be used when browser focus is on the element to which the keyboard events are attached. By default, + * this is the map div, though you can change this with the keyboardEventTarget in ol.Map. document never loses focus but, + * for any other element, focus will have to be on, and returned to, this element if the keys are to function. + * See also ol.interaction.KeyboardPan. + */ + class KeyboardZoom extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.KeyboardZoomOptions); + } + /** + * Interaction for modifying feature geometries. + */ + class Modify extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.ModifyOptions); + } + /** + * Allows the user to zoom the map by scrolling the mouse wheel. + */ + class MouseWheelZoom extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.MouseWheelZoomOptions); + } + /** + * Allows the user to rotate the map by twisting with two fingers on a touch screen. + */ + class PinchRotate extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.PinchRotateOptions); + } + /** + * Allows the user to zoom the map by pinching with two fingers on a touch screen. + */ + class PinchZoom extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.PinchZoomOptions); + } + /** + * Base class that calls user-defined functions on down, move and up events. This class also manages "drag sequences". + * + * When the handleDownEvent user function returns true a drag sequence is started. During a drag sequence the handleDragEvent + * user function is called on move events. The drag sequence ends when the handleUpEvent user function is called and returns false. + */ + class Pointer extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.PointerOptions); + } + /** + * Interaction for selecting vector features. By default, selected features are styled differently, so this interaction can be used + * for visual highlighting, as well as selecting features for other actions, such as modification or output. There are three ways of + * controlling which features are selected: using the browser event as defined by the condition and optionally the toggle, + * add/remove, and multi options; a layers filter; and a further feature filter using the filter option. + * + * Selected features are added to an internal unmanaged layer. + */ + class Select extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.SelectOptions); + /** + * Returns the associated vectorlayer of the (last) selected feature. + * Note that this will not work with any programmatic method like pushing features to collection. + */ + getLayer(): ol.layer.Layer; + /** + * Get the selected features. + */ + getFeatures(): ol.Collection; + } + /** + * Events emitted by ol.interaction.Select instances are instances of this type. + */ + class SelectEvent extends ol.events.Event { + /** + * Deselectd features array. + */ + deselected: Array; + /** + * Associated ol.MapBrowserEvent. + */ + mapBrowserEvent: ol.MapBrowserEvent; + /** + * Selected features array. + */ + selected: Array; + /** + * The event target. + */ + target: ol.Object; + /** + * The event type. + */ + type: string; + /** + * Stop event propagation. + */ + preventDefault(): void; + /** + * Stop event propagation. + */ + stopPropagation(): void; + } + /** + * Handles snapping of vector features while modifying or drawing them. The features can come from a ol.source.Vector or + * ol.Collection Any interaction object that allows the user to interact with the features using the mouse can benefit + * from the snapping, as long as it is added before. + * + *The snap interaction modifies map browser event coordinate and pixel properties to force the snap to occur + * to any interaction that them. + */ + class Snap extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.SnapOptions); + } + /** + * Set of interactions included in maps by default. Specific interactions can be excluded by setting the appropriate option + * to false in the constructor options, but the order of the interactions is fixed. If you want to specify a different order for + * interactions, you will need to create your own ol.interaction.Interaction instances and insert them into a ol.Collection in + * the order you want before creating your ol.Map instance. + */ + function defaults(opts: olx.interaction.DefaultsOptions): ol.Collection; + /** + * Function that takes coordinates and an optional existing geometry as arguments, and returns a geometry. + * The optional existing geometry is the geometry that is returned when the function is called without a second argument. + */ + interface DrawGeometryFunctionType { (coordinates: ol.Coordinate, geom?: ol.geom.Geometry): ol.geom.Geometry; } + /** + * A function that takes an ol.Feature or ol.render.Feature and an ol.layer.Layer and returns true if the feature + * may be selected or false otherwise. + */ + interface SelectFilterFunction { (feature: ol.Feature | ol.render.Feature, layer: ol.layer.Layer): boolean; } + /** + * A function that takes a ol.MapBrowserEvent and two ol.Pixels and returns a {boolean}. + * If the condition is met, true should be returned. + */ + interface DragBoxEndConditionType { + (evt: ol.MapBrowserEvent, startPixel: ol.Pixel, endPixel: ol.Pixel): boolean + } + } + + namespace layer { + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. Note that with ol.layer.Base and all its subclasses, any property set in the options is set as a ol.Object property on the layer object, so is observable, and has get/set accessors. + */ + class Base extends ol.Object { + + /** + * @constructor + * @param options Layer options. + */ + constructor(options?: olx.layer.BaseOptions); + + /** + * Return the brightness of the layer. + * @returns The brightness of the layer. + */ + getBrightness(): number; + + /** + * Return the contrast of the layer. + * @returns The contrast of the layer. + */ + getContrast(): number; + + /** + * Return the extent of the layer or undefined if it will be visible regardless of extent. + * @returns The layer extent. + */ + getExtent(): ol.Extent; + + /** + * Return the hue of the layer. + * @returns The hue of the layer + */ + getHue(): number; + + /** + * Return the maximum resolution of the layer. + * @returns The maximum resolution of the layer + */ + getMaxResolution(): number; + + /** + * Return the minimum resolution of the layer. + * @returns The minimum resolution of the layer. + */ + getMinResolution(): number; + + /** + * Return the opacity of the layer (between 0 and 1). + * @returns The opacity of the layer. + */ + getOpacity(): number; + + /** + * Return the saturation of the layer. + * @returns The saturation of the layer. + */ + getSaturation(): number; + + /** + * Return the visibility of the layer (true or false). + * The visibility of the layer + */ + getVisible(): boolean; + + /** + * Adjust the layer brightness. A value of -1 will render the layer completely black. A value of 0 will leave the brightness unchanged. A value of 1 will render the layer completely white. Other values are linear multipliers on the effect (values are clamped between -1 and 1). + * @param brightness The brightness of the layer + */ + setBrightness(brigthness: number): void; + + /** + * Adjust the layer contrast. A value of 0 will render the layer completely grey. A value of 1 will leave the contrast unchanged. Other values are linear multipliers on the effect (and values over 1 are permitted). + * @param contrast The contrast of the layer + */ + setContrast(contrast: number): void; + + /** + * Set the extent at which the layer is visible. If undefined, the layer will be visible at all extents. + * @param extent The extent of the layer + */ + setExtent(extent?: ol.Extent): void; + + /** + * Apply a hue-rotation to the layer. A value of 0 will leave the hue unchanged. Other values are radians around the color circle. + * @param hue The hue of the layer + */ + setHue(hue: number): void; + + /** + * Set the maximum resolution at which the layer is visible. + * @param maxResolution The maximum resolution of the layer. + */ + setMaxResolution(maxResolution: number): void; + + /** + * Set the minimum resolution at which the layer is visible. + * @param minResolution The minimum resolution of the layer. + */ + setMinResolution(minResolution: number): void; + + /** + * Set the opacity of the layer, allowed values range from 0 to 1. + * @param opactity The opacity of the layer. + */ + setOpacity(opacity: number): void; + + /** + * Adjust layer saturation. A value of 0 will render the layer completely unsaturated. A value of 1 will leave the saturation unchanged. Other values are linear multipliers of the effect (and values over 1 are permitted). + * @param saturation The saturation of the layer. + */ + setSaturation(saturation: number): void; + + /** + * Set the visibility of the layer (true or false). + * @param visible The visibility of the layer. + */ + setVisible(visible: boolean): void; + } + + /** + * A ol.Collection of layers that are handled together. + */ + class Group extends ol.layer.Base { + + /** + * @constructor + * @param options Layer options. + */ + constructor(options?: olx.layer.GroupOptions); + + /** + * Returns the collection of layers in this group. + * @returns Collection of layers that are part of this group. + */ + getLayers(): ol.Collection; + + /** + * Set the collection of layers in this group. + * @param layers Collection of layers that are part of this group. + */ + setLayers(layers: ol.Collection): void; + } + + /** + * Layer for rendering vector data as a heatmap. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Heatmap extends ol.layer.Vector { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.layer.HeatmapOptions); + + /** + * Return the blur size in pixels. + * @returns Blur size in pixels + */ + getBlur(): number; + + /** + * Return the gradient colors as array of strings. + * @returns Colors + */ + getGradient(): Array; + + /** + * Return the size of the radius in pixels. + * @returns Radius size in pixel + */ + getRadius(): number; + + /** + * Set the blur size in pixels. + * @param blur Blur size in pixels + */ + setBlur(blur: number): void; + + /** + * Set the gradient colors as array of strings. + * @param colors Gradient + */ + setGradient(colors: Array): void; + + /** + * Set the size of the radius in pixels. + * @param radius Radius size in pixels + */ + setRadius(radius: number): void; + } + + /** + * Server-rendered images that are available for arbitrary extents and resolutions. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Image extends ol.layer.Layer { + + /** + * @constructor + * @param options Layer options + */ + constructor(options?: olx.layer.ImageOptions); + + /** + * Return the associated source of the image layer. + * @returns Source. + */ + getSource(): ol.source.Image; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. A visual representation of raster or vector map data. Layers group together those properties that pertain to how the data is to be displayed, irrespective of the source of that data. + */ + class Layer extends ol.layer.Base { + + /** + * @constructor + * @param options Layer options + */ + constructor(options?: olx.layer.LayerOptions); + + /** + * Get the layer source. + * @returns The layer source (or null if not yet set) + */ + getSource(): ol.source.Source; + + /** + * Set the layer source. + * @param source The layer source. + */ + setSource(source: ol.source.Source): void; + } + + /** + * For layer sources that provide pre-rendered, tiled images in grids that are organized by zoom levels for specific resolutions. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Tile extends ol.layer.Layer { + + /** + * @constructor + * @param options Tile layer options. + */ + constructor(options?: olx.layer.TileOptions); + + /** + * Return the level as number to which we will preload tiles up to. + * @retruns The level to preload tiled up to. + */ + getPreload(): number; + + /** + * Return the associated tilesource of the layer. + * @returns Source + */ + getSource(): ol.source.Tile; + + /** + * Whether we use interim tiles on error. + * @returns Use interim tiles on error. + */ + getUseInterimTilesOnError(): boolean; + + /** + * Set the level as number to which we will preload tiles up to. + * @param preload The level to preload tiled up to + */ + setPreload(preload: number): void; + + /** + * Set whether we use interim tiles on error. + * @param useInterimTilesOnError Use interim tiles on error. + */ + setUseInterimTilesOnError(useInterimTilesOnError: boolean): void; + } + + /** + * Vector data that is rendered client-side. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Vector extends ol.layer.Layer { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.layer.VectorOptions); + + /** + * Return the associated vectorsource of the layer. + * @returns Source. + */ + getSource(): ol.source.Vector; + + /** + * Get the style for features. This returns whatever was passed to the style option at construction or to the setStyle method. + */ + getStyle(): ol.style.Style | Array | ol.style.StyleFunction; + + /** + * Get the style function. + * @returns Layer style function + */ + getStyleFunction(): ol.style.StyleFunction; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + */ + setStyle(): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + * @param layer Layer style + */ + setStyle(style: ol.style.Style): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + * @param layer Layer style + */ + setStyle(style: Array): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + * @param Layer style + */ + setStyle(style: ol.style.StyleFunction): void; + + /** + * Sets the layer to be rendered on top of other layers on a map. The map will not manage this layer + * in its layers collection, and the callback in ol.Map#forEachLayerAtPixel will receive null as + * layer. This is useful for temporary layers. To remove an unmanaged layer from the map, use #setMap(null). + * To add the layer to a map and have it managed by the map, use ol.Map#addLayer instead. + * @argument map. + */ + setMap(map: ol.Map): void; + + /** + * Set Z-index of the layer, which is used to order layers before rendering. The default Z-index is 0. + */ + setZIndex(zIndex: number): void; + } + } + + namespace loadingstrategy { + + /** + * Strategy function for loading all features with a single request. + * @param extent Extent + * @param resolution Resolution + * @returns Extents + */ + function all(extent: ol.Extent, resolution: number): Array; + + /** + * Strategy function for loading features based on the view's extent and resolution. + * @param extent Extent + * @param resolution Resolution + * @returns Extents + */ + function bbox(extent: ol.Extent, resolution: number): Array; + + /** + * Creates a strategy function for loading features based on a tile grid. + * @param tilegrid Tile grid + * @returns Loading strategy + */ + function tile(tileGrid: ol.tilegrid.TileGrid): ol.LoadingStrategy; + } + + namespace proj { + + // Type definitions + interface ProjectionLike extends String { } + interface Units extends String { } + + // Methods + + /** + * Meters per unit lookup table. + */ + //TODO: validate! + var METERS_PER_UNIT: Object; + + /** + * Registers coordinate transform functions to convert coordinates between the source projection and the destination projection. The forward and inverse functions convert coordinate pairs; this function converts these into the functions used internally which also handle extents and coordinate arrays. + * @param source Source projection + * @param destination Destination projection + * @param forward The forward transform function (that is, from the source projection to the destination projection) that takes a ol.Coordinate as argument and returns the transformed ol.Coordinate. + * @param inverse The inverse transform function (that is, from the destination projection to the source projection) that takes a ol.Coordinate as argument and returns the transformed ol.Coordinate. + */ + function addCoordinateTransforms(source: ProjectionLike, destination: ProjectionLike, forward: (coordinate: Coordinate) => Coordinate, inverse: (coordinate: Coordinate) => Coordinate): void; + + /** + * Registers transformation functions that don't alter coordinates. Those allow to transform between projections with equal meaning. + * @param projections Projections. + */ + function addEquivalentProjections(projections: Array): void; + + /** + * Add a Projection object to the list of supported projections that can be looked up by their code. + * @param projection Projection instance. + */ + function addProjection(projection: Projection): void; + + /** + * Transforms a coordinate from longitude/latitude to a different projection. + * @param coordinate Coordinate as longitude and latitude, i.e. an array with longitude as 1st and latitude as 2nd element. + * @param projection Target projection. The default is Web Mercator, i.e. 'EPSG:3857'. + */ + function fromLonLat(coordinate: Coordinate, opt_projection: ProjectionLike): Coordinate; + + /** + * Fetches a Projection object for the code specified. + * @param projectionLike Either a code string which is a combination of authority and identifier such as "EPSG:4326", or an existing projection object, or undefined. + * @returns Projection object, or null if not in list. + */ + function get(projectionLike: ProjectionLike): Projection; + + /** + * Given the projection-like objects, searches for a transformation function to convert a coordinates array from the source projection to the destination projection. + * @param source Source. + * @param destination Destination. + * @returns Transform function. + */ + function getTransform(source: ProjectionLike, destination: ProjectionLike): ol.TransformFunction; + + /** + * Transforms a coordinate to longitude/latitude. + * @param coordinate Projected coordinate. + * @param projection Projection of the coordinate. The default is Web Mercator, i.e. 'EPSG:3857'. + * @returns Coordinate as longitude and latitude, i.e. an array with longitude as 1st and latitude as 2nd element. + */ + function toLonLat(coordinate: Coordinate, projection: ProjectionLike): Coordinate; + + /** + * Transforms a coordinate from source projection to destination projection. This returns a new coordinate (and does not modify the original). + * @param coordinate Coordinate. + * @param source Source projection-like. + * @param destination Destination projection-like. + * @returns Coordinate. + */ + function transform(coordinate: Coordinate, source: ProjectionLike, destination: ProjectionLike): Coordinate; + + /** + * Transforms an extent from source projection to destination projection. This returns a new extent (and does not modify the original). + * @param extent The extent to transform. + * @param source Source projection-like. + * @param destination Destination projection-like. + * @returns The transformed extent. + */ + function transformExtent(extent: Extent, source: ProjectionLike, destination: ProjectionLike): Extent; + + class Projection { + constructor(options: olx.Projection); + + getExtent(): Extent; + + /** + * Set the validity extent for this projection. + * @param extent The new extent of the projection. + */ + setExtent(extent: Extent): void; + } + } + + namespace render { + + class Event extends ol.events.Event { + } + + class VectorContext { + } + class Feature { + get(key: string): any; + getExtent(): ol.Extent; + getGeometry(): ol.geom.Geometry; + getProperties: Object[]; + getType(): ol.geom.GeometryType; + } + namespace canvas { + class Immediate { + } + } + } + + namespace source { + + class BingMaps extends TileImage { + } + + class CartoDB extends XYZ { + } + + class Cluster extends Vector { + constructor(options: olx.source.ClusterOptions); + } + + class Image extends Source { + } + + class ImageArcGISRest extends Image { + } + + class ImageCanvas extends Image { + } + + class ImageEvent extends ol.events.Event { + } + + class ImageMapGuide extends Image { + } + + class ImageStatic extends ol.source.Image { + constructor(options?: olx.StaticImageOptions); + } + + class ImageVector extends ImageCanvas { + } + + class ImageWMS extends Image { + constructor(options: olx.ImageWMSOptions); + } + + class MapQuest extends XYZ { + constructor(options: any); + } + + class OSM extends XYZ { + constructor(opt_options?: olx.OSMOptions); + } + + class Source extends ol.Object { + + constructor(options: any); + + /** + * Get the projection of the source. + * @return Projection. + */ + getProjection(): ol.proj.Projection; + + /** + * Refreshes the source and finally dispatches a 'change' event. + */ + refresh(): void; + } + + class Stamen extends XYZ { + } + + class Tile extends Source { + } + + class TileArcGISRest extends TileImage { + } + + class TileDebug extends Tile { + } + + class TileEvent extends ol.events.Event { + } + + class TileImage extends UrlTile { + } + + class TileJSON extends TileImage { + } + + class TileUTFGrid extends Tile { + } + + class TileWMS extends TileImage { + constructor(options: olx.TileWMSOptions); + + /** + * Update the user-provided (WMS request) parameters. + */ + updateParams(params: any): void; + + /** + * Get the user-provided (WMS request) params, i.e. those passed to the constructor through the "params" option, and possibly updated using the updateParams method. + */ + getParams(): any; + + /** + * Return the GetFeatureInfo URL for the passed coordinate, resolution, and + * projection. Return `undefined` if the GetFeatureInfo URL cannot be + * constructed. + * @param coordinate Coordinate. + * @param resolution Resolution. + * @param rojection Projection. + * @param params GetFeatureInfo params. `INFO_FORMAT` at least should + * be provided. If `QUERY_LAYERS` is not provided then the layers specified + * in the `LAYERS` parameter will be used. `VERSION` should not be + * specified here. + * @return GetFeatureInfo URL. + */ + getGetFeatureInfoUrl(coordinate: ol.Coordinate, resolution: number, projection: ol.proj.ProjectionLike, params: {}): string; + } + + class UrlTile extends Tile { + } + + class Vector extends Source { + constructor(opts?: olx.source.VectorOptions) + /** + * Add a single feature to the source. If you want to add a batch of features at once, + * call source.addFeatures() instead. + */ + addFeature(feature: ol.Feature): void; + + /** + * Add a batch of features to the source. + */ + addFeatures(features: ol.Feature[]): void; + + /** + * Remove all features from the source. + * @param Skip dispatching of removefeature events. + */ + clear(fast?: boolean): void; + /** + * Get the extent of the features currently in the source. + */ + getExtent(): ol.Extent; + + /** + * Get all features in the provided extent. Note that this returns all features whose bounding boxes + * intersect the given extent (so it may include features whose geometries do not intersect the extent). + * This method is not available when the source is configured with useSpatialIndex set to false. + */ + getFeaturesInExtent(extent: ol.Extent): ol.Feature[]; + + /** + * Get all features on the source + */ + getFeatures(): ol.Feature[]; + + /** + * Get all features whose geometry intersects the provided coordinate. + */ + getFeaturesAtCoordinate(coordinate: ol.Coordinate): ol.Feature[]; + } + + class VectorEvent extends ol.events.Event { + } + + class VectorTile extends UrlTile { + } + + class WMTS extends TileImage { + constructor(options: olx.source.WMTSOptions); + } + + class XYZ extends TileImage { + } + + class Zoomify extends TileImage { + } + + // Namespaces + namespace wms { + interface ServerType extends String { } + } + + // Type definitions + interface State extends String { } + interface WMTSRequestEncoding extends String { } + } + + namespace style { + + class AtlasManager { + } + + class Circle extends Image { + constructor(opt_options?: olx.style.CircleOptions); + } + + /** + * Set fill style for vector features. + */ + class Fill { + + constructor(opt_options?: olx.style.FillOptions); + + getColor(): ol.Color | string; + + /** + * Set the color. + */ + setColor(color: ol.Color | string): void; + + getChecksum(): string; + } + + class Icon extends Image { + constructor(option: olx.style.IconOptions) + } + + class Image { + getOpacity(): number; + getRotateWithView(): boolean; + getRotation(): number; + getScale(): number; + getSnapToPiexl(): boolean; + + setOpacity(opacity: number): void; + setRotation(rotation: number): void; + setScale(scale: number): void; + } + + interface GeometryFunction { + (feature: Feature): ol.geom.Geometry + } + + class RegularShape { + } + + class Stroke { + constructor(opts?: olx.style.StrokeOptions); + getColor(): ol.Color | string; + getLineCap(): string; + getLineDash(): number[]; + getLineJoin(): string; + getMitterLimit(): number; + getWidth(): number; + setColor(color: ol.Color | string): void; + setLineCap(lineCap: string): void; + setLineDash(lineDash: number[]): void; + setLineJoin(lineJoin: string): void; + setMiterLimit(miterLimit: number): void; + setWidth(width: number): void; + } + + /** + * Container for vector feature rendering styles. Any changes made to the style + * or its children through `set*()` methods will not take effect until the + * feature, layer or FeatureOverlay that uses the style is re-rendered. + */ + class Style { + constructor(opts: olx.style.StyleOptions); + + getFill(): ol.style.Fill; + /*** + * Get the geometry to be rendered. + * @return Feature property or geometry or function that returns the geometry that will + * be rendered with this style. + */ + getGeometry(): string | ol.geom.Geometry | ol.style.GeometryFunction; + getGeometryFunction(): ol.style.GeometryFunction; + getImage(): ol.style.Image; + getStroke(): ol.style.Stroke; + getText(): ol.style.Text; + getZIndex(): number; + + setGeometry(geometry: string | ol.geom.Geometry | ol.style.GeometryFunction): void; + setZIndex(zIndex: number): void; + } + + /** + * Set text style for vector features. + */ + class Text { + constructor(opt?: olx.style.TextOptions); + + getFont(): string; + getOffsetX(): number; + getOffsetY(): number; + getFill(): Fill; + getRotation(): number; + getScale(): number; + getStroke(): Stroke; + getText(): string; + getTextAlign(): string; + getTextBaseline(): string; + + /** + * Set the font. + */ + setFont(font: string): void; + + /** + * Set the x offset. + */ + setOffsetX(offsetX: number): void; + + /** + * Set the y offset. + */ + setOffsetY(offsetY: number): void; + + /** + * Set the fill. + */ + setFill(fill: Fill): void; + + /** + * Set the rotation. + */ + setRotation(rotation: number): void; + + /** + * Set the scale. + */ + setScale(scale: number): void; + + /** + * Set the stroke. + * + */ + setStroke(stroke: Stroke): void; + + /** + * Set the text. + */ + setText(text: string): void; + + /** + * Set the text alignment. + */ + setTextAlign(textAlign: string): void; + + /** + * Set the text baseline. + */ + setTextBaseline(textBaseline: string): void; + } + + /** + * A function that takes an ol.Feature and a {number} representing the view's resolution. The function should return an array of ol.style.Style. This way e.g. a vector layer can be styled. + */ + interface StyleFunction { (feature: ol.Feature, resolution: number): ol.style.Style } + } + + namespace tilegrid { + + /** + * Base class for setting the grid pattern for sources accessing tiled-image servers. + */ + class TileGrid { + + /** + * @constructor + * @param options Tile grid options + */ + constructor(options: olx.tilegrid.TileGridOptions); + + /** + * Creates a TileCoord transform function for use with this tile grid. Transforms the internal tile coordinates with bottom-left origin to the tile coordinates used by the ol.TileUrlFunction. The returned function expects an ol.TileCoord as first and an ol.proj.Projection as second argument and returns a transformed ol.TileCoord. + */ + createTileCoordTransform(): { (tilecoord: ol.TileCoord, projection: ol.proj.Projection): ol.TileCoord }; + + /** + * Get the maximum zoom level for the grid. + * @returns Max zoom + */ + getMaxZoom(): number; + + /** + * Get the minimum zoom level for the grid. + * @returns Min zoom + */ + getMinZoom(): number; + + /** + * Get the origin for the grid at the given zoom level. + * @param z Z + * @returns Origin + */ + getOrigin(z: number): ol.Coordinate; + + /** + * Get the list of resolutions for the tile grid. + * @param z Z + * @returns Resolution + */ + getResolution(z: number): number; + + /** + * Get the list of resolutions for the tile grid. + * @returns Resolutions + */ + getResolutions(): Array; + + /** + * Get the tile coordinate for the given map coordinate and resolution. This method considers that coordinates that intersect tile boundaries should be assigned the higher tile coordinate. + * @param coordinate Coordinate + * @param resolution Resolution + * @param tileCoord Destination ol.TileCoord object. + * @returns Tile coordinate + */ + getTileCoordForCoordAndResolution(coordinate: ol.Coordinate, resolution: number, tileCoord?: ol.TileCoord): ol.TileCoord; + + /** + * Get a tile coordinate given a map coordinate and zoom level. + * @param coordinate Coordinate + * @param z Zoom level + * @param tileCoord Destination ol.TileCoord object + * @returns Tile coordinate + */ + getTileCoordForCoordAndZ(coordinate: ol.Coordinate, z: number, tileCoord?: ol.TileCoord): ol.TileCoord; + + /** + * Get the tile size for a zoom level. The type of the return value matches the tileSize or tileSizes that the tile grid was configured with. To always get an ol.Size, run the result through ol.size.toSize(). + * @param z Z + * @returns Tile size + */ + getTileSize(z: number): number | ol.Size; + } + + /** + * Set the grid pattern for sources accessing WMTS tiled-image servers. + */ + class WMTS extends TileGrid { + + /** + * @constructor + * @param options WMTS options + */ + constructor(options: olx.tilegrid.WMTSOptions); + + /** + * Create a tile grid from a WMTS capabilities matrix set. + * @param matrixSet An object representing a matrixSet in the capabilities document. + * @param extent An optional extent to restrict the tile ranges the server provides. + * @returns WMTS tilegrid instance + */ + createFromCapabilitiesMatrixSet(matrixSet: any, extent: ol.Extent): ol.tilegrid.WMTS; + + /** + * Get the list of matrix identifiers. + * @returns MatrixIds + */ + getMatrixIds(): Array; + } + + /** + * Set the grid pattern for sources accessing Zoomify tiled-image servers. + */ + class Zoomify extends TileGrid { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.tilegrid.ZoomifyOptions); + } + + /** + * Creates a tile grid with a standard XYZ tiling scheme. + * @param options Tile grid options. + * @returns The grid instance + */ + function createXYZ(options?: olx.tilegrid.XYZOptions): ol.tilegrid.TileGrid; + } + + namespace webgl { + + class Context { + + /** + * @constructor + * @param canvas HTML Canvas Element + * @param gl WebGL Rendering context + */ + constructor(canvas: HTMLCanvasElement, gl: WebGLRenderingContext); + + /** + Get the WebGL rendering context + @returns The rendering context. + */ + getGL(): WebGLRenderingContext; + + /** + * Get the frame buffer for hit detection. + * @returns The hit detection frame buffer. + */ + getHitDetectionFramebuffer(): WebGLFramebuffer; + + /** + * Use a program. If the program is already in use, this will return false. + * @param program Program. + * @returns Changed. + */ + useProgram(program: WebGLProgram): boolean; + } + } + + // Type definitions + + /** + * A function returning the canvas element ({HTMLCanvasElement}) used by the source as an image. The arguments passed to the function are: ol.Extent the image extent, {number} the image resolution, {number} the device pixel ratio, ol.Size the image size, and ol.proj.Projection the image projection. The canvas returned by this function is cached by the source. The this keyword inside the function references the ol.source.ImageCanvas. + */ + function CanvasFunctionType(extent: Extent, resolution: number, pixelRatio: number, size: Size, projection: proj.Projection): HTMLCanvasElement; + + /** + * A color represented as a short array [red, green, blue, alpha]. red, green, and blue should be integers in the range 0..255 inclusive. alpha should be a float in the range 0..1 inclusive. + */ + interface Color extends Array { } + + /** + * An array of numbers representing an xy coordinate. Example: [16, 48]. + */ + interface Coordinate extends Array { } + + /** + * An array of numbers representing an extent: [minx, miny, maxx, maxy]. + */ + interface Extent extends Array { } + + /** + * Overlay position: 'bottom-left', 'bottom-center', 'bottom-right', 'center-left', 'center-center', 'center-right', 'top-left', 'top-center', 'top-right' + */ + interface OverlayPositioning extends String { } + + /** + * An array with two elements, representing a pixel. The first element is the x-coordinate, the second the y-coordinate of the pixel. + */ + interface Pixel extends Array { } + + /** + * Available renderers: 'canvas', 'dom' or 'webgl'. + */ + interface RendererType extends String { } + + /** + * An array of numbers representing a size: [width, height]. + */ + interface Size extends Array { } + + /** + * An array of three numbers representing the location of a tile in a tile grid. The order is z, x, and y. z is the zoom level. + */ + interface TileCoord extends Array { } + + // Functions + + /** + * A function that takes a ol.Coordinate and transforms it into a {string}. + */ + interface CoordinateFormatType { (coordinate?: Coordinate): string; } + + /** + * Implementation based on the code of OpenLayers, no documentation available (yet). If it is incorrect, please create an issue and I will change it. + */ + interface FeatureLoader { (extent: ol.Extent, number: number, projection: ol.proj.Projection): string } + + /** + * A function that returns a style given a resolution. The this keyword inside the function references the ol.Feature to be styled. + */ + interface FeatureStyleFunction { (resolution: number): ol.style.Style } + + /** + * Loading strategy + */ + interface LoadingStrategy { (extent: ol.Extent, resolution: number): Array } + + /** + * Function to perform manipulations before rendering. This function is called with the ol.Map as first and an optional olx.FrameState as second argument. Return true to keep this function for the next frame, false to remove it. + */ + interface PreRenderFunction { (map: ol.Map, frameState?: olx.FrameState): boolean } + + /** + * A transform function accepts an array of input coordinate values, an optional output array, and an optional dimension (default should be 2). The function transforms the input coordinate values, populates the output array, and returns the output array. + */ + interface TransformFunction { (input: Array, output?: Array, dimension?: number): Array } +} + +declare module "openlayers" { + export = ol; +} diff --git a/openlayers/openlayers-tests.ts b/openlayers/openlayers-tests.ts index 4937d52516..5c1f6d46c8 100644 --- a/openlayers/openlayers-tests.ts +++ b/openlayers/openlayers-tests.ts @@ -1,11 +1,17 @@ -/// +/// // Basic type variables for test functions +var anyValue: any; var voidValue: void; var numberValue: number; var booleanValue: boolean; var stringValue: string; +var stringArray: Array; var jsonValue: JSON; +var voidOrBooleanValue: void | boolean; +var domEventTarget: EventTarget; +var fn: Function; +var object: Object; // Callback predefinitions for OpenLayers var preRenderFunction: ol.PreRenderFunction; @@ -14,44 +20,55 @@ var coordinateFormatType: ol.CoordinateFormatType; var featureStyleFunction: ol.FeatureStyleFunction; var featureLoader: ol.FeatureLoader; var easingFunction: (t: number) => number; +var drawGeometryFunction: ol.DrawGeometryFunctionType; // Type variables for OpenLayers +var attribution: ol.Attribution; +var boundingCoordinates: Array; var circle: ol.geom.Circle; var color: ol.Color; var coordinate: ol.Coordinate; var coordinatesArray: Array; var coordinatesArrayDim2: Array>; var extent: ol.Extent; -var boundingCoordinates: Array; -var size: ol.Size; -var style: ol.style.Style; -var styleArray: Array; -var feature: ol.Feature; -var featureArray: Array; -var graticule: ol.Graticule -var geometry: ol.geom.Geometry; -var geometriesArray: Array; +var olEvent: ol.events.Event; +var eventKey: ol.EventsKey; +var eventKeyArray: Array; +var eventKeyMixed: ol.EventsKey | Array; +var eventTarget: ol.events.EventTarget; var feature: ol.Feature; var featureArray: Array; +var featureCollection: ol.Collection; var featureFormat: ol.format.Feature; +var featureUrlFunction: ol.FeatureUrlFunction; +var graticule: ol.Graticule; +var geometriesArray: Array; var geometry: ol.geom.Geometry; var geometryCollection: ol.geom.GeometryCollection; var geometryLayout: ol.geom.GeometryLayout; var geometryType: ol.geom.GeometryType; var linearRing: ol.geom.LinearRing; var lineString: ol.geom.LineString; -var loadingstrategy: ol.LoadingStrategy; +var loadingStrategy: ol.LoadingStrategy; +var logoOptions: olx.LogoOptions; +var mapBrowserEvent: ol.MapBrowserEvent; var multiLineString: ol.geom.MultiLineString; var multiPoint: ol.geom.MultiPoint; var multiPolygon: ol.geom.MultiPolygon; var point: ol.geom.Point; var polygon: ol.geom.Polygon; -var simpleGeometry: ol.geom.SimpleGeometry; -var tilegrid: ol.tilegrid.TileGrid; -var vector: ol.source.Vector; var projection: ol.proj.Projection; -var projectionLike: ol.proj.ProjectionLike; +var projectionLike: ol.ProjectionLike; +var simpleGeometry: ol.geom.SimpleGeometry; +var size: ol.Size; +var style: ol.style.Style; +var styleArray: Array; +var styleFunction: ol.StyleFunction; +var tilegrid: ol.tilegrid.TileGrid; var transformFn: ol.TransformFunction; +var vectorSource: ol.source.Vector; +var units: ol.proj.Units; +var styleRegularShape: ol.style.RegularShape; // // ol.Attribution @@ -116,16 +133,16 @@ featureLoader = ol.featureloader.xhr(stringValue, featureFormat); // // ol.loadingstrategy // -loadingstrategy = ol.loadingstrategy.all; -loadingstrategy = ol.loadingstrategy.bbox; -loadingstrategy = ol.loadingstrategy.tile(tilegrid); +loadingStrategy = ol.loadingstrategy.all; +loadingStrategy = ol.loadingstrategy.bbox; +loadingStrategy = ol.loadingstrategy.tile(tilegrid); // // // ol.geom.Circle // booleanValue = circle.intersectsExtent(extent); -circle = circle.transform(projectionLike, projectionLike); +circle = circle.transform(projectionLike, projectionLike); // // @@ -136,7 +153,7 @@ coordinate = geometryResult.getClosestPoint(coordinate); geometryResult.getClosestPoint(coordinate, coordinate); extent = geometryResult.getExtent(); geometryResult.getExtent(extent); -geometryResult.transform(projection, projection); +geometryResult.transform(projectionLike, projectionLike); // // @@ -266,6 +283,10 @@ polygon = new ol.geom.Polygon(coordinatesArrayDim2); polygon = new ol.geom.Polygon(coordinatesArrayDim2, geometryLayout); polygon = ol.geom.Polygon.circular(localSphere, coordinate, numberValue); polygon = ol.geom.Polygon.circular(localSphere, coordinate, numberValue, numberValue); +polygon = ol.geom.Polygon.fromCircle(circle); +polygon = ol.geom.Polygon.fromCircle(circle, numberValue); +polygon = ol.geom.Polygon.fromCircle(circle, numberValue, numberValue); +polygon = ol.geom.Polygon.fromExtent(extent); voidValue = polygon.appendLinearRing(linearRing); polygon = polygon.clone(); numberValue = polygon.getArea(); @@ -273,9 +294,12 @@ coordinatesArrayDim2 = polygon.getCoordinates(); coordinatesArrayDim2 = polygon.getCoordinates(booleanValue); point = polygon.getInteriorPoint(); linearRing = polygon.getLinearRing(numberValue); +numberValue = polygon.getLinearRingCount(); linearRingsArray = polygon.getLinearRings(); geometryType = polygon.getType(); booleanValue = polygon.intersectsExtent(extent); +voidValue = polygon.setCoordinates([[coordinate]]); +voidValue = polygon.setCoordinates([[coordinate]], geometryLayout); // // @@ -290,9 +314,42 @@ voidValue = simpleGeometry.translate(numberValue, numberValue); // // ol.source // -vector = new ol.source.Vector({ - features: [feature] +var featureCallback: (f: ol.Feature) => any; +vectorSource = new ol.source.Vector({ + attributions: [attribution], + features: featureCollection, + format: featureFormat, + loader: featureLoader, + logo: logoOptions, + strategy: loadingStrategy, + url: stringValue, + useSpatialIndex: booleanValue, + wrapX: booleanValue }); +vectorSource = new ol.source.Vector({ + features: featureArray +}); +vectorSource = new ol.source.Vector({ + url: featureUrlFunction, + loader: featureLoader +}); +voidValue = vectorSource.addFeature(feature); +voidValue = vectorSource.addFeatures(featureArray); +voidValue = vectorSource.clear(); +voidValue = vectorSource.clear(booleanValue); +anyValue = vectorSource.forEachFeature(featureCallback); +anyValue = vectorSource.forEachFeature(featureCallback, object); +anyValue = vectorSource.forEachFeatureInExtent(extent, featureCallback, object); +anyValue = vectorSource.forEachFeatureIntersectingExtent(extent, featureCallback, object); +feature = vectorSource.getClosestFeatureToCoordinate(coordinate); +extent = vectorSource.getExtent(); +feature = vectorSource.getFeatureById(stringValue); +feature = vectorSource.getFeatureById(numberValue); +featureArray = vectorSource.getFeatures(); +featureArray = vectorSource.getFeaturesAtCoordinate(coordinate); +featureCollection = vectorSource.getFeaturesCollection(); +featureArray = vectorSource.getFeaturesInExtent(extent); +voidValue = vectorSource.removeFeature(feature); // // ol.Feature @@ -300,7 +357,11 @@ vector = new ol.source.Vector({ feature = new ol.Feature(); feature = new ol.Feature(geometry); feature = new ol.Feature({ - geometry: geometry + geometry: geometry, + a: numberValue, + b: stringValue, + c: null, + d: object }); feature = feature.clone(); geometry = feature.getGeometry(); @@ -315,6 +376,7 @@ voidValue = feature.setId(numberValue); voidValue = feature.setStyle(style); voidValue = feature.setStyle(styleArray); voidValue = feature.setStyle(featureStyleFunction); +voidValue = feature.setProperties(object); // // ol.View @@ -329,19 +391,71 @@ var view: ol.View = new ol.View({ // ol.layer.Tile // var tileLayer: ol.layer.Tile = new ol.layer.Tile({ - source: new ol.source.MapQuest({ layer: 'osm' }) + source: new ol.source.OSM() }); +// +// ol.Object +// +var olObject: ol.Object = new ol.Object({ + a: numberValue, + b: stringValue, + c: booleanValue, + d: voidValue, + e: object, + f: fn +}); +anyValue = olObject.get(stringValue); +stringArray = olObject.getKeys(); +object = olObject.getProperties(); +voidValue = olObject.set(stringValue, anyValue); +voidValue = olObject.set(stringValue, anyValue, booleanValue); +voidValue = olObject.setProperties(object, booleanValue); +voidValue = olObject.unset(stringValue, booleanValue); + +// +// ol.Observable +// +ol.Observable.unByKey(eventKey); +var observable: ol.Observable = new ol.Observable(); +voidValue = observable.changed(); +voidOrBooleanValue = observable.dispatchEvent({type: stringValue}); +voidOrBooleanValue = observable.dispatchEvent({type: stringValue, target: domEventTarget}); +voidOrBooleanValue = observable.dispatchEvent({type: stringValue, target: eventTarget}); +voidOrBooleanValue = observable.dispatchEvent({type: stringValue, a: numberValue, b: stringValue, c: booleanValue, d: null, e: {}}); +voidOrBooleanValue = observable.dispatchEvent(olEvent); +voidOrBooleanValue = observable.dispatchEvent(stringValue); +numberValue = observable.getRevision(); +eventKeyMixed = observable.on(stringValue, fn); +eventKeyMixed = observable.on([stringValue, stringValue], fn, {}); +eventKeyMixed = observable.once(stringValue, fn); +eventKeyMixed = observable.once([stringValue, stringValue], fn, {}); +voidValue = observable.un(stringValue, fn); +voidValue = observable.un([stringValue, stringValue], fn, {}); +voidValue = observable.unByKey(eventKey); +voidValue = observable.unByKey(eventKeyArray); + // // ol.proj // +var getPointResolutionFn: (n: number, c: ol.Coordinate) => number; projection = new ol.proj.Projection({ - code:stringValue, + code:stringValue, }); -projection.setExtent(projection.getExtent()); +stringValue = projection.getCode(); +extent = projection.getExtent(); +numberValue = projection.getMetersPerUnit(); +numberValue = projection.getPointResolution(numberValue, coordinate); +units = projection.getUnits(); +extent = projection.getWorldExtent(); +booleanValue = projection.isGlobal(); +voidValue = projection.setExtent(extent); +voidValue = projection.setGetPointResolution(getPointResolutionFn); +voidValue = projection.setGlobal(booleanValue); +voidValue = projection.setWorldExtent(extent); // -// ol.Map +// ol.Map // var map: ol.Map = new ol.Map({ @@ -349,12 +463,14 @@ var map: ol.Map = new ol.Map({ layers: [tileLayer], target: stringValue }); -map.beforeRender(preRenderFunction); +voidValue = map.beforeRender(preRenderFunction); // // ol.source.ImageWMS // var imageWMS: ol.source.ImageWMS = new ol.source.ImageWMS({ + params: {}, + projection: projection, serverType: stringValue, url:stringValue }); @@ -363,7 +479,6 @@ var imageWMS: ol.source.ImageWMS = new ol.source.ImageWMS({ // ol.source.Source // const source = imageWMS as ol.source.Source; -voidValue = source.refresh(); projection = source.getProjection(); // @@ -371,22 +486,27 @@ projection = source.getProjection(); // var tileWMS: ol.source.TileWMS = new ol.source.TileWMS({ params: {}, + projection: projection, serverType: stringValue, url:stringValue }); -tileWMS.updateParams(tileWMS.getParams()); +voidValue = tileWMS.updateParams(tileWMS.getParams()); stringValue = tileWMS.getGetFeatureInfoUrl([0, 0], 1, "EPSG:4326", {}); // // ol.source.WMTS // var wmts: ol.source.WMTS = new ol.source.WMTS({ - tileGrid: new ol.tilegrid.WMTS({}), - layer: "", - style: "", - matrixSet: "", - wrapX: true + layer: "", + projection: projection, + matrixSet: "", + style: "", + tileGrid: new ol.tilegrid.WMTS({ + matrixIds: [], + resolutions: [], + }), + wrapX: true, }); // @@ -420,7 +540,7 @@ zoomOptions.start = numberValue; zoomOptions.resolution = numberValue; zoomOptions.easing = easingFunction; preRenderFunction = ol.animation.zoom(zoomOptions); -map.beforeRender(preRenderFunction); +voidValue = map.beforeRender(preRenderFunction); // // ol.coordinate @@ -433,6 +553,7 @@ stringValue = ol.coordinate.format(coordinate, stringValue, numberValue); coordinate = ol.coordinate.rotate(coordinate, numberValue); stringValue = ol.coordinate.toStringHDMS(); stringValue = ol.coordinate.toStringHDMS(coordinate); +stringValue = ol.coordinate.toStringHDMS(coordinate, numberValue); stringValue = ol.coordinate.toStringXY(); stringValue = ol.coordinate.toStringXY(coordinate); stringValue = ol.coordinate.toStringXY(coordinate, numberValue); @@ -452,9 +573,7 @@ easingFunction = ol.easing.upAndDown; var geolocation: ol.Geolocation = new ol.Geolocation({ projection: projection }); -geolocation.on('change', function (evt) { - window.console.log(geolocation.getPosition()); -}); +coordinate = geolocation.getPosition(); // // ol.Graticule @@ -467,7 +586,7 @@ graticule = new ol.Graticule({ var graticuleMap: ol.Map = graticule.getMap(); var graticuleMeridians: Array = graticule.getMeridians(); var graticuleParallels: Array = graticule.getParallels(); -graticule.setMap(graticuleMap); +voidValue = graticule.setMap(graticuleMap); // // ol.DeviceOrientation @@ -476,9 +595,7 @@ graticule.setMap(graticuleMap); var deviceOrientation: ol.DeviceOrientation = new ol.DeviceOrientation({ tracking: true, }); -deviceOrientation.on('change', function (evt) { - window.console.log(deviceOrientation.getHeading()); -}); +numberValue = deviceOrientation.getHeading(); // // ol.Overlay @@ -487,17 +604,17 @@ deviceOrientation.on('change', function (evt) { var popup: ol.Overlay = new ol.Overlay({ element: document.getElementById('popup') }); -map.addOverlay(popup); +voidValue = map.addOverlay(popup); var popupElement: Element = popup.getElement(); var popupMap: ol.Map = popup.getMap(); var popupOffset: Array = popup.getOffset(); coordinate = popup.getPosition(); var popupPositioning: ol.OverlayPositioning = popup.getPositioning(); -popup.setElement(popupElement); -popup.setMap(popupMap); -popup.setOffset(popupOffset); -popup.setPosition(coordinate); -popup.setPositioning(popupPositioning); +voidValue = popup.setElement(popupElement); +voidValue = popup.setMap(popupMap); +voidValue = popup.setOffset(popupOffset); +voidValue = popup.setPosition(coordinate); +voidValue = popup.setPositioning(popupPositioning); // @@ -555,9 +672,76 @@ var modify: ol.interaction.Modify = new ol.interaction.Modify({ }); var draw: ol.interaction.Draw = new ol.interaction.Draw({ - type: "Point" -}) + type: "Point", + clickTolerance: numberValue, + features: new ol.Collection([]), + source: vectorSource, + snapTolerance: numberValue, + maxPoints: numberValue, + minPoints: numberValue, + style: style, + geometryFunction: drawGeometryFunction, + geometryName: stringValue, + condition: ol.events.condition.never, + freehandCondition: ol.events.condition.never, + wrapX: booleanValue +}); +draw = new ol.interaction.Draw({ + type: "Point", + style: styleArray +}); +draw = new ol.interaction.Draw({ + type: "Point", + style: styleFunction +}); +var styleFunctionAsStyle = function(feature: ol.Feature, resolution: number): ol.style.Style { return style; } +draw = new ol.interaction.Draw({ + type: "Point", + style: styleFunctionAsStyle +}); +var styleFunctionAsArray = function(feature: ol.Feature, resolution: number): ol.style.Style[] { return styleArray; } +draw = new ol.interaction.Draw({ + type: "Point", + style: styleFunctionAsArray +}); + +var dragbox: ol.interaction.DragBox = new ol.interaction.DragBox({ + className: stringValue, + condition: ol.events.condition.always, + boxEndCondition: function (mapBrowserEvent: ol.MapBrowserEvent, startPixel: ol.Pixel, endPixel: ol.Pixel) { + var width: number = endPixel[0] - startPixel[0]; + var height: number = endPixel[1] - startPixel[1]; + return booleanValue; + } +}); +polygon = dragbox.getGeometry(); + +var interaction: ol.interaction.Interaction = new ol.interaction.Interaction({ + handleEvent: function (e: ol.MapBrowserEvent) { + return booleanValue; + } +}); +booleanValue = interaction.getActive(); +map = interaction.getMap(); +voidValue = interaction.setActive(true); + + const select: ol.interaction.Select = new ol.interaction.Select({ layers: (layer: ol.layer.Layer) => true, }); + +// +// ol.style.RegularShape +// + +styleRegularShape = new ol.style.RegularShape({ + fill: new ol.style.Fill({color: 'red'}), + points: 4, +}); + +// +// ol.proj +// + +let value = ol.proj.METERS_PER_UNIT['degrees']; diff --git a/openlayers/openlayers.d.ts b/openlayers/openlayers.d.ts index 36026fa70d..ed3c8e9e21 100644 --- a/openlayers/openlayers.d.ts +++ b/openlayers/openlayers.d.ts @@ -1,1265 +1,13443 @@ // Type definitions for OpenLayers v3.18.2 // Project: http://openlayers.org/ -// Definitions by: Wouter Goedhart +// Definitions by: Olivier Sechet // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions partially generated using tsd-jsdoc (https://github.com/englercj/tsd-jsdoc) -declare namespace olx { - interface StaticImageOptions { +declare type GlobalObject = Object; - /** Attributions */ - attributions?: Array - - /*** The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail. */ - crossOrigin?: string - - /*** Extent of the image in map coordinates. This is the [left, bottom, right, top] map coordinates of your image.*/ - imageExtent: ol.Extent; - - /*** Size of the image in pixels.*/ - imageSize?: ol.Size; - - /*** experimental Optional function to load an image given a URL.*/ - imageLoadFunction?: ol.TileLoadFunctionType; - - /*** Optional logo.*/ - logo?: olx.LogoOptions; - - /*** experimental Projection.*/ - projection: ol.proj.Projection; - - /*** Image URL.*/ - url: string; - } - - interface ZoomToExtentOptions { - /*** Class name. Default is ol-zoom-extent.*/ - className?: string; - - /*** Target.*/ - target?: Element; - - /*** Text label to use for the button. Default is E. Instead of text, also a Node (e.g. a span element) can be used.*/ - label?: string | Node; - - /*** Text label to use for the button tip. Default is Zoom to extent.*/ - tipLabel?: string; - - /*** The extent to zoom to. If undefined the validity extent of the view projection is used.*/ - extent: ol.Extent; - } - - interface OverviewMapOptions { - /*** Whether the control should start collapsed or not (expanded). Default to true.*/ - collapsed?: boolean; - /*** Text label to use for the expanded overviewmap button. Default is «. Instead of text, also a Node (e.g. a span element) can be used.*/ - collapseLabel? :string | Node; - /*** Whether the control can be collapsed or not. Default to true.*/ - collapsible?: boolean; - /*** Text label to use for the collapsed overviewmap button. Default is ». Instead of text, also a Node (e.g. a span element) can be used.*/ - label?: string | Node; - /*** Layers for the overview map. If not set, then all main map layers are used instead.*/ - layers?: ol.layer.Layer[] | ol.Collection; - /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ - render?: Function; - /*** Specify a target if you want the control to be rendered outside of the map's viewport.*/ - target?: Element; - /*** Text label to use for the button tip. Default is Overview map*/ - tipLabel?: string; - /*** Custom view for the overview map. If not provided, a default view with an EPSG:3857 projection will be used.*/ - view?: ol.View; - } - - interface RotateOptions { - /*** CSS class name. Default is ol-rotate.*/ - className?: string; - /*** Text label to use for the rotate button. Default is ⇧. Instead of text, also a Node (e.g. a span element) can be used.*/ - label?: string | Element; - /*** Text label to use for the rotate tip. Default is Reset rotation.*/ - tipLabel?: string; - /*** Animation duration in milliseconds. Default is 250.*/ - duration?: number; - /*** Hide the control when rotation is 0. Default is true.*/ - autoHide?: boolean; - /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ - render?: Function; - /*** Function called when the control is clicked. This will override the default resetNorth.*/ - resetNorth?: Function; - /*** Target.*/ - target?: Element; - } - - interface AttributionControlOptions { - /*** CSS class name. Default is ol-attribution.*/ - className?: string; - /*** Target.*/ - target?: Element; +/** + * @namespace ol + */ +declare module ol { + /** + * The animation static methods are designed to be used with the + * {@link ol.Map#beforeRender} method. For example: + * + * var map = new ol.Map({ ... }); + * var zoom = ol.animation.zoom({ + * resolution: map.getView().getResolution() + * }); + * map.beforeRender(zoom); + * map.getView().setResolution(map.getView().getResolution() * 2); + * + * @namespace ol.animation + */ + module animation { /** - * Specify if attributions can be collapsed. If you use an OSM source, - * should be set to false — see OSM Copyright — Default is true. + * Generate an animated transition that will "bounce" the resolution as it + * approaches the final value. + * @param {olx.animation.BounceOptions} options Bounce options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api */ - collapsible?: boolean; - /*** Specify if attributions should be collapsed at startup. Default is true.*/ - collapsed?: boolean; - /*** Text label to use for the button tip. Default is "Attributions".*/ - tipLabel?: Array | ol.Collection; + function bounce(options: olx.animation.BounceOptions): ol.PreRenderFunction; + /** - * Text label to use for the collapsed attributions button. Default is i. - * Instead of text, also a Node (e.g. a span element) can be used. + * Generate an animated transition while updating the view center. + * @param {olx.animation.PanOptions} options Pan options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api */ - label?: string | Node; + function pan(options: olx.animation.PanOptions): ol.PreRenderFunction; + /** - * Text label to use for the expanded attributions button. Default is ». - * Instead of text, also a Node (e.g. a span element) can be used. + * Generate an animated transition while updating the view rotation. + * @param {olx.animation.RotateOptions} options Rotate options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api */ - collapseLabel?: string | Node; - /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ - render?: Function; + function rotate(options: olx.animation.RotateOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view resolution. + * @param {olx.animation.ZoomOptions} options Zoom options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function zoom(options: olx.animation.ZoomOptions): ol.PreRenderFunction; + } - interface AttributionOptions { - - /** HTML markup for this attribution. */ - html: string; - } - - interface DeviceOrientationOptions { - + /** + * Error object thrown when an assertion failed. This is an ECMA-262 Error, + * extended with a `code` property. + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} + * @constructor + * @extends {Error} + * @implements {oli.AssertionError} + * @param {number} code Error code. + */ + class AssertionError extends Error { /** - * Start tracking. Default is false. + * Error object thrown when an assertion failed. This is an ECMA-262 Error, + * extended with a `code` property. + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} + * @constructor + * @extends {Error} + * @implements {oli.AssertionError} + * @param {number} code Error code. */ - tracking?: boolean; - } - - interface FrameState { + constructor(code: number); /** + * Error code. The meaning of the code can be found on + * {@link http://openlayers.org/en/latest/errors.html} (replace `latest` with + * the version found in the OpenLayers script's header comment if a version + * other than the latest is used). + * @type {number} + * @api + */ + code: number; + + } + + /** + * @classdesc + * An attribution for a layer source. + * + * Example: + * + * source: new ol.source.OSM({ + * attributions: [ + * new ol.Attribution({ + * html: 'All maps © ' + + * 'OpenCycleMap' + * }), + * ol.source.OSM.ATTRIBUTION + * ], + * .. + * + * @constructor + * @param {olx.AttributionOptions} options Attribution options. + * @struct + * @api stable + */ + class Attribution { + /** + * @classdesc + * An attribution for a layer source. * + * Example: + * + * source: new ol.source.OSM({ + * attributions: [ + * new ol.Attribution({ + * html: 'All maps © ' + + * 'OpenCycleMap' + * }), + * ol.source.OSM.ATTRIBUTION + * ], + * .. + * + * @constructor + * @param {olx.AttributionOptions} options Attribution options. + * @struct + * @api stable */ - pixelRatio: number; + constructor(options: olx.AttributionOptions); /** - * + * Get the attribution markup. + * @return {string} The attribution HTML. + * @api stable */ - time: number; + getHTML(): string; - /** - * - */ - viewState: olx.ViewState; } - interface FeatureOverlayOptions { - + /** + * @classdesc + * An expanded version of standard JS Array, adding convenience methods for + * manipulation. Add and remove changes to the Collection trigger a Collection + * event. Note that this does not cover changes to the objects _within_ the + * Collection; they trigger events on the appropriate object, not on the + * Collection as a whole. + * + * @constructor + * @extends {ol.Object} + * @fires ol.Collection.Event + * @param {!Array.=} opt_array Array. + * @template T + * @api stable + */ + class Collection extends ol.Object { /** - * Features + * @classdesc + * An expanded version of standard JS Array, adding convenience methods for + * manipulation. Add and remove changes to the Collection trigger a Collection + * event. Note that this does not cover changes to the objects _within_ the + * Collection; they trigger events on the appropriate object, not on the + * Collection as a whole. + * + * @constructor + * @extends {ol.Object} + * @fires ol.Collection.Event + * @param {!Array.=} opt_array Array. + * @template T + * @api stable */ - features?: Array | ol.Collection | ol.style.StyleFunction; + constructor(opt_array?: T[]); /** - * Map + * Remove all elements from the collection. + * @api stable + */ + clear(): void; + + /** + * Add elements to the collection. This pushes each item in the provided array + * to the end of the collection. + * @param {!Array.} arr Array. + * @return {ol.Collection.} This collection. + * @api stable + */ + extend(arr: T[]): ol.Collection; + + /** + * Iterate over each element, calling the provided callback. + * @param {function(this: S, T, number, Array.): *} f The function to call + * for every element. This function takes 3 arguments (the element, the + * index and the array). The return value is ignored. + * @param {S=} opt_this The object to use as `this` in `f`. + * @template S + * @api stable + */ + forEach(f: ((self: S, item: T, index: number, array: T[]) => any), opt_this?: S): void; + + /** + * Get a reference to the underlying Array object. Warning: if the array + * is mutated, no events will be dispatched by the collection, and the + * collection's "length" property won't be in sync with the actual length + * of the array. + * @return {!Array.} Array. + * @api stable + */ + getArray(): T[]; + + /** + * Get the element at the provided index. + * @param {number} index Index. + * @return {T} Element. + * @api stable + */ + item(index: number): T; + + /** + * Get the length of this collection. + * @return {number} The length of the array. + * @observable + * @api stable + */ + getLength(): number; + + /** + * Insert an element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api stable + */ + insertAt(index: number, elem: T): void; + + /** + * Remove the last element of the collection and return it. + * Return `undefined` if the collection is empty. + * @return {T|undefined} Element. + * @api stable + */ + pop(): (T); + + /** + * Insert the provided element at the end of the collection. + * @param {T} elem Element. + * @return {number} Length. + * @api stable + */ + push(elem: T): number; + + /** + * Remove the first occurrence of an element from the collection. + * @param {T} elem Element. + * @return {T|undefined} The removed element or undefined if none found. + * @api stable + */ + remove(elem: T): (T); + + /** + * Remove the element at the provided index and return it. + * Return `undefined` if the collection does not contain this index. + * @param {number} index Index. + * @return {T|undefined} Value. + * @api stable + */ + removeAt(index: number): (T); + + /** + * Set the element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api stable + */ + setAt(index: number, elem: T): void; + + } + + module Collection { + + type EventType = string; + + /** + * @classdesc + * Events emitted by {@link ol.Collection} instances are instances of this + * type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.Collection.Event} + * @param {ol.Collection.EventType} type Type. + * @param {*=} opt_element Element. + */ + class Event extends ol.events.Event { + /** + * @classdesc + * Events emitted by {@link ol.Collection} instances are instances of this + * type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.Collection.Event} + * @param {ol.Collection.EventType} type Type. + * @param {*=} opt_element Element. + */ + constructor(type: ol.Collection.EventType, opt_element?: any); + + /** + * The element that is added to or removed from the collection. + * @type {*} + * @api stable + */ + element: any; + + } + } + + /** + * Colors can be defined as a {@link ol.Color} array, or as strings in + * `rgb(r,g,b)` or `rgba(r,g,b,a)` format, or in hex `#rrggbb` or `#rgb` format. + * Color names, like 'red', 'blue' or 'green', may also be used with the + * Canvas renderer. + * + * @namespace ol.color + */ + module color { + /** + * Return the color as an array. This function maintains a cache of calculated + * arrays which means the result should not be modified. + * @param {ol.Color|string} color Color. + * @return {ol.Color} Color. + * @api + */ + function asArray(color: (ol.Color | string)): ol.Color; + + /** + * Return the color as an rgba string. + * @param {ol.Color|string} color Color. + * @return {string} Rgba string. + * @api + */ + function asString(color: (ol.Color | string)): string; + + } + + /** + * An {@link ol.ColorLike} can be a color, gradient or pattern accepted by + * [CanvasRenderingContext2D.fillStyle](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle). + * @namespace ol.colorlike + */ + module colorlike { + /** + * @param {ol.Color|ol.ColorLike} color Color. + * @return {ol.ColorLike} The color as an ol.ColorLike + * @api + */ + function asColorLike(color: (ol.Color | ol.ColorLike)): ol.ColorLike; + + } + + /** + * @namespace ol.control + */ + module control { + /** + * @classdesc + * Control to show all the attributions associated with the layer sources + * in the map. This control is one of the default controls included in maps. + * By default it will show in the bottom right portion of the map, but this can + * be changed by using a css selector for `.ol-attribution`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.AttributionOptions=} opt_options Attribution options. + * @api stable + */ + class Attribution extends ol.control.Control { + /** + * @classdesc + * Control to show all the attributions associated with the layer sources + * in the map. This control is one of the default controls included in maps. + * By default it will show in the bottom right portion of the map, but this can + * be changed by using a css selector for `.ol-attribution`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.AttributionOptions=} opt_options Attribution options. + * @api stable + */ + constructor(opt_options?: olx.control.AttributionOptions); + + /** + * Update the attribution element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.Attribution} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return `true` if the attribution is collapsible, `false` otherwise. + * @return {boolean} True if the widget is collapsible. + * @api stable + */ + getCollapsible(): boolean; + + /** + * Set whether the attribution should be collapsible. + * @param {boolean} collapsible True if the widget is collapsible. + * @api stable + */ + setCollapsible(collapsible: boolean): void; + + /** + * Collapse or expand the attribution according to the passed parameter. Will + * not do anything if the attribution isn't collapsible or if the current + * collapsed state is already the one requested. + * @param {boolean} collapsed True if the widget is collapsed. + * @api stable + */ + setCollapsed(collapsed: boolean): void; + + /** + * Return `true` when the attribution is currently collapsed or `false` + * otherwise. + * @return {boolean} True if the widget is collapsed. + * @api stable + */ + getCollapsed(): boolean; + + } + + /** + * @classdesc + * A control is a visible widget with a DOM element in a fixed position on the + * screen. They can involve user input (buttons), or be informational only; + * the position is determined using CSS. By default these are placed in the + * container with CSS class name `ol-overlaycontainer-stopevent`, but can use + * any outside DOM element. + * + * This is the base class for controls. You can use it for simple custom + * controls by creating the element with listeners, creating an instance: + * ```js + * var myControl = new ol.control.Control({element: myElement}); + * ``` + * and then adding this to the map. + * + * The main advantage of having this as a control rather than a simple separate + * DOM element is that preventing propagation is handled for you. Controls + * will also be `ol.Object`s in a `ol.Collection`, so you can use their + * methods. + * + * You can also extend this base for your own control class. See + * examples/custom-controls for an example of how to do this. + * + * @constructor + * @extends {ol.Object} + * @implements {oli.control.Control} + * @param {olx.control.ControlOptions} options Control options. + * @api stable + */ + class Control extends ol.Object { + /** + * @classdesc + * A control is a visible widget with a DOM element in a fixed position on the + * screen. They can involve user input (buttons), or be informational only; + * the position is determined using CSS. By default these are placed in the + * container with CSS class name `ol-overlaycontainer-stopevent`, but can use + * any outside DOM element. + * + * This is the base class for controls. You can use it for simple custom + * controls by creating the element with listeners, creating an instance: + * ```js + * var myControl = new ol.control.Control({element: myElement}); + * ``` + * and then adding this to the map. + * + * The main advantage of having this as a control rather than a simple separate + * DOM element is that preventing propagation is handled for you. Controls + * will also be `ol.Object`s in a `ol.Collection`, so you can use their + * methods. + * + * You can also extend this base for your own control class. See + * examples/custom-controls for an example of how to do this. + * + * @constructor + * @extends {ol.Object} + * @implements {oli.control.Control} + * @param {olx.control.ControlOptions} options Control options. + * @api stable + */ + constructor(options: olx.control.ControlOptions); + + /** + * Get the map associated with this control. + * @return {ol.Map} Map. + * @api stable + */ + getMap(): ol.Map; + + /** + * Remove the control from its current map and attach it to the new map. + * Subclasses may set up event handlers to get notified about changes to + * the map here. + * @param {ol.Map} map Map. + * @api stable + */ + setMap(map: ol.Map): void; + + /** + * This function is used to set a target element for the control. It has no + * effect if it is called after the control has been added to the map (i.e. + * after `setMap` is called on the control). If no `target` is set in the + * options passed to the control constructor and if `setTarget` is not called + * then the control is added to the map's overlay container. + * @param {Element|string} target Target. + * @api + */ + setTarget(target: (Element | string)): void; + + } + + /** + * @classdesc + * Provides a button that when clicked fills up the full screen with the map. + * The full screen source element is by default the element containing the map viewport unless + * overriden by providing the `source` option. In which case, the dom + * element introduced using this parameter will be displayed in full screen. + * + * When in full screen mode, a close button is shown to exit full screen mode. + * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to + * toggle the map in full screen mode. + * + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.FullScreenOptions=} opt_options Options. + * @api stable + */ + class FullScreen extends ol.control.Control { + /** + * @classdesc + * Provides a button that when clicked fills up the full screen with the map. + * The full screen source element is by default the element containing the map viewport unless + * overriden by providing the `source` option. In which case, the dom + * element introduced using this parameter will be displayed in full screen. + * + * When in full screen mode, a close button is shown to exit full screen mode. + * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to + * toggle the map in full screen mode. + * + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.FullScreenOptions=} opt_options Options. + * @api stable + */ + constructor(opt_options?: olx.control.FullScreenOptions); + + } + + /** + * Set of controls included in maps by default. Unless configured otherwise, + * this returns a collection containing an instance of each of the following + * controls: + * * {@link ol.control.Zoom} + * * {@link ol.control.Rotate} + * * {@link ol.control.Attribution} + * + * @param {olx.control.DefaultsOptions=} opt_options Defaults options. + * @return {ol.Collection.} Controls. + * @api stable + */ + function defaults(opt_options?: olx.control.DefaultsOptions): ol.Collection; + + /** + * @classdesc + * A control to show the 2D coordinates of the mouse cursor. By default, these + * are in the view projection, but can be in any supported projection. + * By default the control is shown in the top right corner of the map, but this + * can be changed by using the css selector `.ol-mouse-position`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.MousePositionOptions=} opt_options Mouse position + * options. + * @api stable + */ + class MousePosition extends ol.control.Control { + /** + * @classdesc + * A control to show the 2D coordinates of the mouse cursor. By default, these + * are in the view projection, but can be in any supported projection. + * By default the control is shown in the top right corner of the map, but this + * can be changed by using the css selector `.ol-mouse-position`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.MousePositionOptions=} opt_options Mouse position + * options. + * @api stable + */ + constructor(opt_options?: olx.control.MousePositionOptions); + + /** + * Update the mouseposition element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.MousePosition} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return the coordinate format type used to render the current position or + * undefined. + * @return {ol.CoordinateFormatType|undefined} The format to render the current + * position in. + * @observable + * @api stable + */ + getCoordinateFormat(): (ol.CoordinateFormatType); + + /** + * Return the projection that is used to report the mouse position. + * @return {ol.proj.Projection|undefined} The projection to report mouse + * position in. + * @observable + * @api stable + */ + getProjection(): (ol.proj.Projection); + + /** + * Set the coordinate format type used to render the current position. + * @param {ol.CoordinateFormatType} format The format to render the current + * position in. + * @observable + * @api stable + */ + setCoordinateFormat(format: ol.CoordinateFormatType): void; + + /** + * Set the projection that is used to report the mouse position. + * @param {ol.proj.Projection} projection The projection to report mouse + * position in. + * @observable + * @api stable + */ + setProjection(projection: ol.proj.Projection): void; + + } + + /** + * Create a new control with a map acting as an overview map for an other + * defined map. + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. + * @api + */ + class OverviewMap extends ol.control.Control { + /** + * Create a new control with a map acting as an overview map for an other + * defined map. + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. + * @api + */ + constructor(opt_options?: olx.control.OverviewMapOptions); + + /** + * Update the overview map element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.OverviewMap} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return `true` if the overview map is collapsible, `false` otherwise. + * @return {boolean} True if the widget is collapsible. + * @api stable + */ + getCollapsible(): boolean; + + /** + * Set whether the overview map should be collapsible. + * @param {boolean} collapsible True if the widget is collapsible. + * @api stable + */ + setCollapsible(collapsible: boolean): void; + + /** + * Collapse or expand the overview map according to the passed parameter. Will + * not do anything if the overview map isn't collapsible or if the current + * collapsed state is already the one requested. + * @param {boolean} collapsed True if the widget is collapsed. + * @api stable + */ + setCollapsed(collapsed: boolean): void; + + /** + * Determine if the overview map is collapsed. + * @return {boolean} The overview map is collapsed. + * @api stable + */ + getCollapsed(): boolean; + + /** + * Return the overview map. + * @return {ol.Map} Overview map. + * @api + */ + getOverviewMap(): ol.Map; + + } + + /** + * @classdesc + * A button control to reset rotation to 0. + * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css + * selector is added to the button when the rotation is 0. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.RotateOptions=} opt_options Rotate options. + * @api stable + */ + class Rotate extends ol.control.Control { + /** + * @classdesc + * A button control to reset rotation to 0. + * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css + * selector is added to the button when the rotation is 0. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.RotateOptions=} opt_options Rotate options. + * @api stable + */ + constructor(opt_options?: olx.control.RotateOptions); + + /** + * Update the rotate control element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.Rotate} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + } + + /** + * @classdesc + * A control displaying rough y-axis distances, calculated for the center of the + * viewport. For conformal projections (e.g. EPSG:3857, the default view + * projection in OpenLayers), the scale is valid for all directions. + * No scale line will be shown when the y-axis distance of a pixel at the + * viewport center cannot be calculated in the view projection. + * By default the scale line will show in the bottom left portion of the map, + * but this can be changed by using the css selector `.ol-scale-line`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ScaleLineOptions=} opt_options Scale line options. + * @api stable + */ + class ScaleLine extends ol.control.Control { + /** + * @classdesc + * A control displaying rough y-axis distances, calculated for the center of the + * viewport. For conformal projections (e.g. EPSG:3857, the default view + * projection in OpenLayers), the scale is valid for all directions. + * No scale line will be shown when the y-axis distance of a pixel at the + * viewport center cannot be calculated in the view projection. + * By default the scale line will show in the bottom left portion of the map, + * but this can be changed by using the css selector `.ol-scale-line`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ScaleLineOptions=} opt_options Scale line options. + * @api stable + */ + constructor(opt_options?: olx.control.ScaleLineOptions); + + /** + * Return the units to use in the scale line. + * @return {ol.control.ScaleLine.Units|undefined} The units to use in the scale + * line. + * @observable + * @api stable + */ + getUnits(): (ol.control.ScaleLine.Units); + + /** + * Update the scale line element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.ScaleLine} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Set the units to use in the scale line. + * @param {ol.control.ScaleLine.Units} units The units to use in the scale line. + * @observable + * @api stable + */ + setUnits(units: ol.control.ScaleLine.Units): void; + } + + module ScaleLine { + /** + * @enum {string} + * @api + */ + type Property = string; + + /** + * Units for the scale line. Supported values are `'degrees'`, `'imperial'`, + * `'nautical'`, `'metric'`, `'us'`. + * @enum {string} + */ + type Units = string; + } + + /** + * @classdesc + * A control with 2 buttons, one for zoom in and one for zoom out. + * This control is one of the default controls of a map. To style this control + * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomOptions=} opt_options Zoom options. + * @api stable + */ + class Zoom extends ol.control.Control { + /** + * @classdesc + * A control with 2 buttons, one for zoom in and one for zoom out. + * This control is one of the default controls of a map. To style this control + * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomOptions=} opt_options Zoom options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomOptions); + + } + + /** + * @classdesc + * A slider type of control for zooming. + * + * Example: + * + * map.addControl(new ol.control.ZoomSlider()); + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. + * @api stable + */ + class ZoomSlider extends ol.control.Control { + /** + * @classdesc + * A slider type of control for zooming. + * + * Example: + * + * map.addControl(new ol.control.ZoomSlider()); + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomSliderOptions); + + /** + * Update the zoomslider element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.ZoomSlider} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + } + + /** + * @classdesc + * A button control which, when pressed, changes the map view to a specific + * extent. To style this control use the css selector `.ol-zoom-extent`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomToExtentOptions=} opt_options Options. + * @api stable + */ + class ZoomToExtent extends ol.control.Control { + /** + * @classdesc + * A button control which, when pressed, changes the map view to a specific + * extent. To style this control use the css selector `.ol-zoom-extent`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomToExtentOptions=} opt_options Options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomToExtentOptions); + + } + + } + + /** + * @namespace ol.coordinate + */ + module coordinate { + /** + * Add `delta` to `coordinate`. `coordinate` is modified in place and returned + * by the function. + * + * Example: + * + * var coord = [7.85, 47.983333]; + * ol.coordinate.add(coord, [-2, 4]); + * // coord is now [5.85, 51.983333] + * + * @param {ol.Coordinate} coordinate Coordinate. + * @param {ol.Coordinate} delta Delta. + * @return {ol.Coordinate} The input coordinate adjusted by the given delta. + * @api stable + */ + function add(coordinate: ol.Coordinate, delta: ol.Coordinate): ol.Coordinate; + + /** + * Returns a {@link ol.CoordinateFormatType} function that can be used to format + * a {ol.Coordinate} to a string. + * + * Example without specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var stringifyFunc = ol.coordinate.createStringXY(); + * var out = stringifyFunc(coord); + * // out is now '8, 48' + * + * Example with explicitly specifying 2 fractional digits: + * + * var coord = [7.85, 47.983333]; + * var stringifyFunc = ol.coordinate.createStringXY(2); + * var out = stringifyFunc(coord); + * // out is now '7.85, 47.98' + * + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {ol.CoordinateFormatType} Coordinate format. + * @api stable + */ + function createStringXY(opt_fractionDigits?: number): ol.CoordinateFormatType; + + /** + * Transforms the given {@link ol.Coordinate} to a string using the given string + * template. The strings `{x}` and `{y}` in the template will be replaced with + * the first and second coordinate values respectively. + * + * Example without specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var template = 'Coordinate is ({x}|{y}).'; + * var out = ol.coordinate.format(coord, template); + * // out is now 'Coordinate is (8|48).' + * + * Example explicitly specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var template = 'Coordinate is ({x}|{y}).'; + * var out = ol.coordinate.format(coord, template, 2); + * // out is now 'Coordinate is (7.85|47.98).' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {string} template A template string with `{x}` and `{y}` placeholders + * that will be replaced by first and second coordinate values. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} Formatted coordinate. + * @api stable + */ + function format(coordinate: (ol.Coordinate), template: string, opt_fractionDigits?: number): string; + + /** + * Rotate `coordinate` by `angle`. `coordinate` is modified in place and + * returned by the function. + * + * Example: + * + * var coord = [7.85, 47.983333]; + * var rotateRadians = Math.PI / 2; // 90 degrees + * ol.coordinate.rotate(coord, rotateRadians); + * // coord is now [-47.983333, 7.85] + * + * @param {ol.Coordinate} coordinate Coordinate. + * @param {number} angle Angle in radian. + * @return {ol.Coordinate} Coordinate. + * @api stable + */ + function rotate(coordinate: ol.Coordinate, angle: number): ol.Coordinate; + + /** + * Format a geographic coordinate with the hemisphere, degrees, minutes, and + * seconds. + * + * Example without specifying fractional digits: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringHDMS(coord); + * // out is now '47° 58′ 60″ N 7° 50′ 60″ E' + * + * Example explicitly specifying 1 fractional digit: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringHDMS(coord, 1); + * // out is now '47° 58′ 60.0″ N 7° 50′ 60.0″ E' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} Hemisphere, degrees, minutes and seconds. + * @api stable + */ + function toStringHDMS(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; + + /** + * Format a coordinate as a comma delimited string. + * + * Example without specifying fractional digits: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringXY(coord); + * // out is now '8, 48' + * + * Example explicitly specifying 1 fractional digit: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringXY(coord, 1); + * // out is now '7.8, 48.0' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} XY. + * @api stable + */ + function toStringXY(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; + + } + + /** + * @classdesc + * The ol.DeviceOrientation class provides access to information from + * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification]( + * http://www.w3.org/TR/orientation-event/) for more details. + * + * Many new computers, and especially mobile phones + * and tablets, provide hardware support for device orientation. Web + * developers targeting mobile devices will be especially interested in this + * class. + * + * Device orientation data are relative to a common starting point. For mobile + * devices, the starting point is to lay your phone face up on a table with the + * top of the phone pointing north. This represents the zero state. All + * angles are then relative to this state. For computers, it is the same except + * the screen is open at 90 degrees. + * + * Device orientation is reported as three angles - `alpha`, `beta`, and + * `gamma` - relative to the starting position along the three planar axes X, Y + * and Z. The X axis runs from the left edge to the right edge through the + * middle of the device. Similarly, the Y axis runs from the bottom to the top + * of the device through the middle. The Z axis runs from the back to the front + * through the middle. In the starting position, the X axis points to the + * right, the Y axis points away from you and the Z axis points straight up + * from the device lying flat. + * + * The three angles representing the device orientation are relative to the + * three axes. `alpha` indicates how much the device has been rotated around the + * Z axis, which is commonly interpreted as the compass heading (see note + * below). `beta` indicates how much the device has been rotated around the X + * axis, or how much it is tilted from front to back. `gamma` indicates how + * much the device has been rotated around the Y axis, or how much it is tilted + * from left to right. + * + * For most browsers, the `alpha` value returns the compass heading so if the + * device points north, it will be 0. With Safari on iOS, the 0 value of + * `alpha` is calculated from when device orientation was first requested. + * ol.DeviceOrientation provides the `heading` property which normalizes this + * behavior across all browsers for you. + * + * It is important to note that the HTML 5 DeviceOrientation specification + * indicates that `alpha`, `beta` and `gamma` are in degrees while the + * equivalent properties in ol.DeviceOrientation are in radians for consistency + * with all other uses of angles throughout OpenLayers. + * + * To get notified of device orientation changes, register a listener for the + * generic `change` event on your `ol.DeviceOrientation` instance. + * + * @see {@link http://www.w3.org/TR/orientation-event/} + * + * @constructor + * @extends {ol.Object} + * @param {olx.DeviceOrientationOptions=} opt_options Options. + * @api + */ + class DeviceOrientation extends ol.Object { + /** + * @classdesc + * The ol.DeviceOrientation class provides access to information from + * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification]( + * http://www.w3.org/TR/orientation-event/) for more details. + * + * Many new computers, and especially mobile phones + * and tablets, provide hardware support for device orientation. Web + * developers targeting mobile devices will be especially interested in this + * class. + * + * Device orientation data are relative to a common starting point. For mobile + * devices, the starting point is to lay your phone face up on a table with the + * top of the phone pointing north. This represents the zero state. All + * angles are then relative to this state. For computers, it is the same except + * the screen is open at 90 degrees. + * + * Device orientation is reported as three angles - `alpha`, `beta`, and + * `gamma` - relative to the starting position along the three planar axes X, Y + * and Z. The X axis runs from the left edge to the right edge through the + * middle of the device. Similarly, the Y axis runs from the bottom to the top + * of the device through the middle. The Z axis runs from the back to the front + * through the middle. In the starting position, the X axis points to the + * right, the Y axis points away from you and the Z axis points straight up + * from the device lying flat. + * + * The three angles representing the device orientation are relative to the + * three axes. `alpha` indicates how much the device has been rotated around the + * Z axis, which is commonly interpreted as the compass heading (see note + * below). `beta` indicates how much the device has been rotated around the X + * axis, or how much it is tilted from front to back. `gamma` indicates how + * much the device has been rotated around the Y axis, or how much it is tilted + * from left to right. + * + * For most browsers, the `alpha` value returns the compass heading so if the + * device points north, it will be 0. With Safari on iOS, the 0 value of + * `alpha` is calculated from when device orientation was first requested. + * ol.DeviceOrientation provides the `heading` property which normalizes this + * behavior across all browsers for you. + * + * It is important to note that the HTML 5 DeviceOrientation specification + * indicates that `alpha`, `beta` and `gamma` are in degrees while the + * equivalent properties in ol.DeviceOrientation are in radians for consistency + * with all other uses of angles throughout OpenLayers. + * + * To get notified of device orientation changes, register a listener for the + * generic `change` event on your `ol.DeviceOrientation` instance. + * + * @see {@link http://www.w3.org/TR/orientation-event/} + * + * @constructor + * @extends {ol.Object} + * @param {olx.DeviceOrientationOptions=} opt_options Options. + * @api + */ + constructor(opt_options?: olx.DeviceOrientationOptions); + + /** + * Rotation around the device z-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * standard Z axis. + * @observable + * @api + */ + getAlpha(): (number); + + /** + * Rotation around the device x-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * planar X axis. + * @observable + * @api + */ + getBeta(): (number); + + /** + * Rotation around the device y-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * planar Y axis. + * @observable + * @api + */ + getGamma(): (number); + + /** + * The heading of the device relative to north (in radians). + * @return {number|undefined} The heading of the device relative to north, in + * radians, normalizing for different browser behavior. + * @observable + * @api + */ + getHeading(): (number); + + /** + * Determine if orientation is being tracked. + * @return {boolean} Changes in device orientation are being tracked. + * @observable + * @api + */ + getTracking(): boolean; + + /** + * Enable or disable tracking of device orientation events. + * @param {boolean} tracking The status of tracking changes to alpha, beta and + * gamma. If true, changes are tracked and reported immediately. + * @observable + * @api + */ + setTracking(tracking: boolean): void; + + } + + /** + * Objects that need to clean up after themselves. + * @constructor + */ + class Disposable { + /** + * Objects that need to clean up after themselves. + * @constructor + */ + constructor(); + + } + + /** + * Easing functions for {@link ol.animation}. + * @namespace ol.easing + */ + module easing { + /** + * Start slow and speed up. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function easeIn(t: number): number; + + /** + * Start fast and slow down. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function easeOut(t: number): number; + + /** + * Start slow, speed up, and then slow down again. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function inAndOut(t: number): number; + + /** + * Maintain a constant speed over time. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function linear(t: number): number; + + /** + * Start slow, speed up, and at the very end slow down again. This has the + * same general behavior as {@link ol.easing.inAndOut}, but the final slowdown + * is delayed. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function upAndDown(t: number): number; + + } + + /** + * Applications do not normally create event instances. They register (and + * unregister) event listener functions, which, when called by the library as + * the result of an event being dispatched, are passed event instances as their + * first argument. Listeners can be registered and unregistered on all objects + * descending from {@link ol.Observable}. All event instances have a `target` + * property, which corresponds to the object on which the event was dispatched. + * By default, `this` within the listener also refers to the target, though + * this can be configured in the listener registration function. + * Some classes have their own event type, which return additional + * properties; see the specific event class page for details. + * + * @namespace ol.events + */ + module events { + /** + * @namespace ol.events.condition + */ + module condition { + /** + * Return `true` if only the alt-key is pressed, `false` otherwise (e.g. when + * additionally the shift-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the alt key is pressed. + * @api stable + */ + function altKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the alt-key and shift-key is pressed, `false` otherwise + * (e.g. when additionally the platform-modifier-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the alt and shift keys are pressed. + * @api stable + */ + function altShiftKeysOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return always true. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True. + * @function + * @api stable + */ + function always(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a `click` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `click` event. + * @api stable + */ + function click(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return always false. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} False. + * @function + * @api stable + */ + function never(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the browser event is a `pointermove` event, `false` + * otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the browser event is a `pointermove` event. + * @api + */ + function pointerMove(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a map `singleclick` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `singleclick` event. + * @api stable + */ + function singleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a map `dblclick` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `dblclick` event. + * @api stable + */ + function doubleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if no modifier key (alt-, shift- or platform-modifier-key) is + * pressed. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True only if there no modifier keys are pressed. + * @api stable + */ + function noModifierKeys(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the platform-modifier-key (the meta-key on Mac, + * ctrl-key otherwise) is pressed, `false` otherwise (e.g. when additionally + * the shift-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the platform modifier key is pressed. + * @api stable + */ + function platformModifierKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the shift-key is pressed, `false` otherwise (e.g. when + * additionally the alt-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the shift key is pressed. + * @api stable + */ + function shiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the target element is not editable, i.e. not a ``-, + * `