Merge branch 'master' of github.com:borisyankov/DefinitelyTyped

This commit is contained in:
mick delaney
2015-07-03 15:57:03 +01:00
55 changed files with 207731 additions and 6859 deletions
+143
View File
@@ -0,0 +1,143 @@
/**
* Created by shearerbeard on 6/28/15.
*/
///<reference path="alt.d.ts"/>
///<reference path="../es6-promise/es6-promise.d.ts" />
import Alt = require("alt");
import Promise = require("es6-promise");
//New alt instance
var alt = new Alt();
//Interfaces for our Action Types
interface TestActionsGenerate {
notifyTest(str:string):void;
}
interface TestActionsExplicit {
doTest(str:string):void;
success():void;
error():void;
loading():void;
}
//Create abstracts to inherit ghost methods
class AbstractActions implements AltJS.ActionsClass {
constructor( alt:AltJS.Alt){}
actions:any;
dispatch: ( ...payload:Array<any>) => void;
generateActions:( ...actions:Array<string>) => void;
}
class AbstractStoreModel<S> implements AltJS.StoreModel<S> {
bindActions:( ...actions:Array<Object>) => void;
bindAction:( ...args:Array<any>) => void;
bindListeners:(obj:any)=> void;
exportPublicMethods:(config:{[key:string]:(...args:Array<any>) => any}) => any;
exportAsync:( source:any) => void;
waitFor:any;
exportConfig:any;
getState:() => S;
}
class GenerateActionsClass extends AbstractActions {
constructor(config:AltJS.Alt) {
this.generateActions("notifyTest");
super(config);
}
}
class ExplicitActionsClass extends AbstractActions {
doTest(str:string) {
this.dispatch(str);
}
success() {
this.dispatch();
}
error() {
this.dispatch();
}
loading() {
this.dispatch();
}
}
var generatedActions = alt.createActions<TestActionsGenerate>(GenerateActionsClass);
var explicitActions = alt.createActions<ExplicitActionsClass>(ExplicitActionsClass);
interface AltTestState {
hello:string;
}
var testSource:AltJS.Source = {
fakeLoad():AltJS.SourceModel<string> {
return {
remote() {
return new Promise.Promise<string>((res:any, rej:any) => {
setTimeout(() => {
if(true) {
res("stuff");
} else {
rej("Things have broken");
}
}, 250)
});
},
local() {
return "local";
},
success: explicitActions.success,
error: explicitActions.error,
loading:explicitActions.loading
};
}
};
class TestStore extends AbstractStoreModel<AltTestState> implements AltTestState {
hello:string = "world";
constructor() {
super();
this.bindAction(generatedActions.notifyTest, this.onTest);
this.bindActions(explicitActions);
this.exportAsync(testSource);
this.exportPublicMethods({
split: this.split
});
}
onTest(str:string) {
this.hello = str;
}
onDoTest(str:string) {
this.hello = str;
}
split():string[] {
return this.hello.split("");
}
}
interface ExtendedTestStore extends AltJS.AltStore<AltTestState> {
fakeLoad():string;
split():Array<string>;
}
var testStore = <ExtendedTestStore>alt.createStore<AltTestState>(TestStore);
function testCallback(state:AltTestState) {
console.log(state);
}
//Listen allows a typed state callback
testStore.listen(testCallback);
testStore.unlisten(testCallback);
//State generic passes to derived store
var name:string = testStore.getState().hello;
var nameChars:Array<string> = testStore.split();
generatedActions.notifyTest("types");
explicitActions.doTest("more types");
export var result = testStore.getState();
+167
View File
@@ -0,0 +1,167 @@
// Type definitions for Alt 0.16.10
// Project: https://github.com/goatslacker/alt
// Definitions by: Michael Shearer <https://github.com/Shearerbeard>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../react/react.d.ts"/>
///<reference path="../es6-promise/es6-promise.d.ts" />
declare module AltJS {
interface StoreReduce {
action:any;
data: any;
}
export interface StoreModel<S> {
//Actions
bindAction?( action:Action<any>, handler:ActionHandler):void;
bindActions?(actions:ActionsClass):void;
//Methods/Listeners
exportPublicMethods?(exportConfig:any):void;
bindListeners?(config:{[methodName:string]:Action<any> | Actions}):void;
exportAsync?(source:Source):void;
registerAsync?(datasource:Source):void;
//state
setState?(state:S):void;
setState?(stateFn:(currentState:S, nextState:S) => S):void;
getState?():S;
waitFor?(store:AltStore<any>):void;
//events
onSerialize?(fn:(data:any) => any):void;
onDeserialize?(fn:(data:any) => any):void;
on?(event:AltJS.lifeCycleEvents, callback:() => any):void;
emitChange?():void;
waitFor?(storeOrStores:AltStore<any> | Array<AltStore<any>>):void;
otherwise?(data:any, action:AltJS.Action<any>):void;
observe?(alt:Alt):any;
reduce?(state:any, config:StoreReduce):Object;
preventDefault?():void;
afterEach?(payload:Object, state:Object):void;
beforeEach?(payload:Object, state:Object):void;
// TODO: Embed dispatcher interface in def
dispatcher?:any;
//instance
getInstance?():AltJS.AltStore<S>;
alt?:Alt;
displayName?:string;
}
export type Source = {[name:string]: () => SourceModel<any>};
export interface SourceModel<S> {
local(state:any):any;
remote(state:any):Promise<S>;
shouldFetch?(fetchFn:(...args:Array<any>) => boolean):void;
loading?:(args:any) => void;
success?:(state:S) => void;
error?:(args:any) => void;
interceptResponse?(response:any, action:Action<any>, ...args:Array<any>):any;
}
export interface AltStore<S> {
getState():S;
listen(handler:(state:S) => any):() => void;
unlisten(handler:(state:S) => any):void;
emitChange():void;
}
export enum lifeCycleEvents {
bootstrap,
snapshot,
init,
rollback,
error
}
export type Actions = {[action:string]:Action<any>};
export interface Action<T> {
( args:T):void;
defer(data:any):void;
}
export interface ActionsClass {
generateActions?( ...action:Array<string>):void;
dispatch( ...payload:Array<any>):void;
actions?:Actions;
}
type StateTransform = (store:StoreModel<any>) => AltJS.AltStore<any>;
interface AltConfig {
dispatcher?:any;
serialize?:(serializeFn:(data:Object) => string) => void;
deserialize?:(deserializeFn:(serialData:string) => Object) => void;
storeTransforms?:Array<StateTransform>;
batchingFunction?:(callback:( ...data:Array<any>) => any) => void;
}
class Alt {
constructor(config?:AltConfig);
actions:Actions;
bootstrap(jsonData:string):void;
takeSnapshot( ...storeNames:Array<string>):string;
flush():Object;
recycle( ...stores:Array<AltJS.AltStore<any>>):void;
rollback():void;
dispatch(action?:AltJS.Action<any>, data?:Object, details?:any):void;
//Actions methods
addActions(actionsName:string, ActionsClass: ActionsClassConstructor):void;
createActions<T>(ActionsClass: ActionsClassConstructor, exportObj?: Object):T;
createActions<T>(ActionsClass: ActionsClassConstructor, exportObj?: Object, ...constructorArgs:Array<any>):T;
generateActions<T>( ...actions:Array<string>):T;
getActions(actionsName:string):AltJS.Actions;
//Stores methods
addStore(name:string, store:StoreModel<any>, saveStore?:boolean):void;
createStore<S>(store:StoreModel<S>, name?:string):AltJS.AltStore<S>;
getStore(name:string):AltJS.AltStore<any>;
}
export interface AltFactory {
new(config?:AltConfig):Alt;
}
type ActionsClassConstructor = new (alt:Alt) => AltJS.ActionsClass;
type ActionHandler = ( ...data:Array<any>) => any;
type ExportConfig = {[key:string]:(...args:Array<any>) => any};
}
declare module "alt/utils/chromeDebug" {
function chromeDebug(alt:AltJS.Alt):void;
export = chromeDebug;
}
declare module "alt/AltContainer" {
import React = require("react");
interface ContainerProps {
store?:AltJS.AltStore<any>;
stores?:Array<AltJS.AltStore<any>>;
inject?:{[key:string]:any};
actions?:{[key:string]:Object};
render?:(...props:Array<any>) => React.ReactElement<any>;
flux?:AltJS.Alt;
transform?:(store:AltJS.AltStore<any>, actions:any) => any;
shouldComponentUpdate?:(props:any) => boolean;
component?:React.Component<any, any>;
}
type AltContainer = React.ReactElement<ContainerProps>;
var AltContainer:React.ComponentClass<ContainerProps>;
export = AltContainer;
}
declare module "alt" {
var alt:AltJS.AltFactory;
export = alt;
}
+1
View File
@@ -1064,6 +1064,7 @@ declare module angular {
///////////////////////////////////////////////////////////////////////////
interface IAnchorScrollService {
(): void;
(hash: string): void;
yOffset: any;
}
@@ -0,0 +1,11 @@
/// <reference path="api-error-handler.d.ts" />
import errorHandler = require('api-error-handler');
import express = require('express');
var api = express.Router();
api.get('/users/:userid', function (req, res, next) {
});
api.use(errorHandler());
+14
View File
@@ -0,0 +1,14 @@
// Type definitions for api-error-handler v1.0.0
// Project: https://github.com/expressjs/api-error-handler
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module 'api-error-handler' {
import express = require('express');
function apiErrorHandler(options?: any): express.ErrorRequestHandler;
export = apiErrorHandler;
}
Vendored
+1
View File
@@ -2535,6 +2535,7 @@ declare module d3 {
tickFormat(): (t: any) => string;
tickFormat(format: (t: any) => string): Axis;
tickFormat(format:string): Axis;
}
export function brush(): Brush<any>;
+8 -4
View File
@@ -10,20 +10,24 @@ declare module Dagre{
interface Graph {
new (): Graph;
edges(): string[];
edge(id: string): any;
edges(): Edge[];
edge(id: any): any;
nodes(): string[];
node(id: string): any;
node(id: any): any;
setDefaultEdgeLabel(callback: () => void): Graph;
setEdge(sourceId: string, targetId: string): Graph;
setGraph(options: { [key: string]: any }): Graph;
setNode(id: string, node: { [key: string]: any }): Graph;
}
interface Edge {
v: string;
w: string;
}
interface GraphLib {
Graph: Graph;
}
}
declare var dagre: Dagre.DagreFactory;
File diff suppressed because it is too large Load Diff
+1360 -1315
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,6 +1,6 @@
/// <reference path="dexie.d.ts" />
import Dexie = require("Dexie");
import Dexie = require("dexie");
module Utils {
+1 -1
View File
@@ -315,6 +315,6 @@ declare module Dexie {
}
}
declare module 'Dexie' {
declare module 'dexie' {
export = Dexie;
}
+2 -2
View File
@@ -1671,7 +1671,7 @@ declare module dojo {
* @param selector A CSS selector to search for.
* @param context OptionalAn optional context to limit the searching scope. Only nodes under context will bescanned.
*/
interface query{(selector: String, context?: String): void}
interface query{(selector: String, context?: String): NodeList}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojo/query.html
*
@@ -1713,7 +1713,7 @@ declare module dojo {
* @param selector A CSS selector to search for.
* @param context OptionalAn optional context to limit the searching scope. Only nodes under context will bescanned.
*/
interface query{(selector: String, context?: HTMLElement): void}
interface query{(selector: String, context?: HTMLElement): NodeList}
interface query {
/**
* can be used as AMD plugin to conditionally load new query engine
-2
View File
@@ -391,8 +391,6 @@ declare module "express" {
authenticatedUser: any;
files: any;
/**
* Clear cookie `name`.
*
+177639
View File
File diff suppressed because one or more lines are too long
+10799
View File
File diff suppressed because it is too large Load Diff
+25
View File
@@ -0,0 +1,25 @@
/// <reference path="./geometry-dom.d.ts" />
var point = new DOMPoint(5, 4);
var matrix = new DOMMatrix(2, 0, 0, 2, 10, 10);
var transformedPoint = point.matrixTransform(matrix);
var point = new DOMPoint(2, 0);
var quad1 = new DOMQuad(point, {x: 12, y: 0}, {x: 2, y: 10}, {x: 12, y: 10});
var rect = new DOMRect(2, 0, 10, 10);
var quad2 = new DOMQuad(rect);
new DOMQuad({x: 40, y: 25}, {x: 180, y: 8}, {x: 210, y: 150}, {x: 10, y: 180});
var matrix = new DOMMatrix();
matrix.scaleSelf(2);
matrix.translateSelf(20,20);
var matrix = new DOMMatrix();
matrix.translateSelf(20, 20);
matrix.scaleSelf(2);
matrix.translateSelf(-20, -20);
var matrix = new DOMMatrix();
matrix.translateSelf(20, 20).scaleSelf(2).translateSelf(-20, -20);
+326
View File
@@ -0,0 +1,326 @@
// Type definitions for Geometry Format Specification
// Project: http://www.w3.org/TR/geometry-1/
// Definitions by: Toshiya Nakakura <https://github.com/nakakura>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module GeometryDom {
export interface DOMPointReadOnly {
/**
* x coordinate / readonly
*/
x: number;
/**
* y coordinate / readonly
*/
y: number;
/**
* z coordinate / readonly
*/
z: number;
/**
* w coordinate / readonly
*/
w: number;
/**
* Post-multiply point with matrix.
* @param matrix
*/
matrixTransform(matrix:DOMMatrixReadOnly): DOMPoint;
}
interface DOMPoint extends DOMPointReadOnly {
/**
* x coordinate
*/
x: number;
/**
* y coordinate
*/
y: number;
/**
* z coordinate
*/
z: number;
/**
* w coordinate
*/
w: number;
}
interface DOMRect extends DOMRectReadOnly {
/**
* x coordinate
*/
x: number;
/**
* y coordinate
*/
y: number;
/**
* width value
*/
width: number;
/**
* height value
*/
height: number;
}
interface DOMRectReadOnly {
/**
* x coordinate
*/
x: number;
/**
* y coordinate
*/
y: number;
/**
* width value
*/
width: number;
/**
* height value
*/
height: number;
/**
* min(y coordinate, y coordinate + height dimension)
*/
top: number;
/**
* max(x coordinate, x coordinate + width dimension)
*/
right: number;
/**
* max(y coordinate, y coordinate + height dimension)
*/
bottom: number;
/**
* min(x coordinate, x coordinate + width dimension)
*/
left: number;
}
interface DOMRectList {
/**
* total number of DOMRect objects associated with the object.
* readonly unsigned long length
*/
length: number;
/**
* the DOMRect object at index must be returned.
* @param index
*/
item(index: number): DOMRect;
}
interface DOMQuad {
/**
* a DOMPoint that represents p1 of the quadrilateral
*/
p1: DOMPoint;
/**
* a DOMPoint that represents p2 of the quadrilateral
*/
p2: DOMPoint;
/**
* a DOMPoint that represents p3 of the quadrilateral
*/
p3: DOMPoint;
/**
* a DOMPoint that represents p4 of the quadrilateral
*/
p4: DOMPoint;
/**
* the associated bounding rectangle of the quadrilateral
*/
bounds: DOMRectReadOnly;
}
interface DOMMatrixReadOnly {
/**
* These attributes are simple aliases for certain elements of the 4x4 matrix
*/
a: number;
b: number;
c: number;
d: number;
e: number;
f: number;
m11: number;
m12: number;
m13: number;
m14: number;
m21: number;
m22: number;
m23: number;
m24: number;
m31: number;
m32: number;
m33: number;
m34: number;
m41: number;
m42: number;
m43: number;
m44: number;
is2D: boolean;
isIdentity: boolean;
translate(tx: number, ty: number, tz?: number): DOMMatrix;
scale(scale: number, originX?: number, originY?: number): DOMMatrix;
scale3d(scale: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;
scaleNonUniform(scale: number, scaleX: number, scaleY: number, scaleZ: number, originX: number, originY: number, originZ: number): DOMMatrix;
rotate(angle: number, originX?: number, originY?: number): DOMMatrix;
rotateFromVector(x: number, y: number): DOMMatrix;
rotateAxisAngle(x: number, y: number, z: number, angle: number): DOMMatrix;
skewX(sx: number): DOMMatrix;
skewY(sx: number): DOMMatrix;
multiply(other: DOMMatrix): DOMMatrix;
flipX(): DOMMatrix;
flipY(): DOMMatrix;
inverse(): DOMMatrix;
transformPoint(point?: DOMPointInit): DOMPoint;
toFloat32Array(): Array<number>;
toFloat64Array(): Array<number>;
}
interface DOMMatrix extends DOMMatrixReadOnly {
a: number;
b: number;
c: number;
d: number;
e: number;
f: number;
m11: number;
m12: number;
m13: number;
m14: number;
m21: number;
m22: number;
m23: number;
m24: number;
m31: number;
m32: number;
m33: number;
m34: number;
m41: number;
m42: number;
m43: number;
m44: number;
multiplySelf(other: DOMMatrix): DOMMatrix;
preMultiplySelf(other: DOMMatrix): DOMMatrix;
translateSelf(tx: number, ty: number, tz?: number): DOMMatrix;
scaleSelf(scale: number, originX?: number, originY?: number): DOMMatrix;
scale3dSelf(scale: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;
scaleNonUniformSelf(scaleX: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;
rotateSelf(angle: number, originX?: number, originY?: number): DOMMatrix;
rotateFromVectorSelf(x: number, y: number): DOMMatrix;
rotateAxisAngleSelf(x: number, y: number, z: number, angle: number): DOMMatrix;
skewXSelf(sx: number): DOMMatrix;
skewYSelf(sy: number): DOMMatrix;
invertSelf(): DOMMatrix;
setMatrixValue(transformList: DOMMatrix): DOMMatrix;
}
}
declare var DOMPointReadOnly: {
prototype: GeometryDom.DOMPointReadOnly;
new (x: number, y: number, z: number, w: number): GeometryDom.DOMPointReadOnly;
};
declare var DOMPoint: {
prototype: GeometryDom.DOMPoint;
new (x?:number, y?:number, z?:number, w?:number): GeometryDom.DOMPoint;
};
interface DOMPointInit {
/**
* x coordinate: 0
*/
x: number;
/**
* y coordinate: 0
*/
y: number;
/**
* z coordinate: 0
*/
z?: number;
/**
* w coordinate: 1
*/
w?: number;
}
declare var DOMRect: {
prototype: GeometryDom.DOMRect;
new (x: number, y: number, width: number, height: number): GeometryDom.DOMRect;
};
declare var DOMRectReadOnly: {
prototype: GeometryDom.DOMRectReadOnly;
new (x: number, y: number, width: number, height: number): GeometryDom.DOMRectReadOnly;
};
interface DOMRectInit {
/**
* x coordinate
*/
x: number;
/**
* y coordinate
*/
y: number;
/**
* width value
*/
width: number;
/**
* height value
*/
height: number;
}
interface DOMRectList {
/**
* total number of DOMRect objects associated with the object.
* readonly unsigned long length
*/
length: number;
/**
* the DOMRect object at index must be returned.
* @param index
*/
item(index: number): GeometryDom.DOMRect;
}
declare var DOMQuad: {
prototype: GeometryDom.DOMQuad;
new (rect?: DOMRectInit): GeometryDom.DOMQuad;
new (p1?: DOMPointInit, p2?: DOMPointInit, p3?: DOMPointInit, p4?: DOMPointInit): GeometryDom.DOMQuad;
};
declare var DOMMatrixReadOnly: {
prototype: GeometryDom.DOMMatrixReadOnly;
new (numberSequence: Array<number>): GeometryDom.DOMMatrixReadOnly;
};
declare var DOMMatrix: {
prototype: GeometryDom.DOMMatrix;
new (): GeometryDom.DOMMatrix;
new (transformList: string): GeometryDom.DOMMatrix;
new (other: GeometryDom.DOMMatrixReadOnly): GeometryDom.DOMMatrix;
new (array: Array<number>): GeometryDom.DOMMatrix;
new (a: number, b: number, c: number, d: number, e: number, f: number): GeometryDom.DOMMatrix;
};
+7
View File
@@ -0,0 +1,7 @@
/// <reference path="htmltojsx.d.ts"/>
import HTMLtoJSX = require("htmltojsx");
var converter = new HTMLtoJSX({
createClass: true,
outputClassName: 'AwesomeComponent'
});
var output = converter.convert('<div>Hello world!</div>');
+17
View File
@@ -0,0 +1,17 @@
// Type definitions for htmltojsx
// Project: https://www.npmjs.com/package/htmltojsx
// Definitions by: Basarat Ali Syed <https://github.com/basarat>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'htmltojsx' {
class HTMLtoJSX {
constructor(options?: {
createClass?: boolean;
outputClassName?: string;
/** as a string e.g. ' ' or '\t' */
indent?: string;
});
convert(html: string): string;
}
export = HTMLtoJSX;
}
+69
View File
@@ -0,0 +1,69 @@
/// <reference path="http-errors.d.ts" />
/// <reference path="../express/express.d.ts" />
import createError = require('http-errors');
import express = require('express');
var app = express();
app.use(function (req, res, next) {
if (!req.user) return next(createError(401, 'Please login to view this page.'));
next();
});
/* Examples taken from https://github.com/jshttp/http-errors/blob/1.3.1/test/test.js */
// createError(status)
var err = createError(404);
console.log(err.name);
console.log(err.message);
console.log(err.status);
console.log(err.statusCode);
console.log(err.expose);
// createError(status, msg)
var err = createError(404, 'LOL');
// createError(status, props)
var err = createError(404, {id: 1});
// createError(props)
var err = createError({id: 1});
console.log((<any> err).id);
// createError(msg, status)
var err = createError('LOL', 404);
// createError(msg)
var err = createError('LOL');
// createError(msg, props)
var err = createError('LOL', {id: 1});
// createError(err)
var err = createError(new Error('LOL'));
// createError(err, props)
var err = createError(new Error('LOL'), {id: 1});
// createError(status, err, props)
var err = createError(404, new Error('LOL'), {id: 1});
// createError(status, msg, props)
var err = createError(404, 'LOL', {id: 1});
// createError(status, msg, { expose: false })
var err = createError(404, 'LOL', {expose: false})
// new createError.NotFound()
var err = new createError.NotFound();
// new createError.InternalServerError()
var err = new createError.InternalServerError();
// new createError['404']()
var err = new createError['404']();
//createError['404'](); // TypeScript should fail with "Did you mean to include 'new'?"
//new createError(); // TypeScript should fail with "Only a void function can be called with the 'new' keyword"
+85
View File
@@ -0,0 +1,85 @@
// Type definitions for http-errors v1.3.1
// Project: https://github.com/jshttp/http-errors
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'http-errors' {
interface HttpError extends Error {
status: number;
statusCode: number;
expose: boolean;
}
interface CreateHttpError {
// See https://github.com/Microsoft/TypeScript/issues/227#issuecomment-50092674
[code: string]: new() => HttpError;
(...args: Array<Error | string | number | Object>): HttpError;
Continue: new() => HttpError;
SwitchingProtocols: new() => HttpError;
Processing: new() => HttpError;
OK: new() => HttpError;
Created: new() => HttpError;
Accepted: new() => HttpError;
NonAuthoritativeInformation: new() => HttpError;
NoContent: new() => HttpError;
ResetContent: new() => HttpError;
PartialContent: new() => HttpError;
MultiStatus: new() => HttpError;
AlreadyReported: new() => HttpError;
IMUsed: new() => HttpError;
MultipleChoices: new() => HttpError;
MovedPermanently: new() => HttpError;
Found: new() => HttpError;
SeeOther: new() => HttpError;
NotModified: new() => HttpError;
UseProxy: new() => HttpError;
Unused: new() => HttpError;
TemporaryRedirect: new() => HttpError;
PermanentRedirect: new() => HttpError;
BadRequest: new() => HttpError;
Unauthorized: new() => HttpError;
PaymentRequired: new() => HttpError;
Forbidden: new() => HttpError;
NotFound: new() => HttpError;
MethodNotAllowed: new() => HttpError;
NotAcceptable: new() => HttpError;
ProxyAuthenticationRequired: new() => HttpError;
RequestTimeout: new() => HttpError;
Conflict: new() => HttpError;
Gone: new() => HttpError;
LengthRequired: new() => HttpError;
PreconditionFailed: new() => HttpError;
PayloadTooLarge: new() => HttpError;
URITooLong: new() => HttpError;
UnsupportedMediaType: new() => HttpError;
RangeNotSatisfiable: new() => HttpError;
ExpectationFailed: new() => HttpError;
ImATeapot: new() => HttpError;
UnprocessableEntity: new() => HttpError;
Locked: new() => HttpError;
FailedDependency: new() => HttpError;
UnorderedCollection: new() => HttpError;
UpgradeRequired: new() => HttpError;
PreconditionRequired: new() => HttpError;
TooManyRequests: new() => HttpError;
RequestHeaderFieldsTooLarge: new() => HttpError;
UnavailableForLegalReasons: new() => HttpError;
InternalServerError: new() => HttpError;
NotImplemented: new() => HttpError;
BadGateway: new() => HttpError;
ServiceUnavailable: new() => HttpError;
GatewayTimeout: new() => HttpError;
HTTPVersionNotSupported: new() => HttpError;
VariantAlsoNegotiates: new() => HttpError;
InsufficientStorage: new() => HttpError;
LoopDetected: new() => HttpError;
BandwidthLimitExceeded: new() => HttpError;
NotExtended: new() => HttpError;
NetworkAuthenticationRequired: new() => HttpError;
}
var httpError: CreateHttpError;
export = httpError;
}
@@ -0,0 +1,17 @@
/// <reference path="jasmine-promise-matchers.d.ts" />
describe('something', () => {
beforeEach(() => {
installPromiseMatchers();
});
it('should do something', () => {
var foo = {};
var bar = {};
expect(foo).toBeResolvedWith(bar);
expect(foo).toBeRejectedWith(bar);
expect(foo).toBeResolved();
expect(foo).toBeRejected();
});
})
+33
View File
@@ -0,0 +1,33 @@
// Type definitions for jasmine-promise-matchers
// Project: https://github.com/bvaughn/jasmine-promise-matchers
// Definitions by: Matthew Hill <https://github.com/matthewjh>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jasmine/jasmine.d.ts" />
declare function installPromiseMatchers(): void;
declare module jasmine {
interface Matchers {
/**
* Verifies that a Promise is (or has been) rejected.
*/
toBeRejected(): boolean;
/**
* Verifies that a Promise is (or has been) rejected with the specified parameter.
*/
toBeRejectedWith(value: any): boolean;
/**
* Verifies that a Promise is (or has been) resolved.
*/
toBeResolved(): boolean;
/**
* Verifies that a Promise is (or has been) resolved with the specified parameter.
*/
toBeResolvedWith(value: any): boolean;
}
}
+24
View File
@@ -657,6 +657,30 @@ describe("jasmine.objectContaining", function () {
});
});
describe("jasmine.arrayContaining", function() {
var foo: any;
beforeEach(function() {
foo = [1, 2, 3, 4];
});
it("matches arrays with some of the values", function() {
expect(foo).toEqual(jasmine.arrayContaining([3, 1]));
expect(foo).not.toEqual(jasmine.arrayContaining([6]));
});
describe("when used with a spy", function() {
it("is useful when comparing arguments", function() {
var callback = jasmine.createSpy('callback');
callback([1, 2, 3, 4]);
expect(callback).toHaveBeenCalledWith(jasmine.arrayContaining([4, 2, 3]));
expect(callback).not.toHaveBeenCalledWith(jasmine.arrayContaining([5, 2]));
});
});
});
describe("Manually ticking the Jasmine Clock", function () {
var timerCallback: any;
+8
View File
@@ -47,6 +47,7 @@ declare module jasmine {
function any(aclass: any): Any;
function anything(): Any;
function arrayContaining(sample: any[]): ArrayContaining;
function objectContaining(sample: any): ObjectContaining;
function createSpy(name: string, originalFn?: Function): Spy;
function createSpyObj(baseName: string, methodNames: any[]): any;
@@ -71,6 +72,13 @@ declare module jasmine {
length: number;
[n: number]: T;
}
interface ArrayContaining {
new (sample: any[]): any;
asymmetricMatch(other: any): boolean;
jasmineToString(): string;
}
interface ObjectContaining {
new (sample: any): any;
+38 -5
View File
@@ -77,6 +77,17 @@ function test_validate() {
$(".selector").validate({
onclick: false
});
$(".selector").validate({
onfocusout: (elt) => { },
onkeyup: (elt) => { },
onclick: (elt) => { }
});
$(".selector").validate({
onfocusout: (elt, event) => { },
onkeyup: (elt, event) => { },
onclick: (elt, event) => { }
});
$(".selector").validate({
focusInvalid: false
});
@@ -111,7 +122,7 @@ function test_validate() {
submitHandler: function () { alert("Submitted!") }
});
$(".selector").validate({
showErrors: function (errorMap: ErrorDictionary, errorList: ErrorListItem[]) {
showErrors: function (errorMap: JQueryValidation.ErrorDictionary, errorList: JQueryValidation.ErrorListItem[]) {
$("#summary").html("Your form contains " + this.numberOfInvalids() + " errors, see details below.");
this.defaultShowErrors();
}
@@ -154,6 +165,18 @@ function test_validate() {
$(".selector").validate({
ignoreTitle: true
});
// onSubmit, onfocusout, onkeyup, onclick
$('.selector').validate({
onsubmit: false,
onfocusout: false,
onkeyup: false,
onclick: false,
});
$('.selector').validate({
onfocusout: () => {},
onkeyup: () => {},
onclick: function(elt) { return 2; }
});
}
function test_methods() {
@@ -194,10 +217,15 @@ function test_methods() {
validator.hideErrors();
var isValid: boolean = validator.valid();
var size: number = validator.size();
var errorMap: ErrorDictionary = validator.errorMap;
var errorList: ErrorListItem[] = validator.errorList;
var errorMap: JQueryValidation.ErrorDictionary = validator.errorMap;
var errorList: JQueryValidation.ErrorListItem[] = validator.errorList;
$("#summary").text(validator.numberOfInvalids() + " field(s) are invalid");
var invalidElements: HTMLElement[] = validator.invalidElements();
var validElements: HTMLElement[] = validator.validElements();
}
function test_static_methods() {
jQuery.validator.setDefaults({
debug: true
});
@@ -228,6 +256,11 @@ function test_methods() {
maxlength: 5
}
});
var invalidElements: HTMLElement[] = validator.invalidElements();
var validElements: HTMLElement[] = validator.validElements();
// jQuery.validator.format
jQuery.validator.format('{0}');
jQuery.validator.format('{0} {1}')('a', 2);
jQuery.validator.format('{0} {1}', 'a', 2);
jQuery.validator.format('{0} {1}', ['a', 2]);
}
+239 -225
View File
@@ -1,4 +1,4 @@
// Type definitions for jquery.validation 1.11.1
// Type definitions for jquery.validation 1.13.1
// Project: http://jqueryvalidation.org/
// Definitions by: François de Campredon <https://github.com/fdecampredon>, John Reilly <https://github.com/johnnyreilly>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -6,229 +6,242 @@
/// <reference path="../jquery/jquery.d.ts"/>
interface ValidationOptions
{
/**
* Enables debug mode. If true, the form is not submitted and certain errors are displayed on the console (will check if a window.console property exists). Try to enable when a form is just submitted instead of validation stopping the submit.
*
* default: false
*/
debug?: boolean;
/**
* Use this class to create error labels, to look for existing error labels and to add it to invalid elements.
*
* default: "error"
*/
errorClass?: string;
/**
* Hide and show this container when validating.
*/
errorContainer?: string;
/**
* Use this element type to create error messages and to look for existing error messages. The default, "label", has the advantage of creating a meaningful link between error message and invalid field using the for attribute (which is always used, regardless of element type).
*
* default: "label"
*/
errorElement?: string;
/**
* Hide and show this container when validating. (eg "#messageBox")
*/
errorLabelContainer?: string;
/**
* Customize placement of created error labels. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object.
*
* default: Places the error label after the invalid element
*/
errorPlacement?: (error: JQuery, element: JQuery) => void;
/**
* If enabled, removes the errorClass from the invalid elements and hides all error messages whenever the element is focused. Avoid combination with focusInvalid.
*
* default: false
*/
focusCleanup?: boolean;
/**
* Focus the last active or first invalid element on submit via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding stealing its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off.
*
* default: true
*/
focusInvalid?: boolean;
/**
* Specify grouping of error messages. A group consists of an arbitrary group name as the key and a space separated list of element names as the value. Use errorPlacement to control where the group message is placed.
*/
groups?: Object;
/**
* How to highlight invalid fields. Override to decide which fields and how to highlight.
*
* default: Adds errorClass (see the option) to the element
*/
highlight?: (element: HTMLElement, errorClass: string, validClass: string) => void;
/**
* Elements to ignore when validating, simply filtering them out. jQuery's not-method is used, therefore everything that is accepted by not() can be passed as this option. Inputs of type submit and reset are always ignored, so are disabled elements.
*/
ignore?: string;
/**
* Set to skip reading messages from the title attribute, helps to avoid issues with Google Toolbar; default is false for compability, the message-from-title is likely to be completely removed in a future release.
*
* default: false
*/
ignoreTitle?: boolean;
/**
* Callback for custom code when an invalid form is submitted. Called with an event object as the first argument, and the validator as the second.
*/
invalidHandler?: (event: JQueryEventObject, validator: Validator) => void;
/**
* Key/value pairs defining custom messages. Key is the name of an element, value the message to display for that element. Instead of a plain message, another map with specific messages for each rule can be used. Overrides the title attribute of an element or the default message for the method (in that order). Each message can be a String or a Callback. The callback is called in the scope of the validator, with the rule's parameters as the first argument and the element as the second, and must return a String to display as the message.
*
* default: the default message for the method used
*/
messages?: Object;
meta?: string;
/**
* Boolean or Function. Validate checkboxes and radio buttons on click. Set to false to disable.
*
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*/
onclick?: boolean|Function;
/**
* Boolean or Function. Validate elements (except checkboxes/radio buttons) on blur. If nothing is entered, all rules are skipped, except when the field was already marked as invalid.
*
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*/
onfocusout?: boolean|Function;
/**
* Boolean or Function. Validate elements on keyup. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. Set to false to disable.
*
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*/
onkeyup?: boolean|Function;
/**
* Validate the form on submit. Set to false to use only other events for validation.
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*
* default: true
*/
onsubmit?: boolean;
/**
* A custom message display handler. Gets the map of errors as the first argument and an array of errors as the second, called in the context of the validator object. The arguments contain only those elements currently validated, which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default behaviour by calling this.defaultShowErrors().
*/
rules?: Object;
/**
* A custom message display handler. Gets the map of errors as the first argument and an array of errors as the second, called in the context of the validator object. The arguments contain only those elements currently validated, which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default behaviour by calling this.defaultShowErrors().
*/
showErrors?: (errorMap: ErrorDictionary, errorList: ErrorListItem[]) => void;
/**
* Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated.
*/
submitHandler?: (form: HTMLFormElement) => void;
/**
* String or Function. If specified, the error label is displayed to show a valid element. If a String is given, it is added as a class to the label. If a Function is given, it is called with the label (as a jQuery object) and the validated input (as a DOM element). The label can be used to add a text like "ok!".
*/
success?: string|{($label: JQuery, validatedInput: HTMLElement):void};
/**
* Called to revert changes made by option highlight, same arguments as highlight.
*
* default: Removes the errorClass
*/
unhighlight?: (element: HTMLElement, errorClass: string, validClass: string) => void;
/**
* This class is added to an element after it was validated and considered valid.
*
* default: "valid"
*/
validClass?: string;
/**
* Wrap error labels with the specified element. Useful in combination with errorLabelContainer to create a list of error messages.
*
* default: window
*/
wrapper?: string;
}
interface ErrorDictionary
declare module JQueryValidation
{
[name: string]: string;
}
type RulesDictionary = { [name: string]: any };
interface ErrorListItem
{
message: string;
element: HTMLElement;
}
type ShouldValidatePredicate = boolean|((element: HTMLElement, event: JQueryEventObject) => void);
interface Validator
{
/**
* Add a compound class method - useful to refactor common combinations of rules into a single class.
*
* @param name The name of the class rule to add
* @param rules The compound rules
*/
addClassRules(name: string, rules: Object): void;
/**
* Add a compound class method - useful to refactor common combinations of rules into a single class.
*
* @param rules A map of className-rules pairs
*/
addClassRules(rules: Object): void;
/**
* Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message.
*
* @param name The name of the method used to identify it and referencing it; this must be a valid JavaScript identifier
* @param method The actual method implementation, returning true if an element is valid. First argument: Current value. Second argument: Validated element. Third argument: Parameters.
*/
addMethod(name: string, method: (value: any, element: HTMLElement, params: any) => boolean, message?: string): void;
/**
* Validates a single element, returns true if it is valid, false otherwise.
*
* @param element An element to validate, must be inside the validated form. eg "#myselect"
*/
element(element: string|JQuery): boolean;
/**
* Validates the form, returns true if it is valid, false otherwise.
*/
form(): boolean;
/**
* Replaces {n} placeholders with arguments.
*
* @param template The string to format.
*/
format(template: string, ...arguments: string[]): string;
invalidElements(): HTMLElement[];
/**
* Returns the number of invalid fields.
*/
numberOfInvalids(): number;
/**
* Resets the controlled form.
*/
resetForm(): void;
/**
* Modify default settings for validation.
*
* @param options Options to set as default.
*/
setDefaults(defaults: ValidationOptions): void;
settings: ValidationOptions;
/**
* Show the specified messages.
*
* @param errors One or more key/value pairs of input names and messages.
*/
showErrors(errors: any): void;
hideErrors(): void;
valid(): boolean;
validElements(): HTMLElement[];
size(): number;
focusInvalid(): void;
messages: { [index: string]: string };
interface ValidationOptions
{
/**
* Enables debug mode. If true, the form is not submitted and certain errors are displayed on the console (will check if a window.console property exists). Try to enable when a form is just submitted instead of validation stopping the submit.
*
* default: false
*/
debug?: boolean;
/**
* Use this class to create error labels, to look for existing error labels and to add it to invalid elements.
*
* default: "error"
*/
errorClass?: string;
/**
* Hide and show this container when validating.
*/
errorContainer?: string;
/**
* Use this element type to create error messages and to look for existing error messages. The default, "label", has the advantage of creating a meaningful link between error message and invalid field using the for attribute (which is always used, regardless of element type).
*
* default: "label"
*/
errorElement?: string;
/**
* Hide and show this container when validating. (eg "#messageBox")
*/
errorLabelContainer?: string;
/**
* Customize placement of created error labels. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object.
*
* default: Places the error label after the invalid element
*/
errorPlacement?: (error: JQuery, element: JQuery) => void;
/**
* If enabled, removes the errorClass from the invalid elements and hides all error messages whenever the element is focused. Avoid combination with focusInvalid.
*
* default: false
*/
focusCleanup?: boolean;
/**
* Focus the last active or first invalid element on submit via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding stealing its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off.
*
* default: true
*/
focusInvalid?: boolean;
/**
* Specify grouping of error messages. A group consists of an arbitrary group name as the key and a space separated list of element names as the value. Use errorPlacement to control where the group message is placed.
*/
groups?: { [groupName: string]: string };
/**
* How to highlight invalid fields. Override to decide which fields and how to highlight.
*
* default: Adds errorClass (see the option) to the element
*/
highlight?: (element: HTMLElement, errorClass: string, validClass: string) => void;
/**
* Elements to ignore when validating, simply filtering them out. jQuery's not-method is used, therefore everything that is accepted by not() can be passed as this option. Inputs of type submit and reset are always ignored, so are disabled elements.
*/
ignore?: string;
/**
* Set to skip reading messages from the title attribute, helps to avoid issues with Google Toolbar; default is false for compability, the message-from-title is likely to be completely removed in a future release.
*
* default: false
*/
ignoreTitle?: boolean;
/**
* Callback for custom code when an invalid form is submitted. Called with an event object as the first argument, and the validator as the second.
*/
invalidHandler?: (event: JQueryEventObject, validator: Validator) => void;
/**
* Key/value pairs defining custom messages. Key is the name of an element, value the message to display for that element. Instead of a plain message, another map with specific messages for each rule can be used. Overrides the title attribute of an element or the default message for the method (in that order). Each message can be a String or a Callback. The callback is called in the scope of the validator, with the rule's parameters as the first argument and the element as the second, and must return a String to display as the message.
*
* default: the default message for the method used
*/
messages?: Object;
meta?: string;
/**
* Boolean or Function. Validate checkboxes and radio buttons on click. Set to false to disable.
*
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*/
onclick?: ShouldValidatePredicate;
/**
* Boolean or Function. Validate elements (except checkboxes/radio buttons) on blur. If nothing is entered, all rules are skipped, except when the field was already marked as invalid.
*
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*/
onfocusout?: ShouldValidatePredicate;
/**
* Boolean or Function. Validate elements on keyup. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. Set to false to disable.
*
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*/
onkeyup?: ShouldValidatePredicate;
/**
* Validate the form on submit. Set to false to use only other events for validation.
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*
* default: true
*/
onsubmit?: boolean;
/**
* A custom message display handler. Gets the map of errors as the first argument and an array of errors as the second, called in the context of the validator object. The arguments contain only those elements currently validated, which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default behaviour by calling this.defaultShowErrors().
*/
rules?: RulesDictionary;
/**
* A custom message display handler. Gets the map of errors as the first argument and an array of errors as the second, called in the context of the validator object. The arguments contain only those elements currently validated, which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default behaviour by calling this.defaultShowErrors().
*/
showErrors?: (errorMap: ErrorDictionary, errorList: ErrorListItem[]) => void;
/**
* Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated.
*/
submitHandler?: (form: HTMLFormElement) => void;
/**
* String or Function. If specified, the error label is displayed to show a valid element. If a String is given, it is added as a class to the label. If a Function is given, it is called with the label (as a jQuery object) and the validated input (as a DOM element). The label can be used to add a text like "ok!".
*/
success?: string|{($label: JQuery, validatedInput: HTMLElement):void};
/**
* Called to revert changes made by option highlight, same arguments as highlight.
*
* default: Removes the errorClass
*/
unhighlight?: (element: HTMLElement, errorClass: string, validClass: string) => void;
/**
* This class is added to an element after it was validated and considered valid.
*
* default: "valid"
*/
validClass?: string;
/**
* Wrap error labels with the specified element. Useful in combination with errorLabelContainer to create a list of error messages.
*
* default: window
*/
wrapper?: string;
}
errorMap: ErrorDictionary;
errorList: ErrorListItem[];
methods: { [index: string]: Function };
interface ErrorDictionary
{
[name: string]: string;
}
interface ErrorListItem
{
message: string;
element: HTMLElement;
}
interface ValidatorStatic
{
/**
* Add a compound class method - useful to refactor common combinations of rules into a single class.
*
* @param name The name of the class rule to add
* @param rules The compound rules
*/
addClassRules(name: string, rules: RulesDictionary): void;
/**
* Add a compound class method - useful to refactor common combinations of rules into a single class.
*
* @param rules A map of className-rules pairs
*/
addClassRules(rules: RulesDictionary): void;
/**
* Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message.
*
* @param name The name of the method used to identify it and referencing it; this must be a valid JavaScript identifier
* @param method The actual method implementation, returning true if an element is valid. First argument: Current value. Second argument: Validated element. Third argument: Parameters.
*/
addMethod(name: string, method: (value: any, element: HTMLElement, params: any) => boolean, message?: string): void;
/**
* Replaces {n} placeholders with arguments.
*
* @param template The string to format.
*/
format(template: string): ( (...args: any[]) => string);
format(template: string, ...args: any[]): string;
/**
* Modify default settings for validation.
*
* @param options Options to set as default.
*/
setDefaults(defaults: ValidationOptions): void;
messages: { [index: string]: string };
methods: { [index: string]: Function };
}
interface Validator
{
element(element: string|JQuery): boolean;
/**
* Validates the form, returns true if it is valid, false otherwise.
*/
form(): boolean;
invalidElements(): HTMLElement[];
/**
* Returns the number of invalid fields.
*/
numberOfInvalids(): number;
/**
* Resets the controlled form.
*/
resetForm(): void;
settings: ValidationOptions;
/**
* Show the specified messages.
*
* @param errors One or more key/value pairs of input names and messages.
*/
showErrors(errors: any): void;
hideErrors(): void;
valid(): boolean;
validElements(): HTMLElement[];
size(): number;
focusInvalid(): void;
errorMap: ErrorDictionary;
errorList: ErrorListItem[];
}
}
interface JQuery
@@ -236,14 +249,14 @@ interface JQuery
/**
* Remove the specified attributes from the first matched element and return them.
*
* @param attributes A space-seperated list of attribute names to remove.
* @param attributes A space-separated list of attribute names to remove.
*/
removeAttrs(attributes: string): any;
/**
* Returns the validations rules for the first selected element
*/
rules(): any;
rules(): any;
/**
* Removes the specified rules and returns all rules for the first matched element.
@@ -265,7 +278,7 @@ interface JQuery
* @param command "add"
* @param rules The rules to add. Accepts the same format as the rules-option of the validate-method.
*/
rules(command: string, rules: Object): any;
rules(command: string, rules: JQueryValidation.RulesDictionary): any;
/**
* Checks whether the selected form is valid or whether all selected elements are valid.
@@ -277,7 +290,7 @@ interface JQuery
*
* @param options options for validation
*/
validate(options?: ValidationOptions): Validator;
validate(options?: JQueryValidation.ValidationOptions): JQueryValidation.Validator;
}
interface JQueryStatic
@@ -287,6 +300,7 @@ interface JQueryStatic
*
* @param template The string to format.
*/
format(template: string, ...arguments: string[]): string;
validator: Validator;
format(template: string, ...arguments: string[]): string;
validator: JQueryValidation.ValidatorStatic;
}
+1 -1
View File
@@ -3278,7 +3278,7 @@ declare module L {
/**
* Sets the pointer-events attribute on the path if SVG backend is used.
*/
pointerEvents?: boolean;
pointerEvents?: string;
/**
* Custom class name set on an element.
+7 -7
View File
@@ -403,15 +403,13 @@ result = <number[]>_([1, 2, 3, 4, 5, 6]).select(function (num) { return num % 2
result = <IFoodCombined[]>_(foodsCombined).select('organic').value();
result = <IFoodCombined[]>_(foodsCombined).select({ 'type': 'fruit' }).value();
result = <number>_.find([1, 2, 3, 4], function (num) {
return num % 2 == 0;
});
result = <number>_.find([1, 2, 3, 4], num => num % 2 == 0);
result = <IFoodCombined>_.find(foodsCombined, { 'type': 'vegetable' });
result = <IFoodCombined>_.find(foodsCombined, 'type', 'vegetable');
result = <IFoodCombined>_.find(foodsCombined, 'organic');
result = <number>_([1, 2, 3, 4]).find(function (num) {
return num % 2 == 0;
});
result = <number>_([1, 2, 3, 4]).find(num => num % 2 == 0);
result = <IFoodCombined>_(foodsCombined).find({ 'type': 'vegetable' });
result = <IFoodCombined>_(foodsCombined).find('type', 'vegetable');
result = <IFoodCombined>_(foodsCombined).find('organic');
result = <number>_.detect([1, 2, 3, 4], function (num) {
@@ -605,8 +603,10 @@ result = <IFoodCombined[]>_(foodsCombined).reject({ 'type': 'fruit' }).value();
result = <number>_.sample([1, 2, 3, 4]);
result = <number[]>_.sample([1, 2, 3, 4], 2);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).sample();
result = <_.LoDashWrapper<number>>_([1, 2, 3, 4]).sample();
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).sample(2);
result = <number>_([1, 2, 3, 4]).sample().value();
result = <number[]>_([1, 2, 3, 4]).sample(2).value();
result = <number[]>_.shuffle([1, 2, 3, 4, 5, 6]);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3]).shuffle();
+76 -106
View File
@@ -2710,15 +2710,19 @@ declare module _ {
//_.find
interface LoDashStatic {
/**
* Iterates over elements of a collection, returning the first element that the callback
* returns truey for. The callback is bound to thisArg and invoked with three arguments;
* (value, index|key, collection).
* Iterates over elements of collection, returning the first element predicate returns
* truthy for. The predicate is bound to thisArg and invoked with three arguments:
* (value, index|key, collection).
*
* If a property name is provided for callback the created "_.pluck" style callback will
* return the property value of the given element.
* If a property name is provided for predicate the created _.property style callback
* returns the property value of the given element.
*
* If an object is provided for callback the created "_.where" style callback will return
* If a value is also provided for thisArg the created _.matchesProperty style callback
* returns true for elements that have a matching property value, else false.
*
* If an object is provided for predicate the created _.matches style callback returns
* true for elements that have the properties of the given object, else false.
*
* @param collection Searches for a value in this list.
* @param callback The function called per iteration.
* @param thisArg The this binding of callback.
@@ -2729,6 +2733,15 @@ declare module _ {
callback: ListIterator<T, boolean>,
thisArg?: any): T;
/**
* Alias of _.find
* @see _.find
**/
detect<T>(
collection: Array<T>,
callback: ListIterator<T, boolean>,
thisArg?: any): T;
/**
* @see _.find
**/
@@ -2737,6 +2750,15 @@ declare module _ {
callback: ListIterator<T, boolean>,
thisArg?: any): T;
/**
* Alias of _.find
* @see _.find
**/
detect<T>(
collection: List<T>,
callback: ListIterator<T, boolean>,
thisArg?: any): T;
/**
* @see _.find
**/
@@ -2746,70 +2768,7 @@ declare module _ {
thisArg?: any): T;
/**
* @see _.find
* @param _.pluck style callback
**/
find<W, T>(
collection: Array<T>,
whereValue: W): T;
/**
* @see _.find
* @param _.pluck style callback
**/
find<W, T>(
collection: List<T>,
whereValue: W): T;
/**
* @see _.find
* @param _.pluck style callback
**/
find<W, T>(
collection: Dictionary<T>,
whereValue: W): T;
/**
* @see _.find
* @param _.where style callback
**/
find<T>(
collection: Array<T>,
pluckValue: string): T;
/**
* @see _.find
* @param _.where style callback
**/
find<T>(
collection: List<T>,
pluckValue: string): T;
/**
* @see _.find
* @param _.where style callback
**/
find<T>(
collection: Dictionary<T>,
pluckValue: string): T;
/**
* @see _.find
**/
detect<T>(
collection: Array<T>,
callback: ListIterator<T, boolean>,
thisArg?: any): T;
/**
* @see _.find
**/
detect<T>(
collection: List<T>,
callback: ListIterator<T, boolean>,
thisArg?: any): T;
/**
* Alias of _.find
* @see _.find
**/
detect<T>(
@@ -2819,50 +2778,55 @@ declare module _ {
/**
* @see _.find
* @param _.pluck style callback
* @param _.matches style callback
**/
find<W, T>(
collection: Array<T>|List<T>|Dictionary<T>,
whereValue: W): T;
/**
* Alias of _.find
* @see _.find
* @param _.matches style callback
**/
detect<W, T>(
collection: Array<T>,
collection: Array<T>|List<T>|Dictionary<T>,
whereValue: W): T;
/**
* @see _.find
* @param _.pluck style callback
* @param _.matchesProperty style callback
**/
detect<W, T>(
collection: List<T>,
whereValue: W): T;
find<T>(
collection: Array<T>|List<T>|Dictionary<T>,
path: string,
srcValue: any): T;
/**
* Alias of _.find
* @see _.find
* @param _.pluck style callback
**/
detect<W, T>(
collection: Dictionary<T>,
whereValue: W): T;
/**
* @see _.find
* @param _.where style callback
* @param _.matchesProperty style callback
**/
detect<T>(
collection: Array<T>,
collection: Array<T>|List<T>|Dictionary<T>,
path: string,
srcValue: any): T;
/**
* @see _.find
* @param _.property style callback
**/
find<T>(
collection: Array<T>|List<T>|Dictionary<T>,
pluckValue: string): T;
/**
* Alias of _.find
* @see _.find
* @param _.where style callback
* @param _.property style callback
**/
detect<T>(
collection: List<T>,
pluckValue: string): T;
/**
* @see _.find
* @param _.where style callback
**/
detect<T>(
collection: Dictionary<T>,
collection: Array<T>|List<T>|Dictionary<T>,
pluckValue: string): T;
/**
@@ -2891,7 +2855,7 @@ declare module _ {
/**
* @see _.find
* @param _.pluck style callback
* @param _.matches style callback
**/
findWhere<W, T>(
collection: Array<T>,
@@ -2899,7 +2863,7 @@ declare module _ {
/**
* @see _.find
* @param _.pluck style callback
* @param _.matches style callback
**/
findWhere<W, T>(
collection: List<T>,
@@ -2907,7 +2871,7 @@ declare module _ {
/**
* @see _.find
* @param _.pluck style callback
* @param _.matches style callback
**/
findWhere<W, T>(
collection: Dictionary<T>,
@@ -2915,7 +2879,7 @@ declare module _ {
/**
* @see _.find
* @param _.where style callback
* @param _.property style callback
**/
findWhere<T>(
collection: Array<T>,
@@ -2923,7 +2887,7 @@ declare module _ {
/**
* @see _.find
* @param _.where style callback
* @param _.property style callback
**/
findWhere<T>(
collection: List<T>,
@@ -2931,7 +2895,7 @@ declare module _ {
/**
* @see _.find
* @param _.where style callback
* @param _.property style callback
**/
findWhere<T>(
collection: Dictionary<T>,
@@ -2947,14 +2911,20 @@ declare module _ {
thisArg?: any): T;
/**
* @see _.find
* @param _.where style callback
* @param _.matches style callback
*/
find<W>(
whereValue: W): T;
/**
* @see _.find
* @param _.where style callback
* @param _.matchesProperty style callback
*/
find(
path: string,
srcValue: any): T;
/**
* @see _.find
* @param _.property style callback
*/
find(
pluckValue: string): T;
@@ -4568,7 +4538,7 @@ declare module _ {
/**
* @see _.sample
**/
sample(): LoDashArrayWrapper<T>;
sample(): LoDashWrapper<T>;
}
//_.shuffle
+90
View File
@@ -0,0 +1,90 @@
/// <reference path="maquette.d.ts" />
// The hello world example from the homepage of maquettejs.org:
var h = maquette.h;
var domNode = document.body;
var projector = maquette.createProjector();
var you = ""; // A piece of data
// An ordinary event handler
function handleNameInput(evt: MouseEvent) {
you = (<HTMLInputElement>evt.target).value;
}
// This function uses the 'hyperscript' notation to create the virtual DOM.
// The 'you' variable is used twice here
function renderMaquette() {
return h("div", [
h("input", {
type: "text", placeholder: "What is your name?", value: you, oninput: handleNameInput
}),
h("p.output", ["Hello " + (you || "you") + "!"])
]);
}
// Project the renderMaquette function to the DOM and update the DOM when needed
projector.append(domNode, renderMaquette);
// Some snapshots taken from the maquette unit tests
// createDOM
var projection = maquette.dom.create(h("div", ["text"]));
projection.update(h("div", ["text2", h("span", ["a"])]));
// cache
var cache = maquette.createCache();
var calculationCalled = false;
var calculate = function () {
calculationCalled = true;
return "calculation result";
};
var result = cache.result([1], calculate);
// h
var vnode = h("div", [
"text",
null,
[ /* empty nested array */],
[null],
["nested text"],
[h("span")],
[h("button", ["click me"])],
[[[["deep"], null], "here"]]
]);
// mapping
var createTarget = function(source:any) {
return {
source: source,
updateCount: 0
};
};
var updateTarget = function(source: any, target:any) {
};
var permutations = [[1,2], [2,1]];
for (var i=0;i<permutations.length;i++) {
for (var j=0;j<permutations.length;j++) {
var mapping = maquette.createMapping(function(key){return key;}, createTarget, updateTarget);
mapping.map(permutations[i]);
mapping.results.forEach(function(target) {target.alreadyPresent = true;});
mapping.map(permutations[j]);
}
}
// styles
var projection = maquette.dom.create(h("div", { styles: { height: "20px" } }));
projection.update(h("div", { styles: { height: null } }));
+306
View File
@@ -0,0 +1,306 @@
// Type definitions for maquette
// Project: http://maquettejs.org/
// Definitions by: Johan Gorter <https://github.com/johan-gorter>
// Definitions: https://github.com/johan-gorter/DefinitelyTyped
/**
* @callback enterAnimationCallback
* @param {Element} element - Element that was just added to the DOM.
* @param {Object} properties - The properties object that was supplied to the {@link module:maquette.h} method
*/
/**
* @callback exitAnimationCallback
* @param {Element} element - Element that ought to be removed from to the DOM.
* @param {function} removeElement - Function that removes the element from the DOM.
* This argument is supplied purely for convenience.
* You may use this function to remove the element when the animation is done.
* @param {Object} properties - The properties object that was supplied to the {@link module:maquette.h} method that rendered this {@link VNode} the previous time.
*/
/**
* @callback updateAnimationCallback
* @param {Element} element - Element that was modified in the DOM.
* @param {Object} properties - The last properties object that was supplied to the {@link module:maquette.h} method
* @param {Object} previousProperties - The previous properties object that was supplied to the {@link module:maquette.h} method
*/
/**
* @callback afterCreateCallback
* @param {Element} element - The element that was added to the DOM.
* @param {Object} projectionOptions - The projection options that were used see {@link module:maquette.createProjector}.
* @param {string} vnodeSelector - The selector passed to the {@link module:maquette.h} function.
* @param {Object} properties - The properties passed to the {@link module:maquette.h} function.
* @param {VNode[]} children - The children that were created.
* @param {Object} properties - The last properties object that was supplied to the {@link module:maquette.h} method
* @param {Object} previousProperties - The previous properties object that was supplied to the {@link module:maquette.h} method
*/
/**
* @callback afterUpdateCallback
* @param {Element} element - The element that may have been updated in the DOM.
* @param {Object} projectionOptions - The projection options that were used see {@link module:maquette.createProjector}.
* @param {string} vnodeSelector - The selector passed to the {@link module:maquette.h} function.
* @param {Object} properties - The properties passed to the {@link module:maquette.h} function.
* @param {VNode[]} children - The children for this node.
*/
/**
* The main object in maquette is the maquette object.
* It is either bound to `window.maquette` or it can be obtained using {@link http://browserify.org/|browserify} or {@link http://requirejs.org/|requirejs}.
*/
declare module maquette {
export var dom: MaquetteDom;
/**
* Creates a {@link CalculationCache} object, useful for caching {@link VNode} trees.
* In practice, caching of {@link VNode} trees is not needed, because achieving 60 frames per second is almost never a problem.
* @returns {CalculationCache}
*/
export function createCache(): CalculationCache;
/**
* Creates a {@link Mapping} instance that keeps an array of result objects synchronized with an array of source objects.
* @param {function} getSourceKey - `function(source)` that must return a key to identify each source object. The result must eather be a string or a number.
* @param {function} createResult - `function(source, index)` that must create a new result object from a given source. This function is identical argument of `Array.map`.
* @param {function} updateResult - `function(source, target, index)` that updates a result to an updated source.
* @returns {Mapping}
*/
export function createMapping(getSourceKey: (source: any) => any, createResult: (source:any, index:number) => any, updateResult: (source: any, target: any, index: number) => void): Mapping;
/**
* Creates a {@link Projector} instance using the provided projectionOptions.
* @param {Object} [projectionOptions] - Options that influence how the DOM is rendered and updated.
* @param {Object} projectionOptions.transitions - A transition strategy to invoke when
* enterAnimation and exitAnimation properties are provided as strings.
* The module `cssTransitions` in the provided `css-transitions.js` file provides such a strategy.
* A transition strategy is not needed when enterAnimation and exitAnimation properties are provided as functions.
* @returns {Projector}
*/
export function createProjector(options? : any) : Projector;
/**
* The `h` method is used to create a virtual DOM node.
* This function is largely inspired by the mercuryjs and mithril frameworks.
* The `h` stands for (virtual) hyperscript.
*
* @param {string} selector - Contains the tagName, id and fixed css classnames in CSS selector format.
* It is formatted as follows: `tagname.cssclass1.cssclass2#id`.
* @param {Object} [properties] - An object literal containing properties that will be placed on the DOM node.
* @param {function} properties.<b>*</b> - Properties with functions values like `onclick:handleClick` are registered as event handlers
* @param {String} properties.<b>*</b> - Properties with string values, like `href:"/"` are used as attributes
* @param {object} properties.<b>*</b> - All non-string values are put on the DOM node as properties
* @param {Object} properties.key - Used to uniquely identify a DOM node among siblings.
* A key is required when there are more children with the same selector and these children are added or removed dynamically.
* @param {Object} properties.classes - An object literal like `{important:true}` which allows css classes, like `important` to be added and removed dynamically.
* @param {Object} properties.styles - An object literal like `{height:"100px"}` which allows styles to be changed dynamically. All values must be strings.
* @param {(string|enterAnimationCallback)} properties.enterAnimation - The animation to perform when this node is added to an already existing parent.
* {@link http://maquettejs.org/docs/animations.html|More about animations}.
* When this value is a string, you must pass a `projectionOptions.transitions` object when creating the projector {@link module:maquette.createProjector}.
* @param {(string|exitAnimationCallback)} properties.exitAnimation - The animation to perform when this node is removed while its parent remains.
* When this value is a string, you must pass a `projectionOptions.transitions` object when creating the projector {@link module:maquette.createProjector}.
* {@link http://maquettejs.org/docs/animations.html|More about animations}.
* @param {updateAnimationCallback} properties.updateAnimation - The animation to perform when the properties of this node change.
* This also includes attributes, styles, css classes. This callback is also invoked when node contains only text and that text changes.
* {@link http://maquettejs.org/docs/animations.html|More about animations}.
* @param {afterCreateCallback} properties.afterCreate - Callback that is executed after this node is added to the DOM. Childnodes and properties have already been applied.
* @param {afterUpdateCallback} properties.afterCreate - Callback that is executed every time this node may have been updated. Childnodes and properties have already been updated.
* @param {Object[]} [children] - An array of virtual DOM nodes to add as child nodes.
* This array may contain nested arrays, `null` or `undefined` values.
* Nested arrays are flattened, `null` and `undefined` will be skipped.
*
* @returns {VNode} A VNode object, used to render a real DOM later. NOTE: There are {@link http://maquettejs.org/docs/rules.html|three basic rules} you should be aware of when updating the virtual DOM.
*/
export function h(selector: string, properties?: any, children?: Array<string|VNode>): VNode;
/**
* A virtual representation of a DOM Node. Maquette assumes that {@link VNode} objects are never modified externally.
* Instances of {@link VNode} can be created using {@link module:maquette.h}.
*/
export interface VNode {
}
// Not used anywhere in the maquette sourcecode, but it is a widely used pattern.
export interface Component {
renderMaquette() : VNode;
}
/**
* A CalculationCache object remembers the previous outcome of a calculation along with the inputs.
* On subsequent calls the previous outcome is returned if the inputs are identical.
* This object can be used to bypass both rendering and diffing of a virtual DOM subtree.
* Instances of {@link CalculationCache} can be created using {@link module:maquette.createCache}.
*/
export interface CalculationCache {
/**
* Manually invalidates the cached outcome.
*/
invalidate(): void;
/**
* If the inputs array matches the inputs array from the previous invocation, this method returns the result of the previous invocation.
* Otherwise, the calculation function is invoked and its result is cached and returned.
* Objects in the inputs array are compared using ===.
* @param {Object[]} inputs - Array of objects that are to be compared using === with the inputs from the previous invocation.
* These objects are assumed to be immutable primitive values.
* @param {function} calculation - Function that takes zero arguments and returns an object (A {@link VNode} assumably) that can be cached.
*/
result(inputs: Array<any>, calculation: () => any):any;
}
/**
* Keeps an array of result objects synchronized with an array of source objects.
* Mapping provides a {@link Mapping#map} function that updates the {@link Mapping#results}.
* The {@link Mapping#map} function can be called multiple times and the results will get created, removed and updated accordingly.
* A {@link Mapping} can be used to keep an array of components (objects with a `renderMaquette` method) synchronized with an array of data.
* Instances of {@link Mapping} can be created using {@link module:maquette.createMapping}.
*/
export interface Mapping {
/**
* The array of results. These results will be synchronized with the latest array of sources that were provided using {@link Mapping#map}.
* @type {Object[]}
*/
results: Array<any>;
/**
* Maps a new array of sources and updates {@link Mapping#results}.
* @param {Object[]} newSources - The new array of sources.
*/
map(newSources: Array<any>): void;
}
/**
* Contains simple low-level utility functions to manipulate the real DOM. The singleton instance is available under {@link module:maquette.dom}.
*/
export interface MaquetteDom {
/**
* Appends a new childnode to the DOM which is generated from a {@link VNode}.
* This is a low-level method. Users wil typically use a {@link Projector} instead.
* @param {Element} parentNode - The parent node for the new childNode.
* @param {VNode} vnode - The root of the virtual DOM tree that was created using the {@link module:maquette.h} function. NOTE: {@link VNode} objects may only be rendered once.
* @param {Object} projectionOptions - Options to be used to create and update the projection, see {@link module:maquette.createProjector}.
* @returns {Projection} The {@link Projection} that was created.
*/
append(parentNode: Element, vnode: VNode, projectionOptions?: any): Projection;
/**
* Creates a real DOM tree from a {@link VNode}. The {@link Projection} object returned will contain the resulting DOM Node under the {@link Projection#domNode} property.
* This is a low-level method. Users wil typically use a {@link Projector} instead.
* @param {VNode} vnode - The root of the virtual DOM tree that was created using the {@link module:maquette.h} function. NOTE: {@link VNode} objects may only be rendered once.
* @param {Object} projectionOptions - Options to be used to create and update the projection, see {@link module:maquette.createProjector}.
* @returns {Projection} The {@link Projection} which contains the DOM Node that was created.
*/
create(vnode: VNode, projectionOptions?: any): Projection;
/**
* Inserts a new DOM node which is generated from a {@link VNode}.
* This is a low-level method. Users wil typically use a {@link Projector} instead.
* @param {Element} beforeNode - The node that the DOM Node is inserted before.
* @param {VNode} vnode - The root of the virtual DOM tree that was created using the {@link module:maquette.h} function. NOTE: {@link VNode} objects may only be rendered once.
* @param {Object} projectionOptions - Options to be used to create and update the projection, see {@link module:maquette.createProjector}.
* @returns {Projection} The {@link Projection} that was created.
*/
insertBefore(beforeNode: Element, vnode: VNode): Projection;
/**
* Merges a new DOM node which is generated from a {@link VNode} with an existing DOM Node.
* This means that the virtual DOM and real DOM have one overlapping element.
* Therefore the selector for the root {VNode} will be ignored, but its properties and children will be applied to the Element provided
* This is a low-level method. Users wil typically use a {@link Projector} instead.
* @param {Element} domNode - The existing element to adopt as the root of the new virtual DOM. Existing attributes and childnodes are preserved.
* @param {VNode} vnode - The root of the virtual DOM tree that was created using the {@link module:maquette.h} function. NOTE: {@link VNode} objects may only be rendered once.
* @param {Object} projectionOptions - Options to be used to create and update the projection, see {@link module:maquette.createProjector}.
* @returns {Projection} The {@link Projection} that was created.
*/
merge(domNode: Element, vnode: VNode): Projection;
}
/**
* Represents a {@link VNode} tree that has been rendered to a real DOM tree.
*/
export interface Projection {
/**
* Updates the projection with the new virtual DOM tree.
* @param {VNode} updatedVnode - The updated virtual DOM tree. Note: The selector for the root of the tree must remain constant.
*/
update(updatedVnode:VNode): void;
/**
* The DOM node that is used as the root of this {@link Projection}.
* @type {Element}
*/
domNode: Element;
}
/**
* Used to create and update the DOM.
* Use {@link Projector#append}, {@link Projector#merge}, {@link Projector#insertBefore} and {@link Projector#replace}
* to create the DOM.
* The `renderMaquetteFunction` callbacks will be called immediately to create the DOM. Afterwards, these functions
* will be called again to update the DOM on the next animation-frame after:
*
* - The {@link Projector#scheduleRender} function was called
* - An event handler (like `onclick`) on a rendered {@link VNode} was called.
*
* The projector stops when {@link Projector#stop} is called or when an error is thrown during rendering.
* It is possible to use `window.onerror` to handle these errors.
* Instances of {@link Projector} can be created using {@link module:maquette.createProjector}.
*/
export interface Projector {
/**
* Appends a new childnode to the DOM using the result from the provided `renderMaquetteFunction`.
* The `renderMaquetteFunction` will be invoked again to update the DOM when needed.
* @param {Element} parentNode - The parent node for the new childNode.
* @param {function} renderMaquetteFunction - Function with zero arguments that returns a {@link VNode} tree.
*/
append(parentNode: Element, renderMaquette: () => VNode): void;
/**
* Scans the document for `<script>` tags with `type="text/hyperscript"`.
* The content of these scripts are registered as `renderMaquette` functions.
* The result of evaluating these functions will be inserted into the DOM after the script.
* These scripts can make use of variables that come from the `parameters` parameter.
* @param {Element} rootNode - Element to start scanning at, example: `document.body`.
* @param {Object} parameters - Variables to expose to the scripts. format: `{var1:value1, var2: value2}`
*/
evaluateHyperscript(rootNode: Element, parameters: any): void;
/**
* Inserts a new DOM node using the result from the provided `renderMaquetteFunction`.
* The `renderMaquetteFunction` will be invoked again to update the DOM when needed.
* @param {Element} beforeNode - The node that the DOM Node is inserted before.
* @param {function} renderMaquetteFunction - Function with zero arguments that returns a {@link VNode} tree.
*/
insertBefore(beforeNode: Element, renderMaquette: () => VNode): void;
/**
* Merges a new DOM node using the result from the provided `renderMaquetteFunction` with an existing DOM Node.
* This means that the virtual DOM and real DOM have one overlapping element.
* Therefore the selector for the root {VNode} will be ignored, but its properties and children will be applied to the Element provided
* The `renderMaquetteFunction` will be invoked again to update the DOM when needed.
* @param {Element} domNode - The existing element to adopt as the root of the new virtual DOM. Existing attributes and childnodes are preserved.
* @param {function} renderMaquetteFunction - Function with zero arguments that returns a {@link VNode} tree.
*/
merge(domNode: Element, renderMaquette: () => VNode): void;
/**
* Replaces an existing DOM node with the result from the provided `renderMaquetteFunction`.
* The `renderMaquetteFunction` will be invoked again to update the DOM when needed.
* @param {Element} domNode - The DOM node to replace.
* @param {function} renderMaquetteFunction - Function with zero arguments that returns a {@link VNode} tree.
*/
replace(domNode: Element, renderMaquette: () => VNode): void;
/**
* Resumes the projector. Use this method to resume rendering after stop was called or an error occurred during rendering.
*/
resume(): void;
/**
* Instructs the projector to re-render to the DOM at the next animation-frame using the registered `renderMaquette` functions.
* This method is automatically called for you when event-handlers that are registered in the {@link VNode}s are invoked.
* You need to call this method for instance when timeouts expire or AJAX responses arrive.
*/
scheduleRender(): void;
/**
* Stops the projector. This means that the registered `renderMaquette` functions will not be called anymore.
* Note that calling {@link Projector#stop} is not mandatory. A projector is a passive object that will get garbage collected as usual if it is no longer in scope.
*/
stop(): void;
}
}
declare module 'maquette' {
export = maquette;
}
+1 -1
View File
@@ -135,7 +135,7 @@ declare module "mongoose" {
}
export interface Model<T extends Document> extends NodeJS.EventEmitter {
new(doc: Object): T;
new(doc?: Object): T;
aggregate(...aggregations: Object[]): Aggregate<T[]>;
aggregate(aggregation: Object, callback: (err: any, res: T[]) => void): Promise<T[]>;
+84 -3
View File
@@ -1,14 +1,95 @@
// Type definitions for multer
// Project: https://github.com/expressjs/multer
// Definitions by: jt000 <https://github.com/jt000>
// Definitions by: jt000 <https://github.com/jt000>, vilicvane <https://vilic.github.io/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module Express {
export interface Request {
files: {
[fieldname: string]: {
/** Field name specified in the form */
fieldname: string;
/** Name of the file on the user's computer */
originalname: string;
/** Renamed file name */
name: string;
/** Encoding type of the file */
encoding: string;
/** Mime type of the file */
mimetype: string;
/** Location of the uploaded file */
path: string;
/** Extension of the file */
extension: string;
/** Size of the file in bytes */
size: number;
/** If the file was truncated due to size limitation */
truncated: boolean;
/** Raw data (is null unless the inMemory option is true) */
buffer: Buffer;
}
}
}
}
declare module "multer" {
import express = require('express');
function multer(options?: any): express.RequestHandler;
function multer(options?: multer.Options): express.RequestHandler;
module multer {
type Options = {
/** The destination directory for the uploaded files. */
dest?: string;
/** An object specifying the size limits of the following optional properties. This object is passed to busboy directly, and the details of properties can be found on https://github.com/mscdex/busboy#busboy-methods */
limits?: {
/** Max field name size (Default: 100 bytes) */
fieldNameSize?: number;
/** Max field value size (Default: 1MB) */
fieldSize?: number;
/** Max number of non- file fields (Default: Infinity) */
fields?: number;
/** For multipart forms, the max file size (in bytes)(Default: Infinity) */
fileSize?: number;
/** For multipart forms, the max number of file fields (Default: Infinity) */
files?: number;
/** For multipart forms, the max number of parts (fields + files)(Default: Infinity) */
parts?: number;
/** For multipart forms, the max number of header key=> value pairs to parse Default: 2000(same as node's http). */
headerPairs?: number;
};
/** A Boolean value to specify whether empty submitted values should be processed and applied to req.body; defaults to false; */
includeEmptyFields?: boolean;
/** If this Boolean value is true, the file.buffer property holds the data in-memory that Multer would have written to disk. The dest option is still populated and the path property contains the proposed path to save the file. Defaults to false. */
inMemory?: boolean;
/** Function to rename the uploaded files. Whatever the function returns will become the new name of the uploaded file (extension is not included). The fieldname and filename of the file will be available in this function, use them if you need to. */
rename?: (fieldname: string, filename: string, req: Express.Request, res: Express.Response) => string;
/** Function to rename the directory in which to place uploaded files. The dest parameter is the default value originally assigned or passed into multer. The req and res parameters are also passed into the function because they may contain information (eg session data) needed to create the path (eg get userid from the session). */
changeDest?: (dest: string, req: Express.Request, res: Express.Response) => string;
/** Event handler triggered when a file starts to be uploaded. A file object, with the following properties, is available to this function: fieldname, originalname, name, encoding, mimetype, path, and extension. */
onFileUploadStart?: (file: string, req: Express.Request, res: Express.Response) => void;
/** Event handler triggered when a chunk of buffer is received. A buffer object along with a file object is available to the function. */
onFileUploadData?: (file: string, data: Buffer, req: Express.Request, res: Express.Response) => void;
/** Event handler trigger when a file is completely uploaded. A file object is available to the function. */
onFileUploadComplete?: (file: string, req: Express.Request, res: Express.Response) => void;
/** Event handler triggered when the form parsing starts. */
onParseStart?: () => void;
/** Event handler triggered when the form parsing completes. The request object and the next objects are are passed to the function. */
onParseEnd?: (req: Express.Request, next: () => void) => void;
/** Event handler for any errors encountering while processing the form. The error object and the next object is available to the function. If you are handling errors yourself, make sure to terminate the request or call the next() function, else the request will be left hanging. */
onError?: () => void;
/** Event handler triggered when a file size exceeds the specification in the limit object. No more files will be parsed after the limit is reached. */
onFileSizeLimit?: (file: string) => void;
/** Event handler triggered when the number of files exceed the specification in the limit object. No more files will be parsed after the limit is reached. */
onFilesLimit?: () => void;
/** Event handler triggered when the number of fields exceed the specification in the limit object. No more fields will be parsed after the limit is reached. */
onFieldsLimit?: () => void;
/** Event handler triggered when the number of parts exceed the specification in the limit object. No more files or fields will be parsed after the limit is reached. */
onPartsLimit?: () => void;
};
}
export = multer;
}
}
+1
View File
@@ -83,6 +83,7 @@ declare module NodeJS {
code?: string;
path?: string;
syscall?: string;
stack?: string;
}
export interface EventEmitter {
+1
View File
@@ -83,6 +83,7 @@ declare module NodeJS {
code?: string;
path?: string;
syscall?: string;
stack?: string;
}
export interface EventEmitter {
+1
View File
@@ -73,6 +73,7 @@ interface ErrnoException extends Error {
code?: string;
path?: string;
syscall?: string;
stack?: string;
}
interface EventEmitter {
+1
View File
@@ -144,6 +144,7 @@ declare module NodeJS {
code?: string;
path?: string;
syscall?: string;
stack?: string;
}
export interface EventEmitter {
File diff suppressed because it is too large Load Diff
+93
View File
@@ -0,0 +1,93 @@
/// <reference path="openlayers.d.ts" />
// Attribution
var attribution: ol.Attribution = new ol.Attribution({
html: "",
});
// View
var view: ol.View = new ol.View({
center: [0, 0],
zoom: 1,
});
// Tile layer
var tileLayer: ol.layer.Tile = new ol.layer.Tile({
source: new ol.source.MapQuest({ layer: 'osm' })
});
// Map
var map: ol.Map = new ol.Map({
view: view,
layers: [ tileLayer ],
target: 'map'
});
// Animation
var bounce = ol.animation.bounce({
resolution: map.getView().getResolution(),
duration: 1000,
start: 0,
});
var pam = ol.animation.pan({
duration: 1000,
start: 0,
source: [0, 0]
});
var rotate = ol.animation.rotate({
duration: 1000,
start: 0,
anchor: [0, 0],
resolution: map.getView().getResolution()
});
var zoom = ol.animation.zoom({
duration: 1000,
start: 0,
resolution: map.getView().getResolution()
});
map.beforeRender(zoom);
map.getView().setResolution(map.getView().getResolution() * 2);
// Geolocation
var geolocation: ol.Geolocation = new ol.Geolocation({
// take the projection to use from the map's view
projection: view.getProjection()
});
geolocation.on('change', function (evt) {
window.console.log(geolocation.getPosition());
});
// Graticule
var graticule: ol.Graticule = new ol.Graticule();
var graticule: ol.Graticule = new ol.Graticule({
map: map,
});
var graticuleMap: ol.Map = graticule.getMap();
var graticuleMeridians: Array<ol.geom.LineString> = graticule.getMeridians();
var graticuleParallels: Array<ol.geom.LineString> = graticule.getParallels();
graticule.setMap(graticuleMap);
// Device orientation
var deviceOrientation: ol.DeviceOrientation = new ol.DeviceOrientation({
tracking: true,
});
deviceOrientation.on('change', function (evt) {
window.console.log(deviceOrientation.getHeading());
});
// Overlay
var popup: ol.Overlay = new ol.Overlay({
element: document.getElementById('popup')
});
popup.setPosition([10, 10]);
map.addOverlay(popup);
var popupElement: Element = popup.getElement();
var popupMap: ol.Map = popup.getMap();
var popupOffset: Array<number> = popup.getOffset();
var popupCoordinate: ol.Coordinate = popup.getPosition();
var popupPositioning: ol.OverlayPositioning = popup.getPositioning();
popup.setElement(popupElement);
popup.setMap(popupMap);
popup.setOffset(popupOffset);
popup.setPosition(popupCoordinate);
popup.setPositioning(popupPositioning);
+2762 -5020
View File
File diff suppressed because it is too large Load Diff
+115
View File
@@ -0,0 +1,115 @@
/// <reference path="packery.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
import Packery = require('packery');
// TODO Add Draggabilly to bind Draggabilly Events
var container = document.querySelector('#container');
var item = document.querySelector('.item');
var items = document.querySelectorAll('.item');
var $element = $('#single-item');
var PackeryEvents = {
dragItemPositioned: 'dragItemPositioned',
layoutComplete: 'layoutComplete',
fitComplete: 'fitComplete',
removeComplete: 'removeComplete'
};
var packery = new Packery(container);
var PackeryItems: Array<any> = [
packery.data(item),
packery.data(item),
packery.data(item),
packery.data(item),
packery.data(item)
];
packery.addItems(item);
packery.addItems(items);
packery.appended(item);
packery.appended(items);
packery.bindResize();
packery.bindDraggabillyEvents($element);
packery.fit(item);
packery.fit(item, 10);
packery.fit(item, 10, 50);
packery.getItemElements();
packery.getItem(item);
packery.layout();
packery.layoutItems(PackeryItems);
packery.off(PackeryEvents.dragItemPositioned, () => {
// Some actions to execute on event trigger
});
packery.off(PackeryEvents.layoutComplete, () => {
// Some actions to execute on event trigger
});
packery.off(PackeryEvents.removeComplete, () => {
// Some actions to execute on event trigger
});
packery.off(PackeryEvents.fitComplete, () => {
// Some actions to execute on event trigger
});
packery.on(PackeryEvents.dragItemPositioned, () => {
// Some actions to execute on event trigger
});
packery.on(PackeryEvents.layoutComplete, () => {
// Some actions to execute on event trigger
});
packery.on(PackeryEvents.removeComplete, () => {
// Some actions to execute on event trigger
});
packery.on(PackeryEvents.fitComplete, () => {
// Some actions to execute on event trigger
});
packery.once(PackeryEvents.dragItemPositioned, () => {
// Some actions to execute on event trigger
});
packery.once(PackeryEvents.layoutComplete, () => {
// Some actions to execute on event trigger
});
packery.once(PackeryEvents.removeComplete, () => {
// Some actions to execute on event trigger
});
packery.once(PackeryEvents.fitComplete, () => {
// Some actions to execute on event trigger
});
packery.data(item);
packery.prepended(item);
packery.prepended(items);
packery.reloadItems();
packery.remove(item);
packery.remove(items);
packery.stamp(item);
packery.stamp(items);
packery.unbindResize();
packery.unstamp(item);
packery.unstamp(items);
+294
View File
@@ -0,0 +1,294 @@
// Type definitions for Packery v1.4.1
// Project: http://packery.metafizzy.co
// Definitions by: Piraveen Kamalathas from Kilix <https://github.com/piraveen>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "packery" {
interface PackeryOptions {
/**
* [itemSelector Specifies which child elements to be used as item elements. Setting itemSelector is always recommended. itemSelector is useful to exclude sizing elements]
* @type {string}
*/
itemSelector?: string;
/**
* [columnWidth The width of a column of a horizontal grid. When set, Packery will align item elements horizontally to this grid]
* @type {number}
*/
columnWidth?: number;
/**
* [rowHeight Height of a row of a vertical grid. When set, Packery will align item elements vertically to this grid]
* @type {number}
*/
rowHeight?: number;
/**
* [gutter The space between item elements, both vertically and horizontally]
* @type {number}
*/
gutter?: number;
/**
* [percentPosition Will set item position in percent values, rather than pixel values. percentPosition works well with percent-width items, as items will not transition their position on resize]
* @type {boolean}
*/
percentPosition?: boolean;
/**
* [stamp Specifies which elements are stamped within the layout. These are special layout elements which will not be laid out by Packery. Rather, Packery will layout item elements around stamped elements]
* @type {string}
*/
stamp?: string;
/**
* [isHorizontal Arranges items horizontally instead of vertically]
* @type {boolean}
*/
isHorizontal?: boolean;
/**
* [isOriginLeft Controls the horizontal flow of the layout. By default, item elements start positioning at the left. Set to false for right-to-left layouts]
* @type {boolean}
*/
isOriginLeft?: boolean;
/**
* [isOriginTop Controls the vertical flow of the layout. By default, item elements start positioning at the top. Set to false for bottom-up layouts. Its like Tetris!]
* @type {boolean}
*/
isOriginTop?: boolean;
/**
* [transitionDuration The time duration of transitions for item elements]
* @type {string}
*/
transitionDuration?: string;
/**
* [containerStyle CSS styles that are applied to the container element. To disable Packery from setting any CSS to the container element, set containerStyle: null]
* @type {Object}
*/
containerStyle?: Object;
/**
* [isResizeBound Binds layout to window resizing]
* @type {boolean}
*/
isResizeBound?: boolean;
/**
* [isInitLayout Enables layout on initialization. Set this to false to disable layout on initialization, so you can use methods or add events before the initial layout]
* @type {boolean}
*/
isInitLayout?: boolean;
}
class Packery {
constructor(element: Element, options?: Object);
/**
* [addItems Add item elements to the Packery instance]
* @param {Element} elements [description]
*/
addItems(elements: Element): void;
/**
* [addItems Add item elements to the Packery instance]
* @param {NodeList} elements [description]
*/
addItems(elements: NodeList): void;
/**
* [addItems Add item elements to the Packery instance]
* @param {Array<Element>} elements [description]
*/
addItems(elements: Array<Element>): void;
/**
* [appended Add and lay out newly appended item elements]
* @param {Element} elements [description]
*/
appended(elements: Element): void;
/**
* [appended Add and lay out newly appended item elements]
* @param {NodeList} elements [description]
*/
appended(elements: NodeList): void;
/**
* [appended Add and lay out newly appended item elements]
* @param {Array<Element>} elements [description]
*/
appended(elements: Array<Element>): void;
/**
* [bindDraggabillyEvents Bind Draggabilly events, so that the Packery instance will layout around the dragged element]
* @param {any} draggie [description]
*/
bindDraggabillyEvents(draggie: any): void;
/**
* [bindResize Binds event listener to window resize, so layout is triggered when the browser window is resized]
*/
bindResize(): void;
/**
* [bindUIDraggableEvents Bind jQuery UI Draggable events, so that the Packery instance will layout around the dragged element]
* @param {any} elements [jQuery UI]
*/
bindUIDraggableEvents($element: any): void;
/**
* [data Get the Packery instance from an element. Note this method is of Packery, rather than of a Packery instance]
* @param {Element} element [description]
* @return {Packery} [description]
*/
data(element: Element): Packery;
/**
* [destroy Removes the Packery functionality completely. This will return the element back to its pre-initialized state]
*/
destroy(): void;
/**
* [fit Fit an item element within the layout, and have other item elements laid out around it. This method is useful when expanding an element, and keeping it in its same position.]
* @param {any} element [description]
* @param {number} x [description]
* @param {number} y [description]
*/
fit(element: Element, x ?: number, y ?: number): void;
/**
* [getItemElements Get an array of elements used as the Packery instance's items.]
* @return {Array<Element>} [description]
*/
getItemElements(): Array<Element>;
/**
* [getItem Get a Packery.Item from an element]
* @param {Element} element [description]
* @return {any} [Packery.item]
*/
getItem(element: Element): any;
/**
* [layout Lay out all item elements.]
*/
layout(): void;
/**
* [layoutItems Lay out specified items]
* @param {Array<Packery.items>} items [description]
*/
layoutItems(items: Array<any>): void;
/**
* [off Remove an event listener]
* @param {string} eventName [description]
* @param {Function} listener [description]
* @return {Packery} [description]
*/
off(eventName: string, listener: Function): Packery;
/**
* [on Add an event listener for certain events]
* @param {string} eventName [description]
* @param {Function} listener [description]
* @return {Packery} [description]
*/
on(eventName: string, listener: Function): Packery;
/**
* [once Add an event listener for certain events, to be triggered once]
* @param {string} eventName [description]
* @param {Function} listener [description]
*/
once(eventName: string, listener: Function): void;
/**
* [prepended Add and lay out newly prepended item elements at the beginning of layout]
* @param {Element} elements [description]
*/
prepended(elements: Element): void;
/**
* [prepended Add and lay out newly prepended item elements at the beginning of layout]
* @param {NodeList} elements [description]
*/
prepended(elements: NodeList): void;
/**
* [prepended Add and lay out newly prepended item elements at the beginning of layout]
* @param {Array<Element>} elements [description]
*/
prepended(elements: Array<Element>): void;
/**
* [reloadItems Recollect all item elements]
*/
reloadItems(): void;
/**
* [remove Remove elements from the Packery instance, then from the DOM]
* @param {Element} elements [description]
*/
remove(elements: Element): void;
/**
* [remove Remove elements from the Packery instance, then from the DOM]
* @param {NodeList} elements [description]
*/
remove(elements: NodeList): void;
/**
* [remove Remove elements from the Packery instance, then from the DOM]
* @param {Array<Element>} elements [description]
*/
remove(elements: Array<Element>): void;
/**
* [stamp Stamp the elements in the layout. Packery will lay out item elements around stamped element]
* @param {Element} elements [description]
*/
stamp(elements: Element): void;
/**
* [stamp Stamp the elements in the layout. Packery will lay out item elements around stamped element]
* @param {NodeList} elements [description]
*/
stamp(elements: NodeList): void;
/**
* [stamp Stamp the elements in the layout. Packery will lay out item elements around stamped element]
* @param {Array<Element>} elements [description]
*/
stamp(elements: Array<Element>): void;
/**
* [unbindResize Un-bind layout to window resize event]
*/
unbindResize(): void;
/**
* [unstamp Un-stamp the elements, so that Packery will no longer layout item elements around them]
* @param {Element} element [description]
*/
unstamp(element: Element): void;
/**
* [unstamp Un-stamp the elements, so that Packery will no longer layout item elements around them]
* @param {NodeList} element [description]
*/
unstamp(element: NodeList): void;
/**
* [unstamp Un-stamp the elements, so that Packery will no longer layout item elements around them]
* @param {Array<Element>} element [description]
*/
unstamp(element: Array<Element>): void;
}
export = Packery;
}
+136
View File
@@ -0,0 +1,136 @@
/// <reference path="pdfkit.d.ts" />
import PDFGradient = require("pdfkit/js/gradient");
var PDFRadialGradiant = PDFGradient.PDFRadialGradiant;
var PDFLinearGradient = PDFGradient.PDFLinearGradient;
import mtext = require("pdfkit/js/mixins/text");
import PDFDocument = require("pdfkit");
import font = require("pdfkit/js/mixins/fonts");
import pdfData = require("pdfkit/js/data");
import text = require("pdfkit/js/mixins/text");
font.registerFont("Arial");
text.widthOfString("Kila",{ellipsis:true});
var doc = new PDFDocument({compress:false, sizes:[526,525],autoFirstPage:true});
doc.addPage({
margin: 50
});
doc.addPage({
margins: {
top: 50,
bottom: 50,
left: 72,
right: 72
}
});
doc.info.Title = "Sample";
doc.info.Author = "kila Mogrosso";
// Create basic shapes
doc.moveTo(0,20)
.lineTo(100,160)
.quadraticCurveTo(130,200,150,120)
.lineTo(400,90)
.stroke();
//SVG Paths
doc.path("M 0,20 L 100,160 Q 130,200 150,120 C 190,-40 200,200 300,150 L 400,90")
.stroke();
//Rectangle shape helper sample
doc.rect(100,200,100,100);
//polygon
doc.polygon([100,0],[50,100],[50,100]);
doc.lineWidth(25);
doc.lineCap('butt').moveTo(50, 20).lineTo(100, 20).stroke();
doc.lineCap('round').moveTo(150, 20).lineTo(200, 20).stroke();
doc.lineCap('square').moveTo(250, 20).circle(275, 30, 15).stroke();
doc.lineJoin('miter').rect(50, 100, 50, 50).stroke();
doc.lineJoin('round').rect(150, 100, 50, 50).stroke();
doc.lineJoin('bevel').rect(250, 100, 50, 50).stroke();
doc.circle(100, 50, 50)
.lineWidth(3)
.fillOpacity(0.8)
.fillAndStroke("red", "#900");
var grad = doc.linearGradient(50, 0, 150, 100)
.stop(0, 'green')
.stop(1, 'red');
doc.rect(50, 0, 100, 100)
.fill(grad);
doc.circle(100, 50, 50).dash(5, {
space: 10
}).stroke();
var rgrad = doc.radialGradient(300, 50, 0, 300, 50, 50);
rgrad.stop(0, 'orange', 0).stop(1, 'orange', 1);
doc.circle(300, 50, 50)
.fill(rgrad);
doc.fillColor('red')
.translate(-100, -50)
.scale(0.8);
doc.path('M 250,75 L 323,301 131,161 369,161 177,301 z')
.fill('non-zero');
doc.translate(280, 0)
.path('M 250,75 L 323,301 131,161 369,161 177,301 z')
.fill('even-odd');
doc.circle(100,100,100)
.clip();
doc.fontSize(25)
.fillColor('blue')
.text('This is a link!', 20, 0);
var width = doc.widthOfString('This is a link!');
var height = doc.currentLineHeight();
doc.underline(20, 0, width, height, {
color: 'blue'
}).link(20, 0, width, height, 'http://google.com/');
doc.moveDown()
.fillColor('black')
.highlight(20, doc.y, doc.widthOfString('This text is highlighted!'), height)
.text('This text is highlighted!');
doc.moveDown()
.strike(20, doc.y, doc.widthOfString('STRIKE!'), height)
.text('STRIKE!');
doc.image('images/test.jpeg', 0, 15, {
width: 300
}).text('Proprotional to width', 0, 0);
doc.image('images/test.jpeg', 320, 15, {
fit: [100, 100]
}).rect(320, 15, 100, 100).stroke().text('Fit', 320, 0);
doc.image('images/test.jpeg', 320, 145, {
width: 200,
height: 100
}).text('Stretch', 320, 130);
doc.image('images/test.jpeg', 320, 280, {
scale: 0.25
}).text('Scale', 320, 265);
+390
View File
@@ -0,0 +1,390 @@
// Type definitions for Pdfkit v0.7.1
// Project: http://pdfkit.org
// Definitions by: Eric Hillah <https://github.com/erichillah>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module PDFKit {
interface PDFGradient {
new(document: any): PDFGradient ;
stop(pos: number, color?: string|PDFKit.PDFGradient, opacity?: number): PDFGradient;
embed(): void;
apply(): void;
}
interface PDFLinearGradient extends PDFGradient {
new(document: any, x1: number, y1: number, x2: number, y2: number): PDFLinearGradient;
shader(fn: () => any): any;
opacityGradient(): PDFLinearGradient;
}
interface PDFRadialGradient extends PDFGradient {
new(document: any, x1: number, y1: number, x2: number, y2: number): PDFRadialGradient;
shader(fn: () => any): any;
opacityGradient(): PDFRadialGradient;
}
}
declare module PDFKit.Mixins {
interface AnnotationOption {
Type?: string;
Rect?: any;
Border?: Array<number>;
SubType?: string;
Contents?: string;
Name?: string;
color?: string;
QuadPoints?: Array<number>;
A?: any;
B?: any;
C?: any;
L?: any;
DA?: string;
}
interface PDFAnnotation<TDocument> {
annotate(x: number, y: number, w: number, h: number, option: AnnotationOption): TDocument;
note(x: number, y: number, w: number, h: number, content: string, option?: AnnotationOption): TDocument;
link(x: number, y: number, w: number, h: number, url: string, option?: AnnotationOption): TDocument;
highlight(x: number, y: number, w: number, h: number, option?: AnnotationOption): TDocument;
underline(x: number, y: number, w: number, h: number, option?: AnnotationOption): TDocument;
strike(x: number, y: number, w: number, h: number, option?: AnnotationOption): TDocument;
lineAnnotation(x1: number, y1: number, x2: number, y2: number, option?: AnnotationOption): TDocument;
rectAnnotation(x: number, y: number, w: number, h: number, option?: AnnotationOption): TDocument;
ellipseAnnotation(x: number, y: number, w: number, h: number, option?: AnnotationOption): TDocument;
textAnnotation(x: number, y: number, w: number, h: number, text: string, option?: AnnotationOption): TDocument;
}
interface PDFColor<TDocument> {
fillColor(color: string|PDFGradient, opacity?: number): TDocument;
strokeColor(color: string, opacity?: number): TDocument;
opacity(opacity: number): TDocument;
fillOpacity(opacity: number): TDocument;
strokeOpacity(opacity: number): TDocument;
linearGradient(x1: number, y1: number, x2: number, y2: number): PDFLinearGradient;
radialGradient(x1: number, y1: number, r1: number, x2: number, y2: number, r2: number): PDFRadialGradient;
}
interface PDFFont<TDocument> {
font(src: string, family?: string, size?: number): TDocument;
fontSize(size: number): TDocument;
currentLineHeight(includeGap?: boolean): number;
registerFont(name: string, src?: string, family?: string): TDocument;
}
interface ImageOption {
width?: number;
height?: number;
/** Scale percentage */
scale?: number;
/** Two elements array specifying dimensions(w,h) */
fit?: number[];
}
interface PDFImage {
/**
* Draw an image in PDFKit document.
* No need chainning capabilities
*/
image(src: any, x: number, y: number, options: ImageOption): any;
}
interface TextOptions {
/** Set to false to disable line wrapping all together */
lineBreak?: boolean;
/** The width that text should be wrapped to (by default, the page width minus the left and right margin) */
width?: number;
/** The maximum height that text should be clipped to */
height?: number;
/** The character to display at the end of the text when it is too long. Set to true to use the default character. */
ellipsis?: boolean|string;
/** the number of columns to flow the text into */
columns?: number;
/** the amount of space between each column (1/4 inch by default) */
columnGap?: number;
/** The amount in PDF points (72 per inch) to indent each paragraph of text */
indent?: number;
/** the amount of space between each paragraph of text */
paragrahGap?: number;
/** the amount of space between each line of text */
lineGap?: number;
/** the amount of space between each word in the text */
wordSpacing?: number;
/** the amount of space between each character in the text */
characterSpacing?: number;
/** whether to fill the text (true by default) */
fill?: boolean;
/** whether to stroke the text */
stroke?: boolean;
/** A URL to link this text to (shortcut to create an annotation) */
link?: string;
/** whether to underline the text */
underline?: boolean;
/** whether to strike out the text */
strike?: boolean;
/**whether the text segment will be followed immediately by another segment. Useful for changing styling in the middle of a paragraph. */
continued?: boolean;
}
interface PDFText<TDocument> {
lineGap(lineGap: number): TDocument;
moveDown(line?: number): TDocument;
moveUp(line?: number): TDocument;
text(text: string, x?: number, y?: number, options?: TextOptions): TDocument;
text(text: string, options?: TextOptions): TDocument;
widthOfString(text: string, options?: TextOptions): number;
heightOfString(text: string, options?: TextOptions): number;
list(list: Array<string|any>, x?: number, y?: number, options?: TextOptions): TDocument;
list(list: Array<string|any>, options?: TextOptions): TDocument;
}
interface PDFVector<TDocument> {
save(): TDocument;
restore(): TDocument;
closePath(): TDocument;
lineWidth(w: number): TDocument;
lineCap(c: string): TDocument;
lineJoin(j: string): TDocument;
miterLimit(m: any): TDocument;
dash(length: number, option: any): TDocument;
undash(): TDocument;
moveTo(x: number, y: number): TDocument;
lineTo(x: number, y: number): TDocument;
bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): TDocument;
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): TDocument;
rect(x: number, y: number, w: number, h: number): TDocument;
roundRect(x: number, y: number, w: number, h: number, r?: number): TDocument;
ellipse(x: number, y: number, r1: number, r2?: number): TDocument;
circle(x: number, y: number, raduis: number): TDocument;
polygon(...points: number[][]): TDocument;
path(path: string): TDocument;
fill(color: string|PDFKit.PDFGradient, rule?: string): TDocument;
stroke(color?: string|PDFKit.PDFGradient): TDocument;
fillAndStroke(fillColor: string, strokeColor?: string, rule?: string): TDocument;
clip(rule?: string): TDocument;
transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): TDocument;
translate(x: number, y: number): TDocument;
rotate(angle: number, options?: { origin?: number[] }): TDocument;
scale(xFactor: number, yFactor?: number, options?: { origin?: number[] }): TDocument;
}
}
declare module PDFKit {
/**
* PDFKit data
*/
interface PDFData {
new (data: any[]): PDFData;
readByte(): any;
writeByte(byte: any): void;
byteAt(index: number): any;
readBool(): boolean;
writeBool(val: boolean): boolean;
readUInt32(): number;
writeUInt32(val: number): void;
readInt32(): number;
writeInt32(val: number): void;
readUInt16(): number;
writeUInt16(val: number): void;
readInt16(): number;
writeInt16(val: number): void;
readString(length: number): string;
writeString(val: string): void;
stringAt(pos: number, length: number): string;
readShort(): number;
writeShort(val: number): void;
readLongLong(): number;
writeLongLong(val: number): void;
readInt(): number;
writeInt(val: number): void;
slice(start: number, end: number): any[];
read(length: number): any[];
write(bytes: any[]): void;
}
}
declare module "pdfkit/js/data" {
var PDFKitData: PDFKit.PDFData;
export = PDFKitData;
}
declare module PDFKit {
interface DocumentInfo {
Producer?: string;
Creator?: string;
CreationDate?: Date;
Title?: string;
Author?: string;
Keywords?: string;
ModDate?: Date;
}
interface PDFDocumentOptions {
compress?: boolean;
info?: DocumentInfo;
autoFirstPage?: boolean;
sizes?: number[];
margin?: { top: number; left: number; bottom: number; right: number }|number;
bufferPages?: boolean;
}
interface PDFDocument extends NodeJS.ReadableStream,
Mixins.PDFAnnotation<PDFDocument>, Mixins.PDFColor<PDFDocument>, Mixins.PDFImage,
Mixins.PDFText<PDFDocument>, Mixins.PDFVector<PDFDocument>, Mixins.PDFFont<PDFDocument> {
/**
* PDF Version
*/
version: number;
/**
* Wheter streams should be compressed
*/
compress: boolean;
/**
* PDF document Metadata
*/
info: DocumentInfo;
/**
* Options for the document
*/
options: PDFDocumentOptions;
/**
* Represent the current page.
*/
page: PDFPage;
x: number;
y: number;
new (options?: PDFDocumentOptions): PDFDocument;
addPage(options?: PDFDocumentOptions): PDFDocument;
bufferedPageRanges(): { start: number; count: number };
switchToPage(n?: number): PDFPage;
flushPages(): void;
ref(data: {}): PDFKitReference;
addContent(data: any): PDFDocument
/**
* Deprecated
*/
write(fileName: string, fn: any): void;
/**
* Deprecated. Throws exception
*/
output(fn: any): void;
end(): void;
toString(): string;
}
}
declare module "pdfkit" {
var doc: PDFKit.PDFDocument;
export = doc;
}
declare module "pdfkit/js/gradient" {
var gradient : {
PDFGradient: PDFKit.PDFGradient;
PDFLinearGradient: PDFKit.PDFLinearGradient;
PDFRadialGradiant: PDFKit.PDFRadialGradient;
}
export = gradient;
}
declare module PDFKit {
/**
* Represent a single page in the PDF document
*/
interface PDFPage {
size: string;
layout: string;
margin: { top: number; left: number; bottom: number; right: number }|number;
width: number;
height: number;
document: PDFDocument;
content: PDFKitReference;
/**
* The page dictionnary
*/
dictionary: PDFKitReference;
fonts: any;
xobjects: any;
ext_gstates: any;
patterns: any;
annotations: any;
maxY(): number;
write(chunk: any): void;
end(): void;
}
}
declare module "pdfkit/js/page" {
var PDFKitPage: PDFKit.PDFPage
export = PDFKitPage
}
declare module PDFKit {
/** PDFReference - represents a reference to another object in the PDF object heirarchy */
class PDFKitReference {
id: number;
gen: number;
deflate:any;
compress: boolean;
uncompressedLength: number;
chunks: any[];
data: { Font?: any; XObject?: any; ExtGState?: any; Pattern: any; Annots: any };
document: PDFDocument;
constructor(document: PDFDocument, id: number, data: {});
initDeflate(): void;
write(chunk: any): void;
end(chunk: any): void;
finalize(): void;
toString(): string;
}
}
declare module "pdfkit/js/reference" {
var PDFKitReference: PDFKit.PDFKitReference;
export = PDFKitReference;
}
declare module "pdfkit/js/mixins/annotations" {
var PDFKitAnnotation: PDFKit.Mixins.PDFAnnotation<void>;
export = PDFKitAnnotation;
}
declare module "pdfkit/js/mixins/color" {
var PDFKitColor: PDFKit.Mixins.PDFColor<void>;
export = PDFKitColor;
}
declare module "pdfkit/js/mixins/fonts" {
var PDFKitFont: PDFKit.Mixins.PDFFont<void>;
export = PDFKitFont;
}
declare module "pdfkit/js/mixins/images" {
var PDFKitImage: PDFKit.Mixins.PDFImage;
export = PDFKitImage;
}
declare module "pdfkit/js/mixins/text" {
var PDFKitText: PDFKit.Mixins.PDFText<void>;
export = PDFKitText;
}
declare module "pdfkit/js/mixins/vector" {
var PDFKitVector: PDFKit.Mixins.PDFVector<void>;
export = PDFKitVector;
}
+44
View File
@@ -81,6 +81,50 @@ myApp.controller('TestCtrl', (
Restangular.one('accounts', 123).one('buildings', 456).get<String>();
Restangular.one('accounts', 123).getList('buildings');
Restangular.one('accounts', 123).getList<String>('buildings');
Restangular.setBaseUrl('/api/v1');
Restangular.setExtraFields(['name']);
Restangular.setResponseExtractor(function (response, operation) {
return response.data;
});
Restangular.setDefaultHttpFields({ cache: true });
Restangular.setMethodOverriders(["put", "patch"]);
Restangular.setErrorInterceptor(function (response) {
console.error('' + response.status + ' ' + response.data);
});
Restangular.setRequestSuffix('.json');
Restangular.setRequestInterceptor(function (element, operation, route, url) {
});
Restangular.addElementTransformer('accounts', false, function (elem: any) {
elem.accountName = 'Changed';
return elem;
});
Restangular.setRestangularFields({
id: "_id",
route: "restangularRoute",
selfLink: "self.href"
});
Restangular.addRequestInterceptor(function(element, operation, route, url) {
delete element.name;
return element;
});
Restangular.setFullRequestInterceptor(function(element, operation, route, url, headers, params, httpConfig) {
delete element.name;
return {
element: element,
params: params,
headers: headers,
httpConfig: httpConfig
};
});
var accountData = Restangular.one('accounts', 123).plain();
var accountClone: restangular.IElement = Restangular.one('accounts', 123).clone();
+1 -1
View File
@@ -83,7 +83,7 @@ declare module restangular {
addRestangularMethod(name: string, operation: string, path?: string, params?: any, headers?: any, elem?: any): IPromise<any>;
}
interface IService extends ICustom {
interface IService extends ICustom, IProvider {
one(route: string, id?: number): IElement;
one(route: string, id?: string): IElement;
oneUrl(route: string, url: string): IElement;
+4
View File
@@ -23,6 +23,10 @@ module SigmaJsTests {
s.refresh();
});
sigma.canvas.edges['def'] = function() {};
sigma.svg.nodes['def'] = {create: (obj: SigmaJs.Node) => { return new Element(); },
update: (obj: SigmaJs.Node) => { return; }};
var N = 100;
var E = 500;
// Generate a random graph:
+28 -1
View File
@@ -15,10 +15,17 @@ declare module SigmaJs{
graphPosition(x: number, y:number): {x: number; y: number};
ratio: number;
readPrefix: string;
settings(setting: string) : any;
x: number;
y: number;
}
interface Canvas {
edges: {[renderType: string]: (edge: Edge, source: Node, target: Node, ...a:any[]) => void};
labels: {[renderType: string]: (node: Node, ...a:any[]) => void};
nodes: {[renderType: string]: (node: Node, ...a:any[]) => void};
}
interface Classes {
configurable: Configurable;
graph: Graph;
@@ -39,6 +46,7 @@ declare module SigmaJs{
}
interface Edge {
[key : string] : any;
color?: string;
id: string;
size?: number;
@@ -74,6 +82,11 @@ declare module SigmaJs{
nodes(ids: string[]): Node[];
}
interface GraphData {
edges: Edge[];
nodes: Node[];
}
interface Image {
clip?: number;
scale?: number;
@@ -87,6 +100,7 @@ declare module SigmaJs{
}
interface Node {
[key : string] : any;
color?: string;
id: string;
image?: any;
@@ -149,7 +163,7 @@ declare module SigmaJs{
interface SigmaConfigs {
container?: Element;
graph?: Graph;
graph?: GraphData;
id?: string;
renderers?: Renderer[];
settings?: { [index: string]: any };
@@ -160,10 +174,12 @@ declare module SigmaJs{
new(container: string): Sigma;
new(container: Element): Sigma;
new(configuration: SigmaConfigs): Sigma;
canvas: Canvas;
classes:Classes;
misc: Miscellaneous;
parsers: Parsers;
plugins: Plugins;
svg: SVG;
}
interface Settings {
@@ -269,6 +285,17 @@ declare module SigmaJs{
// Animation settings
animationsTime?: number;
}
interface SVG {
edges: {[renderType: string]: SVGObject<SigmaJs.Edge>};
labels: {[renderType: string]: SVGObject<SigmaJs.Node>};
nodes: {[renderType: string]: SVGObject<SigmaJs.Node>};
}
interface SVGObject<T> {
create: (object: T, ...a:any[]) => Element;
update: (object: T, ...a:any[]) => void;
}
}
declare var sigma: SigmaJs.SigmaFactory;
+155
View File
@@ -0,0 +1,155 @@
// Type definitions for stampit
// Project: https://github.com/ericelliott/stampit
// Definitions by: Vasyl Boroviak <https://github.com/koresar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var stampit: stampit.Stampit;
declare module stampit {
interface Stampit {
/**
* Return a factory (akaStamp) function that will produce new objects using the
* prototypes that are passed in or composed.
* @param methods A map of method names and bodies for delegation.
* @param state A map of property names and values to clone for each new object.
* @param enclose A closure (function) used to create private data and privileged methods.
* */
(methods?:{}, state?:{}, enclose?:{(...encloseArgs:any[]): void}[]):stampit.Stamp;
/**
* Take two or more Stamps and combine them to produce a new Stamp.
* Combining overrides properties with last-in priority.
* @param stamps Stamps produced by stampit.
* @return A new Stamp made of all the given.
*/
compose(...stamps:Stamp[]): Stamp;
/**
* Take a destination object followed by one or more source objects,
* and copy the source object properties to the destination object,
* with last in priority overrides.
* @param destination An object to copy properties to.
* @param source Objects to copy properties from.
* @return The destination object.
*/
mixIn(destination:any, ...source:any[]): any;
/**
* Alias for mixIn.
* Take a destination object followed by one or more source objects,
* and copy the source object properties to the destination object,
* with last in priority overrides.
* @param destination An object to copy properties to.
* @param source Objects to copy properties from.
* @return The destination object.
*/
extend(destination:any, ...source:any[]): any;
/**
* Check if an object is a Stamp.
* @param obj An object to check.
* @return true if the object is a Stamp; otherwise - false.
*/
isStamp(obj:any): boolean;
/**
* Take an old-fashioned JS constructor and return a Stamp
* that you can freely compose with other Stamps.
* @param Constructor Old-fashioned constructor function.
* @return A new Stamp based on the given constructor.
*/
convertConstructor(Constructor:any): Stamp;
}
/**
* A factory function that will produce new objects using the
* prototypes that are passed in or composed.
*/
export interface Stamp {
/**
* Just like calling stamp() invokes the stamp and returns a new object instance.
* @param state Properties you wish to set on the new objects.
* @param encloseArgs The remaining arguments are passed to all .enclose() functions.
* WARNING Avoid using two different .enclose() functions that expect different arguments.
* .enclose() functions that take arguments should not be considered safe to compose
* with other .enclose() functions that also take arguments. Taking arguments with
* an .enclose() function is an anti-pattern that should be avoided, when possible.
* @return A new object composed of the Stamps and prototypes provided.
*/
(state?:{}, ...encloseArgs:any[]): any;
/**
* Just like calling stamp(), stamp.create() invokes the stamp and returns a new instance.
* @param state Properties you wish to set on the new objects.
* @param encloseArgs The remaining arguments are passed to all .enclose() functions.
* WARNING Avoid using two different .enclose() functions that expect different arguments.
* .enclose() functions that take arguments should not be considered safe to compose
* with other .enclose() functions that also take arguments. Taking arguments with
* an .enclose() function is an anti-pattern that should be avoided, when possible.
* @return A new object composed of the Stamps and prototypes provided.
*/
create(state?:{}, ...encloseArgs:any[]): any;
/**
* An object map containing the fixed prototypes.
*/
fixed: Fixed;
/**
* Add methods to the methods prototype. Chainable.
* @param methods Object(s) containing map of method names and bodies for delegation.
* @return Self.
*/
methods(...methods:{}[]): Stamp;
/**
* Take n objects and add them to the state prototype. Changes `this` object. Chainable.
* @param states Object(s) containing map of property names and values to clone for each new object.
* @return Self.
*/
state(...states:{}[]): Stamp;
/**
* Take n functions, an array of functions, or n objects and add the functions to the enclose prototype.
* Functions passed into .enclose() are called any time an object is instantiated.
* That happens when the stamp function is invoked, or when the .create() method is called.
* Changes `this` object. Chainable.
* @param functions Closures (functions) used to create private data and privileged methods.
* @return Self.
*/
enclose(...functions:{(...encloseArgs:any[]): void}[]): Stamp;
/**
* Take n functions, an array of functions, or n objects and add the functions to the enclose prototype.
* Functions passed into .enclose() are called any time an object is instantiated.
* That happens when the stamp function is invoked, or when the .create() method is called.
* Changes `this` object. Chainable.
* @param methods Function properties of these objects will be treated as closure functions.
* @return Self.
*/
enclose(...methods:{}[]): Stamp;
/**
* Take one or more Stamps and
* combine them with `this` to produce and return a new Stamp.
* Combining overrides properties with last-in priority.
* NOT chainable.
* @param stamps Stampit factories, aka Stamps.
* @return A new Stamp composed from arguments and `this`.
*/
compose(...stamps:Stamp[]): Stamp;
}
/**
* An object map containing the fixed prototypes.
*/
interface Fixed {
methods: {};
state: {};
enclose: {(...encloseArgs:any[]): void}[];
}
}
declare module "stampit" {
export = stampit;
}
+168
View File
@@ -0,0 +1,168 @@
/// <reference path="stampit-1.2.0.d.ts" />
var a = stampit().enclose(() => {
var a = 'a';
this.getA = () => {
return a;
};
});
a(); // Object -- so far so good.
a().getA(); // "a"
var b = stampit().enclose(function () {
var a = 'b';
this.getB = function () {
return a;
};
});
var c = stampit.compose(a, b);
var foo = c(); // we won't throw this one away...
foo.getA(); // "a"
foo.getB(); // "b"
// Some more privileged methods, with some private data.
// Use stampit.mixIn() to make this feel declarative:
var availability = stampit().enclose(function () {
var isOpen = false; // private
return stampit.mixIn(this, {
open: function open() {
isOpen = true;
return this;
},
close: function close() {
isOpen = false;
return this;
},
isOpen: function isOpenMethod() {
return isOpen;
}
});
});
// Hre's a mixin with public methods, and some state:
var membership = stampit({
members: {},
add: function (member: any) {
this.members[member.name] = member;
return this;
},
getMember: function (name: any) {
return this.members[name];
}
},
{
members: {}
});
// Let's set some defaults:
var defaults = stampit().state({
name: 'The Saloon',
specials: 'Whisky, Gin, Tequila'
});
// Classical inheritance has nothing on this. No parent/child coupling. No deep inheritance hierarchies.
// Just good, clean code reusability.
var bar = stampit.compose(defaults, availability, membership);
// Note that you can override state on instantiation:
var myBar = bar({name: 'Moe\'s'});
// Silly, but proves that everything is as it should be.
myBar.add({name: 'Homer' }).open().getMember('Homer');
var myStamp = stampit().methods({
foo: function () {
return 'foo';
},
methodOverride: function () {
return false;
}
}).methods({
bar: function () {
return 'bar'
},
methodOverride: function () {
return true;
}
});
myStamp.state({
foo: {bar: 'bar'},
stateOverride: false
}).state({
bar: 'bar',
stateOverride: true
});
myStamp.enclose(function () {
var secret = 'foo';
this.getSecret = function () {
return secret;
};
}).enclose(function () {
this.a = true;
}).enclose({
bar: function bar() {
this.b = true;
}
}, {
baz: function baz() {
this.c = true;
}
});
var obj = myStamp.create();
obj.getSecret && obj.a && obj.b && obj.c; // true
var newStamp = stampit(null, { defaultNum: 1 }).compose(myStamp);
var obj1 = stampit().methods({
a: function () { return 'a'; }
}, {
b: function () { return 'b'; }
}).create();
var obj2 = stampit().state({
a: 'a'
}, {
b: 'b'
}).create();
var obj = defaults.compose(newStamp, membership, availability).create();
// The old constructor / class thing...
var Constructor = function Constructor() {
this.thing = 'initialized';
};
Constructor.prototype.foo = function foo() { return 'foo'; };
// The conversion
var oldskool = stampit.convertConstructor(Constructor);
// A new stamp to compose with...
var newskool = stampit().methods({
bar: function bar() { return 'bar'; }
// your methods here...
}).enclose(function () {
this.baz = 'baz';
});
// Now you can compose those old constructors just like you could
// with any other stamp...
var myThing = stampit.compose(oldskool, newskool);
var t = myThing();
t.thing; // 'initialized',
t.foo(); // 'foo',
t.bar(); // 'bar'
+39 -30
View File
@@ -1,7 +1,8 @@
/// <reference path="stampit.d.ts" />
import stampit = require('./stampit.d');
var a = stampit().enclose(() => {
var a = 'a';
var a = stampit().init((options) => {
var a = options.args[0];
this.getA = () => {
return a;
};
@@ -10,7 +11,7 @@ a(); // Object -- so far so good.
a().getA(); // "a"
var b = stampit().enclose(function () {
var b = stampit().init(function () {
var a = 'b';
this.getB = function () {
return a;
@@ -26,7 +27,7 @@ foo.getB(); // "b"
// Some more privileged methods, with some private data.
// Use stampit.mixIn() to make this feel declarative:
var availability = stampit().enclose(function () {
var availability = stampit().init(function () {
var isOpen = false; // private
return stampit.mixIn(this, {
@@ -43,22 +44,25 @@ var availability = stampit().enclose(function () {
}
});
});
// Hre's a mixin with public methods, and some state:
// Here's a mixin with public methods, and some refs:
var membership = stampit({
methods: {
members: {},
add: function (member: any) {
add: function (member:any) {
this.members[member.name] = member;
return this;
},
getMember: function (name: any) {
getMember: function (name:any) {
return this.members[name];
}
},
{
refs: {
members: {}
});
}
});
// Let's set some defaults:
var defaults = stampit().state({
var defaults = stampit().refs({
name: 'The Saloon',
specials: 'Whisky, Gin, Tequila'
});
@@ -66,11 +70,10 @@ var defaults = stampit().state({
// Classical inheritance has nothing on this. No parent/child coupling. No deep inheritance hierarchies.
// Just good, clean code reusability.
var bar = stampit.compose(defaults, availability, membership);
// Note that you can override state on instantiation:
// Note that you can override refs on instantiation:
var myBar = bar({name: 'Moe\'s'});
// Silly, but proves that everything is as it should be.
myBar.add({name: 'Homer' }).open().getMember('Homer');
myBar.add({name: 'Homer'}).open().getMember('Homer');
var myStamp = stampit().methods({
@@ -89,23 +92,23 @@ var myStamp = stampit().methods({
}
});
myStamp.state({
myStamp.refs({
foo: {bar: 'bar'},
stateOverride: false
}).state({
refsOverride: false
}).refs({
bar: 'bar',
stateOverride: true
refsOverride: true
});
myStamp.enclose(function () {
myStamp.init(function () {
var secret = 'foo';
this.getSecret = function () {
return secret;
};
}).enclose(function () {
}).init(function () {
this.a = true;
}).enclose({
}).init({
bar: function bar() {
this.b = true;
}
@@ -118,17 +121,20 @@ myStamp.enclose(function () {
var obj = myStamp.create();
obj.getSecret && obj.a && obj.b && obj.c; // true
var newStamp = stampit(null, { defaultNum: 1 }).compose(myStamp);
var newStamp = stampit({refs: {defaultNum: 1}}).compose(myStamp);
var obj1 = stampit().methods({
a: function () { return 'a'; }
a: function () {
return 'a';
}
}, {
b: function () { return 'b'; }
b: function () {
return 'b';
}
}).create();
var obj2 = stampit().state({
var obj2 = stampit().refs({
a: 'a'
}, {
b: 'b'
@@ -137,21 +143,24 @@ var obj2 = stampit().state({
var obj = defaults.compose(newStamp, membership, availability).create();
// The old constructor / class thing...
var Constructor = function Constructor() {
this.thing = 'initialized';
};
Constructor.prototype.foo = function foo() { return 'foo'; };
Constructor.prototype.foo = function foo() {
return 'foo';
};
// The conversion
var oldskool = stampit.convertConstructor(Constructor);
// A new stamp to compose with...
var newskool = stampit().methods({
bar: function bar() { return 'bar'; }
bar: function bar() {
return 'bar';
}
// your methods here...
}).enclose(function () {
}).init(function () {
this.baz = 'baz';
});
@@ -165,4 +174,4 @@ t.thing; // 'initialized',
t.foo(); // 'foo',
t.bar(); // 'bar'
t.bar(); // 'bar'
+276 -134
View File
@@ -1,155 +1,297 @@
// Type definitions for stampit
// Project: https://github.com/ericelliott/stampit
// Type definitions for stampit 2.1
// Project: https://github.com/stampit-org/stampit
// Definitions by: Vasyl Boroviak <https://github.com/koresar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var stampit: stampit.Stampit;
/**
* Function used as .init() argument.
*/
interface Init {
(ctx:Context): any | Promise;
}
declare module stampit {
interface Stampit {
/**
* Return a factory (akaStamp) function that will produce new objects using the
* prototypes that are passed in or composed.
* @param methods A map of method names and bodies for delegation.
* @param state A map of property names and values to clone for each new object.
* @param enclose A closure (function) used to create private data and privileged methods.
* */
(methods?:{}, state?:{}, enclose?:{(...encloseArgs:any[]): void}[]):stampit.Stamp;
interface Promise {
then(resolve:(result: any) => any|Promise, reject:(reason: any | Error) => any|Promise): Promise
}
/**
* Take two or more Stamps and combine them to produce a new Stamp.
* Combining overrides properties with last-in priority.
* @param stamps Stamps produced by stampit.
* @return A new Stamp made of all the given.
*/
compose(...stamps:Stamp[]): Stamp;
/**
* Take a destination object followed by one or more source objects,
* and copy the source object properties to the destination object,
* with last in priority overrides.
* @param destination An object to copy properties to.
* @param source Objects to copy properties from.
* @return The destination object.
*/
mixIn(destination:any, ...source:any[]): any;
/**
* Alias for mixIn.
* Take a destination object followed by one or more source objects,
* and copy the source object properties to the destination object,
* with last in priority overrides.
* @param destination An object to copy properties to.
* @param source Objects to copy properties from.
* @return The destination object.
*/
extend(destination:any, ...source:any[]): any;
/**
* Check if an object is a Stamp.
* @param obj An object to check.
* @return true if the object is a Stamp; otherwise - false.
*/
isStamp(obj:any): boolean;
/**
* Take an old-fashioned JS constructor and return a Stamp
* that you can freely compose with other Stamps.
* @param Constructor Old-fashioned constructor function.
* @return A new Stamp based on the given constructor.
*/
convertConstructor(Constructor:any): Stamp;
}
/**
* The .init() function argument.
*/
interface Context {
/**
* The object which has been just instantiated.
*/
instance: any;
/**
* A factory function that will produce new objects using the
* prototypes that are passed in or composed.
* The stamp the object has been instantiated with.
*/
export interface Stamp {
/**
* Just like calling stamp() invokes the stamp and returns a new object instance.
* @param state Properties you wish to set on the new objects.
* @param encloseArgs The remaining arguments are passed to all .enclose() functions.
* WARNING Avoid using two different .enclose() functions that expect different arguments.
* .enclose() functions that take arguments should not be considered safe to compose
* with other .enclose() functions that also take arguments. Taking arguments with
* an .enclose() function is an anti-pattern that should be avoided, when possible.
* @return A new object composed of the Stamps and prototypes provided.
*/
(state?:{}, ...encloseArgs:any[]): any;
stamp: Stamp;
/**
* Just like calling stamp(), stamp.create() invokes the stamp and returns a new instance.
* @param state Properties you wish to set on the new objects.
* @param encloseArgs The remaining arguments are passed to all .enclose() functions.
* WARNING Avoid using two different .enclose() functions that expect different arguments.
* .enclose() functions that take arguments should not be considered safe to compose
* with other .enclose() functions that also take arguments. Taking arguments with
* an .enclose() function is an anti-pattern that should be avoided, when possible.
* @return A new object composed of the Stamps and prototypes provided.
*/
create(state?:{}, ...encloseArgs:any[]): any;
/**
* The arguments list passed to the stamp.
*/
args: any[];
}
/**
* An object map containing the fixed prototypes.
*/
fixed: Fixed;
/**
* An object map containing the fixed prototypes.
*/
interface Fixed {
methods: {};
/**
* Add methods to the methods prototype. Chainable.
* @param methods Object(s) containing map of method names and bodies for delegation.
* @return Self.
*/
methods(...methods:{}[]): Stamp;
/**
* @deprecated Use .refs() instead.
*/
state: {};
/**
* Take n objects and add them to the state prototype. Changes `this` object. Chainable.
* @param states Object(s) containing map of property names and values to clone for each new object.
* @return Self.
*/
state(...states:{}[]): Stamp;
refs: {};
/**
* Take n functions, an array of functions, or n objects and add the functions to the enclose prototype.
* Functions passed into .enclose() are called any time an object is instantiated.
* That happens when the stamp function is invoked, or when the .create() method is called.
* Changes `this` object. Chainable.
* @param functions Closures (functions) used to create private data and privileged methods.
* @return Self.
*/
enclose(...functions:{(...encloseArgs:any[]): void}[]): Stamp;
/**
* @deprecated Use .init() instead.
*/
enclose: Init[];
/**
* Take n functions, an array of functions, or n objects and add the functions to the enclose prototype.
* Functions passed into .enclose() are called any time an object is instantiated.
* That happens when the stamp function is invoked, or when the .create() method is called.
* Changes `this` object. Chainable.
* @param methods Function properties of these objects will be treated as closure functions.
* @return Self.
*/
enclose(...methods:{}[]): Stamp;
init: Init[];
/**
* Take one or more Stamps and
* combine them with `this` to produce and return a new Stamp.
* Combining overrides properties with last-in priority.
* NOT chainable.
* @param stamps Stampit factories, aka Stamps.
* @return A new Stamp composed from arguments and `this`.
*/
compose(...stamps:Stamp[]): Stamp;
}
props: {};
static: {};
}
interface Options {
/**
* A hash containing methods (functions) of any future created instance.
*/
methods?: {} | {}[];
/**
* A hash containing references to the object. This hash will be shallow mixed into any future created instance.
*/
refs?: {} | {}[];
/**
* Initialization function which will be called per each newly created instance.
*/
init?: Init | Init[];
/**
* Properties which will be deeply (but safely, no data override) merged into any future created instance.
*/
props?: {} | {}[];
/**
* Properties which will be mixed to the new and any other stamp which this stamp will be composed with.
*/
static?: {} | {}[];
}
/**
* A factory function that will produce new objects using the
* prototypes that are passed in or composed.
*/
interface Stamp {
/**
* Invokes the stamp and returns a new object instance.
* @param state Properties you wish to set on the new objects.
* @param encloseArgs The remaining arguments are passed to all .enclose() functions.
* WARNING Avoid using two different .enclose() functions that expect different arguments.
* .enclose() functions that take arguments should not be considered safe to compose
* with other .enclose() functions that also take arguments. Taking arguments with
* an .enclose() function is an anti-pattern that should be avoided, when possible.
* @return A new object composed of the Stamps and prototypes provided.
*/
(state?:{}, ...encloseArgs:any[]): any | Promise;
/**
* Just like calling stamp(), stamp.create() invokes the stamp and returns a new instance.
* @param state Properties you wish to set on the new objects.
* @param encloseArgs The remaining arguments are passed to all .enclose() functions.
* WARNING Avoid using two different .enclose() functions that expect different arguments.
* .enclose() functions that take arguments should not be considered safe to compose
* with other .enclose() functions that also take arguments. Taking arguments with
* an .enclose() function is an anti-pattern that should be avoided, when possible.
* @return A new object composed of the Stamps and prototypes provided.
*/
create(state?:{}, ...encloseArgs:any[]): any | Promise;
/**
* An object map containing the fixed prototypes.
*/
interface Fixed {
methods: {};
state: {};
enclose: {(...encloseArgs:any[]): void}[];
}
fixed: Fixed;
/**
* Add methods to the methods prototype. Creates and returns new Stamp. Chainable.
* @param methods Object(s) containing map of method names and bodies for delegation.
* @return A new Stamp.
*/
methods(...methods:{}[]): Stamp;
/**
* Take n objects and add them to the state prototype. Creates and returns new Stamp. Chainable.
* @param states Object(s) containing map of property names and values to clone for each new object.
* @return A new Stamp.
*/
refs(...states:{}[]): Stamp;
/**
* Take n objects and merge them (but safely, no data override) to the of any future created instance.
* Creates and returns new Stamp. Chainable.
* @param objects Object(s) to merge for each new object.
* @return A new Stamp.
*/
props(...objects:{}[]): Stamp;
/**
* @deprecated Use .refs() instead.
*/
state(...states:{}[]): Stamp;
/**
* @deprecated Use .init() instead.
*/
enclose(...functions:Init[]): Stamp;
/**
* @deprecated Use .init() instead.
*/
enclose(...functions:{}[]): Stamp;
/**
* Take n functions, an array of functions, or n objects and add the functions to the enclose prototype.
* Functions passed into .enclose() are called any time an object is instantiated.
* That happens when the stamp function is invoked, or when the .create() method is called.
* Creates and returns new Stamp. Chainable.
* @param functions Closures (functions) used to create private data and privileged methods.
* @return A new Stamp.
*/
init(...functions:Init[]): Stamp;
/**
* Take n functions, an array of functions, or n objects and add the functions to the enclose prototype.
* Functions passed into .enclose() are called any time an object is instantiated.
* That happens when the stamp function is invoked, or when the .create() method is called.
* Creates and returns new Stamp. Chainable.
* @param functions Function properties of these objects will be treated as closure functions.
* @return A new Stamp.
*/
init(...functions:{}[]): Stamp;
/**
* Take n objects and add them to a new stamp and any future stamp it composes with.
* Creates and returns new Stamp. Chainable.
* @param statics Object(s) containing map of property names and values to mixin into each new stamp.
* @return A new Stamp.
*/
static(...statics:{}[]): Stamp;
/**
* Take one or more Stamps and
* combine them with `this` to produce and return a new Stamp.
* Combining overrides properties with last-in priority.
* NOT chainable.
* @param stamps Stampit factories, aka Stamps.
* @return A new Stamp composed from arguments and `this`.
*/
compose(...stamps:Stamp[]): Stamp;
}
declare module "stampit" {
export = stampit;
}
/**
* Return a factory (akaStamp) function that will produce new objects using the
* prototypes that are passed in or composed.
* @param {object} options Stampit options object containing refs, methods, init, props, and static.
* @param {object} options.methods A map of method names and bodies for delegation.
* @param {object} options.refs A map of property names and values to clone for each new object.
* @param {object} options.props A map of property names and values to clone for each new object.
* @param {function} options.init A closure(s) (function(s)) used to create private data and privileged methods.
* @param {object} options.static A map of properties to mixin into new and other stamp it will compose with.
* */
declare function stampit(options?: Options): Stamp
declare module stampit {
/**
* A shortcut methods for stampit().methods()
* @param methods Object(s) containing map of method names and bodies for delegation.
* @return A new Stamp.
*/
export function methods(...methods:{}[]): Stamp;
/**
* A shortcut methods for stampit().refs()
* @param states Object(s) containing map of property names and values to clone for each new object.
* @return A new Stamp.
*/
export function refs(...states:{}[]): Stamp;
/**
* A shortcut methods for stampit().props()
* @param states Object(s) to merge for each new object.
* @return A new Stamp.
*/
export function props(...states:{}[]): Stamp;
/**
* A shortcut methods for stampit().init()
* @param functions Closures (functions) used to create private data and privileged methods.
* @return A new Stamp.
*/
export function init(...functions:Init[]): Stamp;
/**
* A shortcut methods for stampit().static()
* @param statics Object(s) containing map of property names and values to mixin into each new stamp (NOT OBJECT).
* @return A new Stamp.
*/
export function static(...statics:{}[]): Stamp;
/**
* Take two or more Stamps and combine them to produce a new Stamp.
* Combining overrides properties with last-in priority.
* @param stamps Stamps produced by stampit.
* @return A new Stamp made of all the given.
*/
export function compose(...stamps:Stamp[]): Stamp;
/**
* Take a destination object followed by one or more source objects,
* and copy the source object properties to the destination object,
* with last in priority overrides.
* @param destination An object to copy properties to.
* @param source Objects to copy properties from.
* @return The destination object.
*/
export function mixin(destination:any, ...source:any[]): any;
/**
* Alias for mixin()
*/
export function mixIn(destination:any, ...source:any[]): any;
/**
* Alias for mixin()
*/
export function extend(destination:any, ...source:any[]): any;
/**
* Alias for mixin()
*/
export function assign(destination:any, ...source:any[]): any;
/**
* Check if an object is a Stamp.
* @param obj An object to check.
* @return true if the object is a Stamp; otherwise - false.
*/
export function isStamp(obj:any): boolean;
/**
* Take an old-fashioned JS constructor and return a Stamp
* that you can freely compose with other Stamps.
* @param Constructor Old-fashioned constructor function.
* @return A new Stamp based on the given constructor.
*/
export function convertConstructor(Constructor:any): Stamp;
}
export = stampit;
+33
View File
@@ -0,0 +1,33 @@
/// <reference path="statuses.d.ts" />
import status = require('statuses');
var code: number;
code = status(403) // => 403
code = status('403') // => 403
code = status('forbidden') // => 403
code = status('Forbidden') // => 403
code = status(306) // throws, as it's not supported by node.js
var codes: Array<number>;
codes = status.codes;
var msg: string;
msg = status[404] // => 'Not Found'
code = status['not found'] // => 404
code = status['Not Found'] // => 404
var isRedirect: boolean;
isRedirect = status.redirect[200] // => undefined
isRedirect = status.redirect[301] // => true
var isEmpty: boolean;
isEmpty = status.empty[200] // => undefined
isEmpty = status.empty[204] // => true
isEmpty = status.empty[304] // => true
var isRetry: boolean;
isRetry = status.retry[501] // => undefined
isRetry = status.retry[503] // => true
+21
View File
@@ -0,0 +1,21 @@
// Type definitions for http-errors v1.2.1
// Project: https://github.com/jshttp/statuses
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'statuses' {
interface Status {
[code: number]: string;
[msg: string]: any | number;
codes: Array<number>;
redirect: {[code: number]: boolean};
empty: {[code: number]: boolean};
retry: {[code: number]: boolean};
(code: number | string): number;
}
var status: Status;
export = status;
}