Merge remote-tracking branch 'source/master' into 90296-fte-rounding

This commit is contained in:
Adam Kalman
2015-05-29 14:20:20 -07:00
145 changed files with 26754 additions and 3821 deletions
+1 -1
View File
@@ -726,7 +726,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](q-io/Q-io.d.ts) [Q-io](https://github.com/kriskowal/q-io) by [Bart van der Schoor](https://github.com/Bartvds)
* [:link:](q-retry/q-retry.d.ts) [q-retry](https://github.com/vilic/q-retry) by [VILIC VANE](https://github.com/vilic)
* [:link:](qajax/qajax.d.ts) [Qajax](https://github.com/gre/qajax) by [Boltmade](https://github.com/Boltmade)
* [:link:](qtip2/qtip2.d.ts) [qtip2](http://qtip2.com) by [Nathan Pitman](https://github.com/Seltzer100)
* [:link:](qtip2/qtip2.d.ts) [qtip2](http://qtip2.com) by [Nathan Pitman](https://github.com/Seltzer)
* [:link:](qunit/qunit.d.ts) [QUnit](http://qunitjs.com) by [Diullei Gomes](https://github.com/diullei)
* [:link:](rabbit.js/rabbit.js.d.ts) [rabbit.js](https://github.com/squaremo/rabbit.js) by [Wonshik Kim](https://github.com/wokim)
* [:link:](ractive/ractive.d.ts) [Ractive](http://ractivejs.org) by [Han Lin Yap](http://yap.nu)
+180
View File
@@ -0,0 +1,180 @@
/// <reference path="DataStream.js.d.ts" />
var buf = new ArrayBuffer(100);
var ds = new DataStream(buf);
ds = new DataStream(buf, 10);
ds = new DataStream(buf, 10, DataStream.BIG_ENDIAN);
ds.save('somefile.ext');
ds.dynamicSize = true;
for (var i=0; i<ds.byteLength; i++) {
}
ds.buffer = buf;
ds.byteOffset = 10;
ds.seek(0);
ds.isEof();
var int32arr: Int32Array;
var int16arr: Int16Array;
var int8arr: Int8Array;
var uint32arr: Uint32Array;
var uint16arr: Uint16Array;
var uint8arr: Uint8Array;
var float64arr: Float64Array;
var float32arr: Float32Array;
var val: number;
var str: string;
int32arr = ds.mapInt32Array(2);
int32arr = ds.mapInt32Array(2, DataStream.LITTLE_ENDIAN);
int16arr = ds.mapInt16Array(2);
int16arr = ds.mapInt16Array(2, DataStream.BIG_ENDIAN);
int8arr = ds.mapInt8Array(2);
uint32arr = ds.mapUint32Array(2);
uint32arr = ds.mapUint32Array(2, DataStream.LITTLE_ENDIAN);
uint16arr = ds.mapUint16Array(2);
uint16arr = ds.mapUint16Array(2, DataStream.BIG_ENDIAN);
uint8arr = ds.mapUint8Array(2);
float64arr = ds.mapFloat64Array(2);
float64arr = ds.mapFloat64Array(2, DataStream.LITTLE_ENDIAN);
float32arr = ds.mapFloat32Array(2);
float32arr = ds.mapFloat32Array(2, DataStream.BIG_ENDIAN);
int32arr = ds.readInt32Array(2);
int32arr = ds.readInt32Array(2, DataStream.LITTLE_ENDIAN);
int16arr = ds.readInt16Array(2);
int16arr = ds.readInt16Array(2, DataStream.BIG_ENDIAN);
int8arr = ds.readInt8Array(2);
uint32arr = ds.readUint32Array(2);
uint32arr = ds.readUint32Array(2, DataStream.LITTLE_ENDIAN);
uint16arr = ds.readUint16Array(2);
uint16arr = ds.readUint16Array(2, DataStream.BIG_ENDIAN);
uint8arr = ds.readUint8Array(2);
float64arr = ds.readFloat64Array(2);
float64arr = ds.readFloat64Array(2, DataStream.LITTLE_ENDIAN);
float32arr = ds.readFloat32Array(2);
float32arr = ds.readFloat32Array(2, DataStream.BIG_ENDIAN);
ds.writeInt32Array(new Int32Array([1,2,3]));
ds.writeInt32Array(new Int32Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeInt16Array(new Int16Array([1,2,3]));
ds.writeInt16Array(new Int16Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeInt8Array(new Int8Array([1,2,3]));
ds.writeUint32Array(new Uint32Array([1,2,3]));
ds.writeUint32Array(new Uint32Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeUint16Array(new Uint16Array([1,2,3]));
ds.writeUint16Array(new Uint16Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeUint8Array(new Uint8Array([1,2,3]));
ds.writeFloat64Array(new Float64Array([1,2,3]));
ds.writeFloat64Array(new Float64Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeFloat32Array(new Float32Array([1,2,3]));
ds.writeFloat32Array(new Float32Array([1,2,3]), DataStream.BIG_ENDIAN);
val = ds.readInt32();
val = ds.readInt32(DataStream.LITTLE_ENDIAN);
val = ds.readInt16();
val = ds.readInt16(DataStream.BIG_ENDIAN);
val = ds.readInt8();
val = ds.readUint32();
val = ds.readUint32(DataStream.LITTLE_ENDIAN);
val = ds.readUint16();
val = ds.readUint16(DataStream.BIG_ENDIAN);
val = ds.readUint8();
val = ds.readFloat64();
val = ds.readFloat64(DataStream.LITTLE_ENDIAN);
val = ds.readFloat32();
val = ds.readFloat32(DataStream.BIG_ENDIAN);
ds.writeInt32(1);
ds.writeInt32(2, DataStream.BIG_ENDIAN);
ds.writeInt16(1);
ds.writeInt16(2, DataStream.LITTLE_ENDIAN);
ds.writeInt8(1);
ds.writeUint32(1);
ds.writeUint32(2, DataStream.BIG_ENDIAN);
ds.writeUint16(1);
ds.writeUint16(2, DataStream.LITTLE_ENDIAN);
ds.writeUint8(1);
ds.writeFloat32(1);
ds.writeFloat32(2, DataStream.BIG_ENDIAN);
ds.writeFloat64(1);
ds.writeFloat64(2, DataStream.LITTLE_ENDIAN);
var embed = [
'tag', 'uint32be',
'code', 'uint32le',
'greet', 'cstring'
];
var def = [
'tag', 'cstring:4',
'code', 'uint32le',
'embed', embed,
'length', 'uint16be',
'data', ['[]', 'float32be', 'length'],
'greet', 'cstring:20',
'endNote', 'uint8'
];
var obj = ds.readStruct(def);
ds.writeStruct(def, obj);
str = ds.readUCS2String(2);
str = ds.readUCS2String(2, DataStream.LITTLE_ENDIAN);
ds.writeUCS2String("str");
ds.writeUCS2String("str", DataStream.LITTLE_ENDIAN);
ds.writeUCS2String("str", DataStream.LITTLE_ENDIAN, 1);
str = ds.readString(2);
str = ds.readString(2, "ASCII");
ds.writeString("str");
ds.writeString("str", "ASCII");
ds.writeString("str", "ASCII", 1);
str = ds.readCString();
str = ds.readCString(2);
ds.writeCString("str");
ds.writeCString("str", 1);
+937
View File
@@ -0,0 +1,937 @@
// Type definitions for DataStream.js
// Project: https://github.com/kig/DataStream.js
// Definitions by: Tat <https://github.com/tatchx/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare class DataStream {
/**
Big-endian const to use as default endianness.
*/
static BIG_ENDIAN: boolean;
/**
Little-endian const to use as default endianness.
*/
static LITTLE_ENDIAN: boolean;
/**
DataStream reads scalars, arrays and structs of data from an ArrayBuffer.
It's like a file-like DataView on steroids.
@param {ArrayBuffer} arrayBuffer ArrayBuffer to read from.
*/
constructor(arrayBuffer: ArrayBuffer);
/**
DataStream reads scalars, arrays and structs of data from an ArrayBuffer.
It's like a file-like DataView on steroids.
@param arrayBuffer ArrayBuffer to read from.
@param byteOffset Offset from arrayBuffer beginning for the DataStream.
*/
constructor(arrayBuffer: ArrayBuffer, byteOffset: number);
/**
DataStream reads scalars, arrays and structs of data from an ArrayBuffer.
It's like a file-like DataView on steroids.
@param arrayBuffer ArrayBuffer to read from.
@param byteOffset Offset from arrayBuffer beginning for the DataStream.
@param endianness DataStream.BIG_ENDIAN or DataStream.LITTLE_ENDIAN (the default).
*/
constructor(arrayBuffer: ArrayBuffer, byteOffset: number, endianness: boolean);
/**
Saves the DataStream contents to the given filename.
Uses Chrome's anchor download property to initiate download.
*
@param filename Filename to save as.
@return nothing
*/
save(filename: string): void;
/**
Whether to extend DataStream buffer when trying to write beyond its size.
If set, the buffer is reallocated to twice its current size until the
requested write fits the buffer.
*/
dynamicSize: boolean;
/**
Returns the byte length of the DataStream object.
*/
byteLength: number;
/**
Set/get the backing ArrayBuffer of the DataStream object.
The setter updates the DataView to point to the new buffer.
*/
buffer: ArrayBuffer;
/**
Set/get the byteOffset of the DataStream object.
The setter updates the DataView to point to the new byteOffset.
*/
byteOffset: number;
/**
Set/get the backing DataView of the DataStream object.
The setter updates the buffer and byteOffset to point to the DataView values.
*/
dataView: Object;
/**
Sets the DataStream read/write position to given position.
Clamps between 0 and DataStream length.
*
@param pos Position to seek to.
@return nothing
*/
seek(pos: number): void;
/**
Returns true if the DataStream seek pointer is at the end of buffer and
there's no more data to read.
*
@return true if the seek pointer is at the end of the buffer.
*/
isEof(): boolean;
/**
Maps an Int32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Int32Array to the DataStream backing buffer.
*/
mapInt32Array(length: number): Int32Array;
/**
Maps an Int32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Int32Array to the DataStream backing buffer.
*/
mapInt32Array(length: number, e: boolean): Int32Array;
/**
Maps an Int16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Int16Array to the DataStream backing buffer.
*/
mapInt16Array(length: number): Int16Array;
/**
Maps an Int16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Int16Array to the DataStream backing buffer.
*/
mapInt16Array(length: number, e: boolean): Int16Array;
/**
Maps an Int8Array into the DataStream buffer.
*
Nice for quickly reading in data.
*
@param length Number of elements to map.
@return Int8Array to the DataStream backing buffer.
*/
mapInt8Array(length: number): Int8Array;
/**
Maps a Uint32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Uint32Array to the DataStream backing buffer.
*/
mapUint32Array(length: number): Uint32Array;
/**
Maps a Uint32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Uint32Array to the DataStream backing buffer.
*/
mapUint32Array(length: number, e: boolean): Uint32Array;
/**
Maps a Uint16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Uint16Array to the DataStream backing buffer.
*/
mapUint16Array(length: number): Uint16Array;
/**
Maps a Uint16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Uint16Array to the DataStream backing buffer.
*/
mapUint16Array(length: number, e: boolean): Uint16Array;
/**
Maps a Uint8Array into the DataStream buffer.
*
Nice for quickly reading in data.
*
@param length Number of elements to map.
@return Uint8Array to the DataStream backing buffer.
*/
mapUint8Array(length: number): Uint8Array;
/**
Maps a Float64Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Float64Array to the DataStream backing buffer.
*/
mapFloat64Array(length: number): Float64Array;
/**
Maps a Float64Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Float64Array to the DataStream backing buffer.
*/
mapFloat64Array(length: number, e: boolean): Float64Array;
/**
Maps a Float32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Float32Array to the DataStream backing buffer.
*/
mapFloat32Array(length: number): Float32Array;
/**
Maps a Float32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Float32Array to the DataStream backing buffer.
*/
mapFloat32Array(length: number, e: boolean): Float32Array;
/**
Reads an Int32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Int32Array.
*/
readInt32Array(length: number): Int32Array;
/**
Reads an Int32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Int32Array.
*/
readInt32Array(length: number, e: boolean): Int32Array;
/**
Reads an Int16Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Int16Array.
*/
readInt16Array(length: number): Int16Array;
/**
Reads an Int16Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Int16Array.
*/
readInt16Array(length: number, e: boolean): Int16Array;
/**
Reads an Int8Array of desired length from the DataStream.
*
@param length Number of elements to map.
@return The read Int8Array.
*/
readInt8Array(length: number): Int8Array;
/**
Reads an Uint32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Uint32Array.
*/
readUint32Array(length: number): Uint32Array;
/**
Reads an Uint32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Uint32Array.
*/
readUint32Array(length: number, e: boolean): Uint32Array;
/**
Reads an Uint16Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Uint16Array.
*/
readUint16Array(length: number): Uint16Array;
/**
Reads an Uint16Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Uint16Array.
*/
readUint16Array(length: number, e: boolean): Uint16Array;
/**
Reads an Uint8Array of desired length from the DataStream.
*
@param length Number of elements to map.
@return The read Uint8Array.
*/
readUint8Array(length: number): Uint8Array;
/**
Reads a Float64Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Float64Array.
*/
readFloat64Array(length: number, e: boolean): Float64Array;
/**
Reads a Float64Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Float64Array.
*/
readFloat64Array(length: number): Float64Array;
/**
Reads a Float32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Float32Array.
*/
readFloat32Array(length: number, e: boolean): Float32Array;
/**
Reads a Float32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Float32Array.
*/
readFloat32Array(length: number): Float32Array;
/**
Writes an Int32Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeInt32Array(arr: Int32Array, e: boolean): void;
/**
Writes an Int32Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeInt32Array(arr: Int32Array): void;
/**
Writes an Int16Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeInt16Array(arr: Int16Array, e: boolean): void;
/**
Writes an Int16Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeInt16Array(arr: Int16Array): void;
/**
Writes an Int8Array to the DataStream.
*
@param arr The array to write.
*/
writeInt8Array(arr: Int8Array): void;
/**
Writes an Uint32Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeUint32Array(arr: Uint32Array, e: boolean): void;
/**
Writes an Uint32Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeUint32Array(arr: Uint32Array): void;
/**
Writes an Uint16Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeUint16Array(arr: Uint16Array, e: boolean): void;
/**
Writes an Uint16Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeUint16Array(arr: Uint16Array): void;
/**
Writes an Uint8Array to the DataStream.
*
@param arr The array to write.
*/
writeUint8Array(arr: Uint8Array): void;
/**
Writes a Float64Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeFloat64Array(arr: Float64Array): void;
/**
Writes a Float64Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeFloat64Array(arr: Float64Array, e: boolean): void;
/**
Writes a Float32Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeFloat32Array(arr: Float32Array): void;
/**
Writes a Float32Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeFloat32Array(arr: Float32Array, e: boolean): void;
/**
Reads a 32-bit int from the DataStream with the desired endianness.
*
@return The read number.
*/
readInt32(): number;
/**
Reads a 32-bit int from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readInt32(e: boolean): number;
/**
Reads a 16-bit int from the DataStream with the desired endianness.
*
@return The read number.
*/
readInt16(): number;
/**
Reads a 16-bit int from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readInt16(e: boolean): number;
/**
Reads an 8-bit int from the DataStream.
*
@return The read number.
*/
readInt8(): number;
/**
Reads a 32-bit unsigned int from the DataStream with the desired endianness.
*
@return The read number.
*/
readUint32(): number;
/**
Reads a 32-bit unsigned int from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readUint32(e: boolean): number;
/**
Reads a 16-bit unsigned int from the DataStream with the desired endianness.
*
@return The read number.
*/
readUint16(): number;
/**
Reads a 16-bit unsigned int from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readUint16(e: boolean): number;
/**
Reads an 8-bit unsigned intfrom the DataStream.
*
@return The read number.
*/
readUint8(): number;
/**
Reads a 32-bit float from the DataStream with the desired endianness.
*
@return The read number.
*/
readFloat32(): number;
/**
Reads a 32-bit float from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readFloat32(e: boolean): number;
/**
Reads a 64-bit float from the DataStream with the desired endianness.
*
@return The read number.
*/
readFloat64(): number;
/**
Reads a 64-bit float from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readFloat64(e: boolean): number;
/**
Writes a 32-bit int to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeInt32(v: number): void;
/**
Writes a 32-bit int to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeInt32(v: number, e: boolean): void;
/**
Writes a 16-bit int to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeInt16(v: number): void;
/**
Writes a 16-bit int to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeInt16(v: number, e: boolean): void;
/**
Writes an 8-bit int to the DataStream.
*
@param v Number to write.
*/
writeInt8(v: number): void;
/**
Writes a 32-bit undigned int to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeUint32(v: number): void;
/**
Writes a 32-bit undigned int to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeUint32(v: number, e: boolean): void;
/**
Writes a 16-bit undigned int to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeUint16(v: number): void;
/**
Writes a 16-bit undigned int to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeUint16(v: number, e: boolean): void;
/**
Writes an 8-bit undigned int to the DataStream.
*
@param v Number to write.
*/
writeUint8(v: number): void;
/**
Writes a 32-bit float to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeFloat32(v: number): void;
/**
Writes a 32-bit float to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeFloat32(v: number, e: boolean): void;
/**
Writes a 64-bit float to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeFloat64(v: number): void;
/**
Writes a 64-bit float to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeFloat64(v: number, e: boolean): void;
/**
Reads a struct of data from the DataStream. The struct is defined as
a flat array of [name, type]-pairs. See the example below:
*
ds.readStruct([
'headerTag', 'uint32', // Uint32 in DataStream endianness.
'headerTag2', 'uint32be', // Big-endian Uint32.
'headerTag3', 'uint32le', // Little-endian Uint32.
'array', ['[]', 'uint32', 16], // Uint32Array of length 16.
'array2Length', 'uint32',
'array2', ['[]', 'uint32', 'array2Length'] // Uint32Array of length array2Length
]);
*
The possible values for the type are as follows:
*
// Number types
// Unsuffixed number types use DataStream endianness.
// To explicitly specify endianness, suffix the type with
// 'le' for little-endian or 'be' for big-endian,
// e.g. 'int32be' for big-endian int32.
'uint8' -- 8-bit unsigned int
'uint16' -- 16-bit unsigned int
'uint32' -- 32-bit unsigned int
'int8' -- 8-bit int
'int16' -- 16-bit int
'int32' -- 32-bit int
'float32' -- 32-bit float
'float64' -- 64-bit float
*
// String types
'cstring' -- ASCII string terminated by a zero byte.
'string:N' -- ASCII string of length N, where N is a literal integer.
'string:variableName' -- ASCII string of length $variableName,
where 'variableName' is a previously parsed number in the current struct.
'string,CHARSET:N' -- String of byteLength N encoded with given CHARSET.
'u16string:N' -- UCS-2 string of length N in DataStream endianness.
'u16stringle:N' -- UCS-2 string of length N in little-endian.
'u16stringbe:N' -- UCS-2 string of length N in big-endian.
*
// Complex types
[name, type, name_2, type_2, ..., name_N, type_N] -- Struct
function(dataStream, struct) {} -- Callback function to read and return data.
{get: function(dataStream, struct) {},
set: function(dataStream, struct) {}}
-- Getter/setter functions to read and return data, handy for using the same
struct definition for reading and writing structs.
['[]', type, length] -- Array of given type and length. The length can be either
a number, a string that references a previously-read
field, or a callback function(struct, dataStream, type){}.
If length is '*', reads in as many elements as it can.
*
@param structDefinition Struct definition object.
@return The read struct. Null if failed to read struct.
*/
readStruct(structDefinition: any[]): Object;
/**
Writes a struct to the DataStream. Takes a structDefinition that gives the
types and a struct object that gives the values. Refer to readStruct for the
structure of structDefinition.
*
@param structDefinition Type definition of the struct.
@param struct The struct data object.
*/
writeStruct(structDefinition: Object, struct: Object): void;
/**
Read UCS-2 string of desired length and endianness from the DataStream.
*
@param length The length of the string to read.
@return The read string.
*/
readUCS2String(length: number): string;
/**
Read UCS-2 string of desired length and endianness from the DataStream.
*
@param length The length of the string to read.
@param endianness The endianness of the string data in the DataStream.
@return The read string.
*/
readUCS2String(length: number, endianness: boolean): string;
/**
Write a UCS-2 string of desired endianness to the DataStream. The
lengthOverride argument lets you define the number of characters to write.
If the string is shorter than lengthOverride, the extra space is padded with
zeroes.
*
@param str The string to write.
*/
writeUCS2String(str: string): void;
/**
Write a UCS-2 string of desired endianness to the DataStream. The
lengthOverride argument lets you define the number of characters to write.
If the string is shorter than lengthOverride, the extra space is padded with
zeroes.
*
@param str The string to write.
@param endianness The endianness to use for the written string data.
*/
writeUCS2String(str: string, endianness: boolean): void;
/**
Write a UCS-2 string of desired endianness to the DataStream. The
lengthOverride argument lets you define the number of characters to write.
If the string is shorter than lengthOverride, the extra space is padded with
zeroes.
*
@param str The string to write.
@param endianness The endianness to use for the written string data.
@param lengthOverride The number of characters to write.
*/
writeUCS2String(str: string, endianness: boolean, lengthOverride: number): void;
/**
Read a string of desired length and encoding from the DataStream.
*
@param length The length of the string to read in bytes.
@return The read string.
*/
readString(length: number): string;
/**
Read a string of desired length and encoding from the DataStream.
*
@param length The length of the string to read in bytes.
@param encoding The encoding of the string data in the DataStream. Defaults to ASCII.
@return The read string.
*/
readString(length: number, encoding: string): string;
/**
Writes a string of desired length and encoding to the DataStream.
*
@param s The string to write.
*/
writeString(s: string): void;
/**
Writes a string of desired length and encoding to the DataStream.
*
@param s The string to write.
@param encoding The encoding for the written string data. Defaults to ASCII.
*/
writeString(s: string, encoding: string): void;
/**
Writes a string of desired length and encoding to the DataStream.
*
@param s The string to write.
@param encoding The encoding for the written string data. Defaults to ASCII.
@param length The number of characters to write.
*/
writeString(s: string, encoding: string, length: number): void;
/**
Read null-terminated string of desired length from the DataStream. Truncates
the returned string so that the null byte is not a part of it.
*
@return The read string.
*/
readCString(): string;
/**
Read null-terminated string of desired length from the DataStream. Truncates
the returned string so that the null byte is not a part of it.
*
@param length The length of the string to read.
@return The read string.
*/
readCString(length: number): string;
/**
Writes a null-terminated string to DataStream and zero-pads it to length
bytes. If length is not given, writes the string followed by a zero.
If string is longer than length, the written part of the string does not have
a trailing zero.
*
@param s The string to write.
*/
writeCString(s: string): void;
/**
Writes a null-terminated string to DataStream and zero-pads it to length
bytes. If length is not given, writes the string followed by a zero.
If string is longer than length, the written part of the string does not have
a trailing zero.
*
@param s The string to write.
@param length The number of characters to write.
*/
writeCString(s: string, length: number): void;
/**
Reads an object of type t from the DataStream, passing struct as the thus-far
read struct to possible callbacks that refer to it. Used by readStruct for
reading in the values, so the type is one of the readStruct types.
*
@param t Type of the object to read.
@return Returns the object on successful read, null on unsuccessful.
*/
readType(t: Object): Object;
/**
Reads an object of type t from the DataStream, passing struct as the thus-far
read struct to possible callbacks that refer to it. Used by readStruct for
reading in the values, so the type is one of the readStruct types.
*
@param t Type of the object to read.
@param struct Struct to refer to when resolving length references and for calling callbacks.
@return Returns the object on successful read, null on unsuccessful.
*/
readType(t: Object, struct: Object): Object;
/**
Writes object v of type t to the DataStream.
*
@param t Type of data to write.
@param v Value of data to write.
@param struct Struct to pass to write callback functions.
*/
writeType(t: Object, v: Object, struct: Object): void;
}
+11 -1
View File
@@ -576,7 +576,7 @@ declare module AceAjax {
/**
* Returns the current tab size.
**/
getTabSize(): string;
getTabSize(): number;
/**
* Returns `true` if the character at the position is a soft tab.
@@ -1034,6 +1034,9 @@ declare module AceAjax {
* Event sessions dealing with the mouse and keyboard are bubbled up from `Document` to the `Editor`, which decides what to do with them.
**/
export interface Editor {
addEventListener(ev: 'change', callback: (ev: EditorChangeEvent) => any);
addEventListener(ev: string, callback: Function);
inMultiSelectMode: boolean;
@@ -1710,6 +1713,13 @@ declare module AceAjax {
**/
new(renderer: VirtualRenderer, session?: IEditSession): Editor;
}
interface EditorChangeEvent {
start: Position;
end: Position;
action: string; // insert, remove
lines: any[];
}
////////////////////////////////
/// PlaceHolder
@@ -10,35 +10,41 @@ module controllers {
static $inject = ["$upload"];
constructor(
private $upload: ng.angularFileUpload.IUploadService
private $upload: angular.angularFileUpload.IUploadService
) {
}
onFileSelect($files: File[]) {
//$files: an array of files selected, each file has name, size, and type.
var uploads: ng.IPromise<any>[] = [];
// $files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
uploads.push(this.$upload.upload<any>({
url: "/api/upload",
method: "POST",
data: {
extraData: {
fileName: file.name, test: "anything"
}
},
file: file
this.$upload.upload({
url: "/api/upload",
method: "POST",
data: {
extraData: {
fileName: file.name,
test: "anything"
}
},
file: file
})
.abort()
.xhr((evt: any) => {
console.log('xhr');
})
.progress((evt: any) => {
console.log('progress');
})
.then(success => {
// file is uploaded successfully
console.log(success.data);
})
.catch(err => {
console.error(err);
}));
.progress((evt: angular.angularFileUpload.IFileProgressEvent) => {
var percent = parseInt((100.0 * evt.loaded / evt.total).toString(), 10);
console.log("upload progress: " + percent + "% for " + evt.config.file.name);
})
.error((data: any, status: number, response: any, headers: any) => {
console.error(data, status, response, headers);
})
.success((data: any, status: number, headers: any, config: angular.angularFileUpload.IFileUploadConfig) => {
// file is uploaded successfully
console.log("Success!", data, status, headers, config);
});
}
}
}
+10 -4
View File
@@ -1,5 +1,5 @@
// Type definitions for Angular File Upload 1.6.7
// Project: https://github.com/danialfarid/angular-file-upload
// Type definitions for Angular File Upload 4.2.1
// Project: https://github.com/danialfarid/ng-file-upload
// Definitions by: John Reilly <https://github.com/johnnyreilly>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -14,8 +14,9 @@ declare module angular.angularFileUpload {
}
interface IUploadPromise<T> extends IHttpPromise<T> {
abort(): IUploadPromise<T>;
progress(callback: IHttpPromiseCallback<T>): IUploadPromise<T>;
xhr(callback: IHttpPromiseCallback<T>): IUploadPromise<T>;
}
interface IFileUploadConfig extends IRequestConfig {
@@ -23,4 +24,9 @@ declare module angular.angularFileUpload {
file: File;
fileName?: string;
}
}
interface IFileProgressEvent extends ProgressEvent {
config: IFileUploadConfig;
}
}
+17
View File
@@ -0,0 +1,17 @@
/// <reference path="../angularjs/angular.d.ts" />
/// <reference path="angular-jwt.d.ts" />
var app = angular.module("angular-jwt-tests", ["angular-jwt"]);
var $jwtHelper: angular.jwt.IJwtHelper;
var expToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3NhbXBsZXMuYXV0aDAuY29tLyIsInN1YiI6ImZhY2Vib29rfDEwMTU0Mjg3MDI3NTEwMzAyIiwiYXVkIjoiQlVJSlNXOXg2MHNJSEJ3OEtkOUVtQ2JqOGVESUZ4REMiLCJleHAiOjE0MTIyMzQ3MzAsImlhdCI6MTQxMjE5ODczMH0.7M5sAV50fF1-_h9qVbdSgqAnXVF7mz3I6RjS6JiH0H8';
var tokenPayload = $jwtHelper.decodeToken(expToken);
var date = $jwtHelper.getTokenExpirationDate(expToken);
var bool = $jwtHelper.isTokenExpired(expToken);
var $jwtInterceptor: angular.jwt.IJwtInterceptor;
$jwtInterceptor.tokenGetter = () => {
return expToken;
}
+30
View File
@@ -0,0 +1,30 @@
// Type definitions for angular-jwt 0.0.8
// Project: https://github.com/auth0/angular-jwt
// Definitions by: Reto Rezzonico <https://github.com/rerezz>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.jwt {
interface JwtToken {
iss: string;
sub: string;
aud: string;
exp: number;
nbf: number;
iat: number;
jti: string;
unique_name: string;
}
interface IJwtHelper {
decodeToken(token: string): JwtToken;
getTokenExpirationDate(token: any): Date;
isTokenExpired(token: any, offsetSeconds?: number): boolean;
}
interface IJwtInterceptor {
tokenGetter(): string;
}
}
+255
View File
@@ -0,0 +1,255 @@
/// <reference path="angular-meteor.d.ts" />
interface ITodo {
_id?: string;
name: string;
public?: boolean;
sticky?: boolean;
}
interface TodoAngularMeteorObject extends ITodo, angular.meteor.AngularMeteorObject<ITodo> {}
interface CustomScope extends angular.meteor.IScope {
sticky: boolean;
todos: angular.meteor.AngularMeteorCollection<ITodo>;
stickyTodos: angular.meteor.AngularMeteorCollection<ITodo>;
notAutoTodos: angular.meteor.AngularMeteorCollection<ITodo>;
todo: ITodo;
todoNotAuto: TodoAngularMeteorObject;
todoSubscribed: TodoAngularMeteorObject;
save: (todo: ITodo) => void;
saveAll: () =>void;
autoSave: (todo: ITodo) => void;
remove: (todoId: string) => void;
removeAll: () => void;
removeAuto: (todo: ITodo) => void;
toSticky: (todo: ITodo) => void;
}
var Todos = new Mongo.Collection<ITodo>('todos');
var app = angular.module('angularMeteorTestApp');
app.controller("mainCtrl", ['$scope', '$meteor', ($scope: CustomScope, $meteor: angular.meteor.IMeteorService) => {
// Bind all the todos to $scope.todos
$scope.todos = $meteor.collection(Todos);
$scope.sticky = true;
// Bind all sticky todos to $scope.stickyTodos
// Binds the query to $scope.sticky so that if it changes, Meteor will re-run the query and bind it
// to $scope.stickyTodos
$scope.stickyTodos = $meteor.collection<ITodo>(function(){
return Todos.find({sticky: $scope.getReactively('sticky')});
});
// Bind without auto-save all todos to $scope.notAutoTodos
$scope.notAutoTodos = $meteor.collection(Todos, false).subscribe("publicTodos");
$scope.todoNotAuto = <TodoAngularMeteorObject>$meteor.object(Todos, 'TodoID', false);
$scope.todoSubscribed = <TodoAngularMeteorObject>$meteor.object(Todos, 'TodoID').subscribe('todos');
$scope.todo = $scope.todoNotAuto.getRawObject();
$scope.todoNotAuto.reset();
$scope.todoNotAuto.save($scope.todo).then((data) => { return data == 1; });;
// todo might be an object like this {text: "Learn Angular", sticky: false}
// or an array like this:
// [{text: "Learn Angular", sticky: false}, {text: "Hello World", sticky: true}]
$scope.save = function(todo) {
$scope.notAutoTodos.save(todo);
};
$scope.saveAll = function() {
$scope.notAutoTodos.save();
};
$scope.autoSave = function(todo) {
$scope.todos.push(todo);
};
// todoId might be an string like this "WhrnEez5yBRgo4yEm"
// or an array like this ["WhrnEez5yBRgo4yEm","gH6Fa4DXA3XxQjXNS"]
$scope.remove = function(todoId) {
$scope.notAutoTodos.remove(todoId);
};
$scope.removeAll = function() {
$scope.notAutoTodos.remove();
};
$scope.removeAuto = function(todo) {
$scope.todos.splice( $scope.todos.indexOf(todo), 1 );
}
$scope.toSticky = function(todo) {
if (angular.isArray(todo)){
angular.forEach(todo, function(object) {
object.sticky = true;
});
} else {
todo.sticky = true;
}
$scope.stickyTodos.save(todo);
};
var todoObject = {name:'first todo'};
var todosArray = [{name:'second todo'}, {name:'third todo'}];
var todoSecondObject = {name:'forth todo'};
$scope.todos.save(todoObject); // todos equals [{name:'first todo'}]
$scope.todos.save(todosArray); // todos equals [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}]
$scope.todos.push(todoSecondObject); // The scope variable equals to [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}, {name:'forth todo'}]
// but the collection still equals to [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}]
$scope.todos.save(); // Now the collection also equals to [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}, {name:'forth todo'}]
$scope.todos.remove('firstTodoId'); // scope and collection equals to [{name:'second todo'}, {name:'third todo'}, {name:'forth todo'}]
var todoIdsArray = ['secondTodoId', 'thirdTodoId'];
$scope.todos.remove(todoIdsArray); // removes everything matches the array of IDs both in scope and in collection
$scope.todos.pop(); // removes only in scope
$scope.todos.remove(); // syncs also in Meteor collection
// Subscribe ->
$meteor.subscribe('todos').then((subscriptionHandle) => {
// Bind all the todos to $scope.todos
$scope.todos = $meteor.collection(Todos);
console.log($scope.todos + ' is ready');
// You can use the subscription handle to stop the subscription if you want
subscriptionHandle.stop();
});
$scope.subscribe('todos').then((subscriptionHandle) => {
// Bind all the todos to $scope.books
$scope.todos = $meteor.collection(Todos);
console.log($scope.todos + ' is ready');
// No need to stop the subscription, it will automatically close on scope destroy
});
$meteor.call<ITodo>('subscribe', $scope.todo._id, $scope.currentUser._id).then((data) => {
// Handle success
console.log('success subscribing', data.name);
}, (err) => {
// Handle error
console.log('failed', err);
});
if (!$scope.loggingIn) {
$meteor.waitForUser();
$meteor.requireUser();
$meteor.requireValidUser(user => {
return user.username == 'admin';
});
$meteor.loginWithPassword('user', 'password').then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.createUser({
username:'moma',
email:'example@gmail.com',
password: 'Bksd@asdf',
profile: {expertize: 'Developer'}
}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.changePassword('old', 'new232f3').then(() => {
console.log('Change password success');
}, err => {
console.log('Error changing password - ', err);
});
$meteor.forgotPassword({email: 'sample@gmail.com'}).then(() => {
console.log('Success sending forgot password email');
}, err => {
console.log('Error sending forgot password email - ', err);
});
$meteor.resetPassword('tokenID', 'new232f3').then(() => {
console.log('Reset password success');
}, err => {
console.log('Error resetting password - ', err);
});
$meteor.verifyEmail('tokenID').then(() => {
console.log('Success verifying password ');
}, err => {
console.log('Error verifying password - ', err);
});
$meteor.logout().then(() => {
console.log('Logout success');
}, err => {
console.log('logout error - ', err);
});
$meteor.logoutOtherClients().then(() => {
console.log('Logout success');
}, err => {
console.log('logout error - ', err);
});
var loginWithOptions = {requestPermissions: ['email']};
$meteor.loginWithFacebook({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithGithub({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithGoogle({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithMeetup({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithTwitter({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithWeibo({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
}
$meteor.autorun($scope, () => { console.log("Aurorun triggered."); });
$meteor.getCollectionByName('collectionName');
// requires meteor add mdg:camera
$meteor.getPicture().then(function(data){
$scope['picture'] = data;
});
$meteor.session('counter').bind($scope, 'counter');
}]);
+330
View File
@@ -0,0 +1,330 @@
// Type definitions for Angular JS Meteor v0.8.8 (angular.meteor module)
// Project: https://github.com/Urigo/angular-meteor
// Definitions by: Peter Grman <https://github.com/pgrm>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../meteor/meteor.d.ts" />
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.meteor {
interface IRootScopeService extends angular.IRootScopeService {
/**
* The current logged in user and it's data. it is null if the user is not logged in. A reactive data source.
*/
currentUser: Meteor.User;
/**
* True if a login method (such as Meteor.loginWithPassword, Meteor.loginWithFacebook, or Accounts.createUser) is currently in progress.
* A reactive data source. Can be use to display animation while user is logging in.
*/
loggingIn: boolean;
}
interface IScope extends angular.IScope, IRootScopeService {
/**
* A method to get a $scope variable and watch it reactivly
*
* @param scopeVariableName - The name of the scope's variable to bind to
* @param [objectEquality=false] - Watch the object equality using angular.equals instead of comparing for reference equality, deeper watch but also slower
*/
getReactively(scopeVariableName: string, objectEquality?: boolean): ReactiveResult;
/**
* A service which is a wrapper for Meteor.subscribe. It subscribes to a Meteor.publish method in the client and returns a AngularJS promise when ready.
* Calling $scope.subscribe will automatically stop the subscription when the scope is destroyed.
*
* @param name - Name of the subscription. Matches the name of the server's publish() call.
* @param publisherArguments - Optional arguments passed to publisher function on server.
*
* @return The promise solved successfully when subscription is ready. The success promise holds the subscription handle.
*/
subscribe(name: string, ...publisherArguments: any[]): angular.IPromise<Meteor.SubscriptionHandle>;
}
/**
* $meteor in angularjs
*/
interface IMeteorService {
/**
* A service that wraps the Meteor collections to enable reactivity within AngularJS.
*
* @param collection - A Meteor Collection or a reactive function to bind to.
* - Reactive function can be used with $scope.getReactively to add $scope variable as reactive variable to the cursor.
* @param [autoClientSave=true] - By default, changes in the Angular collection will automatically update the Meteor collection.
* - However if set to false, changes in the client won't be automatically propagated back to the Meteor collection.
*/
collection<T>(collection: Mongo.Collection<T>|ReactiveResult|Function|(()=>T), autoClientSave?: boolean): AngularMeteorCollection<T>;
/**
* A service that wraps the Meteor collections to enable reactivity within AngularJS.
*
* @param collection - A Meteor Collection or a reactive function to bind to.
* - Reactive function can be used with $scope.getReactively to add $scope variable as reactive variable to the cursor.
* @param [autoClientSave=true] - By default, changes in the Angular collection will automatically update the Meteor collection.
* - However if set to false, changes in the client won't be automatically propagated back to the Meteor collection.
* @param [updateCollection] - A collection object which will be used for updates (insert, update, delete).
*/
collection<T, U>(collection: Mongo.Collection<T>|ReactiveResult|Function|(()=>T), autoClientSave: boolean, updateCollection: Mongo.Collection<U>): AngularMeteorCollection2<T, U>;
/**
* A service that wraps a Meteor object to enable reactivity within AngularJS.
* Finds the first document that matches the selector, as ordered by sort and skip options. Wraps collection.findOne
*
* @param collection - A Meteor Collection to bind to.
* @param selector - A query describing the documents to find or just the ID of the document.
* - $meteor.object will find the first document that matches the selector,
* - as ordered by sort and skip options, exactly like Meteor's collection.findOne
* @param [autoClientSave=true] - By default, changes in the Angular object will automatically update the Meteor object.
* - However if set to false, changes in the client won't be automatically propagated back to the Meteor object.
*/
object<T>(collection: Mongo.Collection<T>, selector: Mongo.Selector|Mongo.ObjectID|string, autoClientSave?: boolean): AngularMeteorObject<T>;
/**
* A service which is a wrapper for Meteor.subscribe. It subscribes to a Meteor.publish method in the client and returns a AngularJS promise when ready.
*
* @param name - Name of the subscription. Matches the name of the server's publish() call.
* @param publisherArguments - Optional arguments passed to publisher function on server.
*
* @return The promise solved successfully when subscription is ready. The success promise holds the subscription handle.
*/
subscribe(name: string, ...publisherArguments: any[]): angular.IPromise<Meteor.SubscriptionHandle>;
/**
* A service service which wraps up Meteor.methods with AngularJS promises.
*
* @param name - Name of method to invoke
* @param methodArguments - Optional method arguments
*
* @return The promise solves successfully with the return value of the method or return reject with the error from the method.
*/
call<T>(name: string, ...methodArguments: any[]): angular.IPromise<T>;
// User Authentication BEGIN ->
/**
* Returns a promise fulfilled with the currentUser when the user subscription is ready.
* This is useful when you want to grab the current user before the route is rendered.
* If there is no logged in user, it will return null.
* See the “Authentication with Routers” section of our tutorial for more information and a full example.
*/
waitForUser(): angular.IPromise<Meteor.User>;
/**
* Resolves the promise successfully if a user is authenticated and rejects otherwise.
* This is useful in cases where you want to require a route to have an authenticated user.
* You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page.
* See the “Authentication with Routers” section of our tutorial for more information and a full example.
*/
requireUser(): angular.IPromise<Meteor.User>;
/**
* Resolves the promise successfully if a user is authenticated and the validatorFn returns true; rejects otherwise.
* This is useful in cases where you want to require a route to have an authenticated user and do extra validation like the user's role or group.
* You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page.
* See the “Authentication with Routers” section of our tutorial for more information and a full example.
*
* The mandatory validator function will be called with the authenticated user as the single param and it's expected to return true in order to resolve.
* If it returns a string, the promise will be rejected using said string as the reason.
* Any other return (false, null, undefined) will be rejected with the default "FORBIDDEN" reason.
*/
requireValidUser(validatorFn: (user: Meteor.User) => boolean|string): angular.IPromise<Meteor.User>;
/**
* Log the user in with a password.
*
* @param user - Either a string interpreted as a username or an email; or an object with a single key: email, username or id.
* @param password - The user's password.
*/
loginWithPassword(user: string|{email: string}|{username: string}|{id: string}, password: string): angular.IPromise<void>;
/**
* Create a new user. More information: http://docs.meteor.com/#/full/accounts_createuser
*
* @param options.username - A unique name for this user. Either this, or email is required.
* @param options.email - The user's email address. Either this, or username is required.
* @param options.password - The user's password. This is not sent in plain text over the wire.
* @param options.profile - The user's profile, typically including the name field.
*/
createUser(options: {username?: string; email?: string; password: string; profile?: Object}): angular.IPromise<void>;
/**
* Change the current user's password. Must be logged in.
*
* @param oldPassword - The user's current password. This is not sent in plain text over the wire.
* @param newPassword - A new password for the user. This is not sent in plain text over the wire.
*/
changePassword(oldPassword: string, newPassword: string): angular.IPromise<void>;
/**
* Request a forgot password email.
*
* @param options.email - The email address to send a password reset link.
*/
forgotPassword(options: {email: string}): angular.IPromise<void>;
/**
* Reset the password for a user using a token received in email. Logs the user in afterwards.
*
* @param token - The token retrieved from the reset password URL.
* @param newPassword - A new password for the user. This is not sent in plain text over the wire.
*/
resetPassword(token: string, newPassword: string): angular.IPromise<void>;
/**
* Marks the user's email address as verified. Logs the user in afterwards.
*
* @param token - The token retrieved from the reset password URL.
*/
verifyEmail(token: string): angular.IPromise<void>;
loginWithFacebook: ILoginWithExternalService;
loginWithTwitter: ILoginWithExternalService;
loginWithGoogle: ILoginWithExternalService;
loginWithGithub: ILoginWithExternalService;
loginWithMeetup: ILoginWithExternalService;
loginWithWeibo: ILoginWithExternalService;
/**
* Log the user out.
*
* @return Resolves with no arguments on success, or reject with a Error argument on failure.
*/
logout(): angular.IPromise<void>;
/**
* Log out other clients logged in as the current user, but does not log out the client that calls this function.
* For example, when called in a user's browser, connections in that browser remain logged in,
* but any other browsers or DDP clients logged in as that user will be logged out.
*
* @return Resolves with no arguments on success, or reject with a Error argument on failure.
*/
logoutOtherClients(): angular.IPromise<void>;
// <- User Authentication END
// $meteorUtils BEGIN ->
/**
* @param scope - The AngularJS scope you use the autorun on.
* @param fn - The function that will re-run every time a reactive variable changes inside it.
*/
autorun(scope: angular.IScope, fn: Function): void;
/**
* @param collectionName - The name of the collection you want to get back
*/
getCollectionByName<T>(collectionName: string): Mongo.Collection<T>;
// <- $meteorUtils END
// $meteorCamera BEGIN ->
/**
* A helper service for taking pictures across platforms.
* Must add mdg:camera package to use! (meteor add mdg:camera)
*
* @param [options] - options is an optional argument that is an Object with the following possible keys:
* @param options.width - An integer that specifies the minimum width of the returned photo.
* @param options.height - An integer that specifies the minimum height of the returned photo.
* @param options.quality - A number from 0 to 100 specifying the desired quality of JPEG encoding.
*
* @return The promise solved successfully when the picture is taken with the data as a parameter or rejected with an error as a parameter in case of error.
*/
getPicture(options?: {width?: number; height?: number; quality?: number}): angular.IPromise<any>;
// <- $meteorCamera END
/**
* A service that binds a scope variable to a Meteor Session variable.
*
* @param sessionKey - The name of the session variable
* @return An object with a single function bind - to bind to that variable.
*/
session(sessionKey: string): {
/**
* @param scope - The scope the document will be bound to.
* @param model - The name of the scope's model variable that the document will be bound to.
*/
bind: (scope: IScope, model: string) => void;
};
}
/**
* An object that connects a Meteor Object to an AngularJS scope variable.
*
* The object contains also all the properties from the generic type T,
* unfortunately TypeScript doesn't at the moment allow to extend a generic type (see https://github.com/Microsoft/TypeScript/issues/2225 for details and updates).
* For a workaround, you'll need to implement an interface which will merge AngularMeteorObject<T> together with T and cast it, like this:
*
* interface TodoAngularMeteorObject extends ITodo, AngularMeteorObject<ITodo> { }
* var todo = <TodoAngularMeteorObject>$meteor.object(TodoCollection, 'TodoID');
*/
interface AngularMeteorObject<T> {
/**
* @param [doc] - The doc to save to the Meteor Object. If nothing is passed, the method saves everything in the AngularMeteorObject as is.
* - Unchanged properties will be overridden with their existing values, which may trigger hooks.
* - If doc is passed, the method only updates the Meteor Object with the properties passed, and no other changes will be saved.
*
* @return Returns a promise with an error in case for an error or a number of successful docs changed in case of success.
*/
save(doc?: T): angular.IPromise<number>;
/**
* Reset the current value of the object to the one in the server.
*/
reset(): void;
/**
* Returns a copy of the AngularMeteorObject with all the AngularMeteor-specific internal properties removed.
* The returned object is then safe to use as a parameter for method calls, or anywhere else where the data needs to be converted to JSON.
*/
getRawObject(): T;
/**
* A shorten (Syntactic sugar) function for the $meteor.subscribe function.
* Takes only one parameter and not returns a promise like $meteor.subscribe does.
*
* @param subscriptionName - The subscription name to subscribe to. Exactly like the first parameter in $meteor.subscribe service.
*/
subscribe(subscriptionName:string): AngularMeteorObject<T>;
}
/**
* An object that connects a Meteor Collection to an AngularJS scope variable
*/
interface AngularMeteorCollection<T> extends AngularMeteorCollection2<T, T> { }
/**
* An object that connects a Meteor Collection to an AngularJS scope variable,
* but can use a differen type for updates.
*/
interface AngularMeteorCollection2<T, U> extends Array<T> {
/**
* @param [docs] - The docs to save to the Meteor Collection.
* - If the docs parameter is empty, the method saves everything in the AngularMeteorCollection as is.
* - If an object is passed, the method pushes that object into the AngularMeteorCollection.
* - If an array is passed, the method pushes all objects in the array into the AngularMeteorCollection.
*/
save(docs?: U|U[]): void;
/**
* @param [keys] - The keys of the object to remove from the Meteor Collection.
* - If nothing is passed, the method removes all the documents from the AngularMeteorCollection.
* - If an object is passed, the method removes the object with that key from the AngularMeteorCollection.
* - If an array is passed, the method removes all objects that matches the keys in the array from the AngularMeteorCollection.
*/
remove(keys?: U|string|number|string[]|number[]): void;
/**
* A shorten (Syntactic sugar) function for the $meteor.subscribe function.
* Takes only one parameter and not returns a promise like $meteor.subscribe does.
*
* @param subscriptionName - The subscription name to subscribe to. Exactly like the first parameter in $meteor.subscribe service.
*/
subscribe(subscriptionName:string): AngularMeteorCollection2<T, U>;
}
interface ILoginWithExternalService {
(options: Meteor.LoginWithExternalServiceOptions): angular.IPromise<void>;
}
interface ReactiveResult { }
}
+18 -9
View File
@@ -6,13 +6,7 @@
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.translate {
interface ITranslatePartialLoaderService {
addPart(name: string): ITranslatePartialLoaderService;
deletePart(name: string, removeData?: boolean): ITranslatePartialLoaderService;
isPartAvailable(name: string): boolean;
}
interface ITranslationTable {
[key: string]: string;
}
@@ -26,12 +20,27 @@ declare module angular.translate {
set(name: string, value: string): void;
}
interface ISTaticFilesLoaderOptions {
interface IStaticFilesLoaderOptions {
prefix: string;
suffix: string;
key?: string;
}
interface IPartialLoader<T> {
addPart(name : string, priority? : number) : T;
deletePart(name : string) : T;
isPartAvailable(name : string) : boolean;
}
interface ITranslatePartialLoaderService extends IPartialLoader<ITranslatePartialLoaderService> {
getRegisteredParts() : Array<string>;
isPartLoaded(name : string, lang : string) : boolean;
}
interface ITranslatePartialLoaderProvider extends angular.IServiceProvider, IPartialLoader<ITranslatePartialLoaderProvider> {
setPart(lang : string, part : string, table : ITranslationTable) : ITranslatePartialLoaderProvider;
}
interface ITranslateService {
(translationId: string, interpolateParams?: any, interpolationId?: string): angular.IPromise<string>;
(translationId: string[], interpolateParams?: any, interpolationId?: string): angular.IPromise<{ [key: string]: string }>;
@@ -78,7 +87,7 @@ declare module angular.translate {
storageKey(): string;
storageKey(key: string): void; // JeroMiya - the library should probably return ITranslateProvider but it doesn't here
useUrlLoader(url: string): ITranslateProvider;
useStaticFilesLoader(options: ISTaticFilesLoaderOptions): ITranslateProvider;
useStaticFilesLoader(options: IStaticFilesLoaderOptions): ITranslateProvider;
useLoader(loaderFactory: string, options: any): ITranslateProvider;
useLocalStorage(): ITranslateProvider;
useCookieStorage(): ITranslateProvider;
+4 -4
View File
@@ -46,7 +46,7 @@ myapp.controller("MyController", ["$scope", "$firebase", '$FirebaseObject', '$Fi
// AngularFireObject
{
var obj = sync.$asObject();
var obj = $FirebaseObject(ref);
// $id
if (obj.$id !== ref.name()) throw "error";
@@ -63,7 +63,7 @@ myapp.controller("MyController", ["$scope", "$firebase", '$FirebaseObject', '$Fi
});
// $ref()
if (obj.$ref() !== sync) throw "error";
if (obj.$ref() !== ref) throw "error";
// $bindTo()
obj.$bindTo($scope, "data").then(function () {
@@ -92,10 +92,10 @@ myapp.controller("MyController", ["$scope", "$firebase", '$FirebaseObject', '$Fi
// AngularFireArray
{
var list = sync.$asArray();
var list = $FirebaseArray(ref);
// $ref()
if (list.$ref() !== sync) throw "error";
if (list.$ref() !== ref) throw "error";
// $add()
list.$add({ foo: "foo value" });
+387 -2
View File
@@ -10,6 +10,9 @@ interface AngularFireService {
(firebase: Firebase, config?: any): AngularFire;
}
/**
* @deprecated. Not possible with AngularFire 1.0+
*/
interface AngularFire {
$asArray(): AngularFireArray;
$asObject(): AngularFireObject;
@@ -24,37 +27,279 @@ interface AngularFire {
$transaction(key:string, updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise<FirebaseDataSnapshot>;
}
/**
* Creates and maintains a synchronized object, with 2-way bindings between Angular and Firebase.
*/
interface AngularFireObject extends AngularFireSimpleObject {
$id: string;
$priority: number;
$value: any;
/**
* Removes all keys from the FirebaseObject and also removes
* the remote data from the server.
*
* @returns a promise which will resolve after the op completes
*/
$remove(): ng.IPromise<Firebase>;
/**
* Saves all data on the FirebaseObject back to Firebase.
* @returns a promise which will resolve after the save is completed.
*/
$save(): ng.IPromise<Firebase>;
/**
* The loaded method is invoked after the initial batch of data arrives from the server.
* When this resolves, all data which existed prior to calling $asObject() is now cached
* locally in the object.
*
* As a shortcut is also possible to pass resolve/reject methods directly into this
* method just as they would be passed to .then()
*
* @param {Function} resolve
* @param {Function} reject
* @returns a promise which resolves after initial data is downloaded from Firebase
*/
$loaded(resolve?: (x: AngularFireObject) => ng.IHttpPromise<{}>, reject?: (err: any) => any): ng.IPromise<AngularFireObject>;
/**
* The loaded method is invoked after the initial batch of data arrives from the server.
* When this resolves, all data which existed prior to calling $asObject() is now cached
* locally in the object.
*
* As a shortcut is also possible to pass resolve/reject methods directly into this
* method just as they would be passed to .then()
*
* @param {Function} resolve
* @param {Function} reject
* @returns a promise which resolves after initial data is downloaded from Firebase
*/
$loaded(resolve?: (x: AngularFireObject) => ng.IPromise<{}>, reject?: (err: any) => any): ng.IPromise<AngularFireObject>;
/**
* The loaded method is invoked after the initial batch of data arrives from the server.
* When this resolves, all data which existed prior to calling $asObject() is now cached
* locally in the object.
*
* As a shortcut is also possible to pass resolve/reject methods directly into this
* method just as they would be passed to .then()
*
* @param {Function} resolve
* @param {Function} reject
* @returns a promise which resolves after initial data is downloaded from Firebase
*/
$loaded(resolve?: (x: AngularFireObject) => void, reject?: (err: any) => any): ng.IPromise<AngularFireObject>;
$ref(): AngularFire;
/**
* @returns {Firebase} the original Firebase instance used to create this object.
*/
$ref(): Firebase;
/**
* Creates a 3-way data sync between this object, the Firebase server, and a
* scope variable. This means that any changes made to the scope variable are
* pushed to Firebase, and vice versa.
*
* If scope emits a $destroy event, the binding is automatically severed. Otherwise,
* it is possible to unbind the scope variable by using the `unbind` function
* passed into the resolve method.
*
* Can only be bound to one scope variable at a time. If a second is attempted,
* the promise will be rejected with an error.
*
* @param {object} scope
* @param {string} varName
* @returns a promise which resolves to an unbind method after data is set in scope
*/
$bindTo(scope: ng.IScope, varName: string): ng.IPromise<any>;
/**
* Listeners passed into this method are notified whenever a new change is received
* from the server. Each invocation is sent an object containing
* <code>{ type: 'value', key: 'my_firebase_id' }</code>
*
* This method returns an unbind function that can be used to detach the listener.
*
* @param {Function} cb
* @param {Object} [context]
* @returns {Function} invoke to stop observing events
*/
$watch(callback: Function, context?: any): Function;
/**
* Informs $firebase to stop sending events and clears memory being used
* by this object (delete's its local content).
*/
$destroy(): void;
}
interface AngularFireObjectService {
/**
* Creates a synchronized object with 2-way bindings between Angular and Firebase.
*
* @param {Firebase} ref
* @returns {FirebaseObject}
*/
(firebase: Firebase): AngularFireObject;
$extend(ChildClass: Object, methods?: Object): Object;
}
/**
* Creates and maintains a synchronized list of data. This is a pseudo-read-only array. One should
* not call splice(), push(), pop(), et al directly on this array, but should instead use the
* $remove and $add methods.
*
* It is acceptable to .sort() this array, but it is important to use this in conjunction with
* $watch(), so that it will be re-sorted any time the server data changes. Examples of this are
* included in the $watch documentation.
*/
interface AngularFireArray extends Array<AngularFireSimpleObject> {
/**
* Create a new record with a unique ID and add it to the end of the array.
* This should be used instead of Array.prototype.push, since those changes will not be
* synchronized with the server.
*
* Any value, including a primitive, can be added in this way. Note that when the record
* is created, the primitive value would be stored in $value (records are always objects
* by default).
*
* Returns a future which is resolved when the data has successfully saved to the server.
* The resolve callback will be passed a Firebase ref representing the new data element.
*
* @param data
* @returns a promise resolved after data is added
*/
$add(newData: any): ng.IPromise<Firebase>;
/**
* Pass either an item in the array or the index of an item and it will be saved back
* to Firebase. While the array is read-only and its structure should not be changed,
* it is okay to modify properties on the objects it contains and then save those back
* individually.
*
* Returns a future which is resolved when the data has successfully saved to the server.
* The resolve callback will be passed a Firebase ref representing the saved element.
* If passed an invalid index or an object which is not a record in this array,
* the promise will be rejected.
*
* @param {int|object} indexOrItem
* @returns a promise resolved after data is saved
*/
$save(recordOrIndex: any): ng.IPromise<Firebase>;
/**
* Pass either an existing item in this array or the index of that item and it will
* be removed both locally and in Firebase. This should be used in place of
* Array.prototype.splice for removing items out of the array, as calling splice
* will not update the value on the server.
*
* Returns a future which is resolved when the data has successfully removed from the
* server. The resolve callback will be passed a Firebase ref representing the deleted
* element. If passed an invalid index or an object which is not a record in this array,
* the promise will be rejected.
*
* @param {int|object} indexOrItem
* @returns a promise which resolves after data is removed
*/
$remove(recordOrIndex: any): ng.IPromise<Firebase>;
/**
* Returns the record for a given Firebase key (record.$id). If the record is not found
* then returns null.
*
* @param {string} key
* @returns {Object|null} a record in this array
*/
$getRecord(key: string): AngularFireSimpleObject;
/**
* Given an item in this array or the index of an item in the array, this returns the
* Firebase key (record.$id) for that record. If passed an invalid key or an item which
* does not exist in this array, it will return null.
*
* @param {int|object} indexOrItem
* @returns {null|string}
*/
$keyAt(recordOrIndex: any): string;
/**
* The inverse of $keyAt, this method takes a Firebase key (record.$id) and returns the
* index in the array where that record is stored. If the record is not in the array,
* this method returns -1.
*
* @param {String} key
* @returns {int} -1 if not found
*/
$indexFor(key: string): number;
/**
* The loaded method is invoked after the initial batch of data arrives from the server.
* When this resolves, all data which existed prior to calling $asArray() is now cached
* locally in the array.
*
* As a shortcut is also possible to pass resolve/reject methods directly into this
* method just as they would be passed to .then()
*
* @param {Function} [resolve]
* @param {Function} [reject]
* @returns a promise
*/
$loaded(resolve?: (x: AngularFireArray) => ng.IHttpPromise<{}>, reject?: (err: any) => any): ng.IPromise<AngularFireArray>;
/**
* The loaded method is invoked after the initial batch of data arrives from the server.
* When this resolves, all data which existed prior to calling $asArray() is now cached
* locally in the array.
*
* As a shortcut is also possible to pass resolve/reject methods directly into this
* method just as they would be passed to .then()
*
* @param {Function} [resolve]
* @param {Function} [reject]
* @returns a promise
*/
$loaded(resolve?: (x: AngularFireArray) => ng.IPromise<{}>, reject?: (err: any) => any): ng.IPromise<AngularFireArray>;
/**
* The loaded method is invoked after the initial batch of data arrives from the server.
* When this resolves, all data which existed prior to calling $asArray() is now cached
* locally in the array.
*
* As a shortcut is also possible to pass resolve/reject methods directly into this
* method just as they would be passed to .then()
*
* @param {Function} [resolve]
* @param {Function} [reject]
* @returns a promise
*/
$loaded(resolve?: (x: AngularFireArray) => void, reject?: (err: any) => any): ng.IPromise<AngularFireArray>;
$ref(): AngularFire;
/**
* @returns {Firebase} the original Firebase ref used to create this object.
*/
$ref(): Firebase;
/**
* Listeners passed into this method are notified whenever a new change (add, updated,
* move, remove) is received from the server. Each invocation is sent an object
* containing <code>{ type: 'child_added|child_updated|child_moved|child_removed',
* key: 'key_of_item_affected'}</code>
*
* Additionally, added and moved events receive a prevChild parameter, containing the
* key of the item before this one in the array.
*
* This method returns a function which can be invoked to stop observing events.
*
* @param {Function} cb
* @param {Object} [context]
* @returns {Function} used to stop observing
*/
$watch(cb: (event: string, key: string, prevChild: string) => void, context?: any): Function;
/**
* Informs $firebase to stop sending events and clears memory being used
* by this array (delete's its local content).
*/
$destroy(): void;
}
interface AngularFireArrayService {
@@ -75,20 +320,160 @@ interface AngularFireAuthService {
}
interface AngularFireAuth {
/**
* Authenticates the Firebase reference with a custom authentication token.
*
* @param {string} authToken An authentication token or a Firebase Secret. A Firebase Secret
* should only be used for authenticating a server process and provides full read / write
* access to the entire Firebase.
* @param {Object} [options] An object containing optional client arguments, such as configuring
* session persistence.
* @return {Promise<Object>} A promise fulfilled with an object containing authentication data.
*/
$authWithCustomToken(authToken: string, options?: Object): ng.IPromise<any>;
/**
* Authenticates the Firebase reference anonymously.
*
* @param {Object} [options] An object containing optional client arguments, such as configuring
* session persistence.
* @return {Promise<Object>} A promise fulfilled with an object containing authentication data.
*/
$authAnonymously(options?: Object): ng.IPromise<any>;
/**
* Authenticates the Firebase reference with an email/password user.
*
* @param {Object} credentials An object containing email and password attributes corresponding
* to the user account.
* @param {Object} [options] An object containing optional client arguments, such as configuring
* session persistence.
* @return {Promise<Object>} A promise fulfilled with an object containing authentication data.
*/
$authWithPassword(credentials: FirebaseCredentials, options?: Object): ng.IPromise<any>;
/**
* Authenticates the Firebase reference with the OAuth popup flow.
*
* @param {string} provider The unique string identifying the OAuth provider to authenticate
* with, e.g. google.
* @param {Object} [options] An object containing optional client arguments, such as configuring
* session persistence.
* @return {Promise<Object>} A promise fulfilled with an object containing authentication data.
*/
$authWithOAuthPopup(provider: string, options?: Object): ng.IPromise<any>;
/**
* Authenticates the Firebase reference with the OAuth redirect flow.
*
* @param {string} provider The unique string identifying the OAuth provider to authenticate
* with, e.g. google.
* @param {Object} [options] An object containing optional client arguments, such as configuring
* session persistence.
* @return {Promise<Object>} A promise fulfilled with an object containing authentication data.
*/
$authWithOAuthRedirect(provider: string, options?: Object): ng.IPromise<any>;
/**
* Authenticates the Firebase reference with an OAuth token.
*
* @param {string} provider The unique string identifying the OAuth provider to authenticate
* with, e.g. google.
* @param {string|Object} credentials Either a string, such as an OAuth 2.0 access token, or an
* Object of key / value pairs, such as a set of OAuth 1.0a credentials.
* @param {Object} [options] An object containing optional client arguments, such as configuring
* session persistence.
* @return {Promise<Object>} A promise fulfilled with an object containing authentication data.
*/
$authWithOAuthToken(provider: string, credentials: Object|string, options?: Object): ng.IPromise<any>;
/**
* Synchronously retrieves the current authentication data.
*
* @return {Object} The client's authentication data.
*/
$getAuth(): FirebaseAuthData;
/**
* Asynchronously fires the provided callback with the current authentication data every time
* the authentication data changes. It also fires as soon as the authentication data is
* retrieved from the server.
*
* @param {function} callback A callback that fires when the client's authenticate state
* changes. If authenticated, the callback will be passed an object containing authentication
* data according to the provider used to authenticate. Otherwise, it will be passed null.
* @param {string} [context] If provided, this object will be used as this when calling your
* callback.
* @return {function} A function which can be used to deregister the provided callback.
*/
$onAuth(callback: Function, context?: any): Function;
/**
* Unauthenticates the Firebase reference.
*/
$unauth(): void;
/**
* Utility method which can be used in a route's resolve() method to grab the current
* authentication data.
*
* @returns {Promise<Object|null>} A promise fulfilled with the client's current authentication
* state, which will be null if the client is not authenticated.
*/
$waitForAuth(): ng.IPromise<any>;
/**
* Utility method which can be used in a route's resolve() method to require that a route has
* a logged in client.
*
* @returns {Promise<Object>} A promise fulfilled with the client's current authentication
* state or rejected if the client is not authenticated.
*/
$requireAuth(): ng.IPromise<any>;
/**
* Creates a new email/password user. Note that this function only creates the user, if you
* wish to log in as the newly created user, call $authWithPassword() after the promise for
* this method has been resolved.
*
* @param {Object} credentials An object containing the email and password of the user to create.
* @return {Promise<Object>} A promise fulfilled with the user object, which contains the
* uid of the created user.
*/
$createUser(credentials: FirebaseCredentials): ng.IPromise<any>;
/**
* Removes an email/password user.
*
* @param {Object} credentials An object containing the email and password of the user to remove.
* @return {Promise<>} An empty promise fulfilled once the user is removed.
*/
$removeUser(credentials: FirebaseCredentials): ng.IPromise<any>;
/**
* Changes the email for an email/password user.
*
* @param {Object} credentials An object containing the old email, new email, and password of
* the user whose email is to change.
* @return {Promise<>} An empty promise fulfilled once the email change is complete.
*/
$changeEmail(credentials: FirebaseChangeEmailCredentials): ng.IPromise<any>;
/**
* Changes the password for an email/password user.
*
* @param {Object} credentials An object containing the email, old password, and new password of
* the user whose password is to change.
* @return {Promise<>} An empty promise fulfilled once the password change is complete.
*/
$changePassword(credentials: FirebaseChangePasswordCredentials): ng.IPromise<any>;
/**
* Sends a password reset email to an email/password user.
*
* @param {Object} credentials An object containing the email of the user to send a reset
* password email to.
* @return {Promise<>} An empty promise fulfilled once the reset password email is sent.
*/
$resetPassword(credentials: FirebaseResetPasswordCredentials): ng.IPromise<any>;
}
@@ -0,0 +1,42 @@
/// <reference path="angularjs-toaster.d.ts" />
class NgToasterTestController {
constructor(public $scope: ng.IScope, public $window: ng.IWindowService, public toaster: ngtoaster.IToasterService) {
this.bar = 'Hi';
}
bar: string;
pop(): void {
this.toaster.success({ title: "title", body: "text1" });
this.toaster.error("title", "text2");
this.toaster.pop({ type: 'wait', title: "title", body: "text" });
this.toaster.pop('success', "title", '<ul><li>Render html</li></ul>', 5000, 'trustedHtml');
this.toaster.pop('error', "title", '<ul><li>Render html</li></ul>', null, 'trustedHtml');
this.toaster.pop('wait', "title", null, null, 'template');
this.toaster.pop('warning', "title", "myTemplate.html", null, 'template');
this.toaster.pop('note', "title", "text");
this.toaster.pop('success', "title", 'Its address is https://google.com.', 5000, 'trustedHtml', (toaster: ngtoaster.IToast): boolean => {
var match = toaster.body.match(/http[s]?:\/\/[^\s]+/);
if (match) {
this.$window.open(match[0]);
}
return true;
});
this.toaster.pop('warning', "Hi ", "{template: 'myTemplateWithData.html', data: 'MyData'}", 15000, 'templateWithData');
}
goToLink(toaster: ngtoaster.IToast): boolean {
var match = toaster.body.match(/http[s]?:\/\/[^\s]+/);
if (match) {
this.$window.open(match[0]);
}
return true;
}
clear(): void {
this.toaster.clear();
}
}
angular
.module('main', ['ngAnimate', 'toaster'])
.controller('myController', NgToasterTestController);
+109
View File
@@ -0,0 +1,109 @@
// Type definitions for angularjs-toaster v0.4.13
// Project: https://github.com/jirikavi/AngularJS-Toaster
// Definitions by: Ben Tesser <https://github.com/btesser>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module ngtoaster {
interface IToasterService {
pop(params:IPopParams): void
/**
* @param {string} type Type of toaster -- 'error', 'info', 'wait', 'success', and 'warning'
*/
pop(type?:string, title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener,
toasterId?:number, showCloseButton?:boolean): void
error(params: IPopParams): void
error(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener,
toasterId?:number): void
into(params: IPopParams): void
info(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener,
toasterId?:number): void
wait(params: IPopParams): void
wait(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener,
toasterId?:number): void
success(params: IPopParams): void
success(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener,
toasterId?:number): void
warning(params: IPopParams): void
warning(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener,
toasterId?:number): void
clear(): void
toast:IToast;
}
interface IToasterEventRegistry {
setup(): void
subscribeToNewToastEvent(onNewToast:IToastEventListener): void
subscribeToClearToastsEvent(onClearToasts:IToastEventListener): void
unsubscribeToNewToastEvent(onNewToast:IToastEventListener): void
unsubscribeToClearToastsEvent(onClearToasts:IToastEventListener): void
}
interface IPopParams extends IToast{
toasterId?: number;
}
interface IToastEventListener {
(event:Event, toasterId: number): void;
}
interface IToast {
/**
* Acceptable types are:
* 'error', 'info', 'wait', 'success', and 'warning'
*/
type?: string;
title?: string;
body?: string;
timeout?: number;
bodyOutputType?: string;
clickHandler?: EventListener;
showCloseButton?: boolean;
}
interface IToasterConfig {
/**
* limits max number of toasts
*/
limit?: number;
'tap-to-dismiss'?: boolean;
'close-button'?: boolean;
'newest-on-top'?: boolean;
'time-out'?: number;
'icon-classes'?: IIconClasses;
/**
* Options include:
* '', 'trustedHtml', 'template', 'templateWithData'
*/
'body-output-type'?: string;
'body-template'?: string;
'icon-class'?: string;
/**
* Options include:
* 'toast-top-full-width', 'toast-bottom-full-width', 'toast-center',
* 'toast-top-left', 'toast-top-center', 'toast-top-rigt',
* 'toast-bottom-left', 'toast-bottom-center', 'toast-bottom-rigt',
*/
'position-class'?: string;
'title-class'?: string;
'message-class'?: string;
'prevent-duplicates'?: boolean;
/**
* stop timeout on mouseover and restart timer on mouseout
*/
'mouseover-timer-stop'?: boolean;
}
interface IIconClasses {
error: string;
info: string;
wait: string;
success: string;
warning: string;
}
}
declare module "ngtoaster" {
export = ngtoaster
}
+5 -2
View File
@@ -39,8 +39,11 @@ declare module angular {
dump(obj: any): string;
// see http://docs.angularjs.org/api/angular.mock.inject
inject(...fns: Function[]): any;
inject(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works
inject: {
(...fns: Function[]): any;
(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works
strictDi(val?: boolean): void;
}
// see http://docs.angularjs.org/api/angular.mock.module
module(...modules: any[]): any;
+121 -19
View File
@@ -474,6 +474,7 @@ declare module angular {
// types do work and it's common to use them.
$setViewValue(value: any, trigger?: string): void;
$setPristine(): void;
$setDirty(): void;
$validate(): void;
$setTouched(): void;
$setUntouched(): void;
@@ -539,9 +540,29 @@ declare module angular {
$applyAsync(exp: string): any;
$applyAsync(exp: (scope: IScope) => any): any;
/**
* Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners.
*
* The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled.
*
* Any exception emitted from the listeners will be passed onto the $exceptionHandler service.
*
* @param name Event name to broadcast.
* @param args Optional one or more arguments which will be passed onto the event listeners.
*/
$broadcast(name: string, ...args: any[]): IAngularEvent;
$destroy(): void;
$digest(): void;
/**
* Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners.
*
* The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.
*
* Any exception emitted from the listeners will be passed onto the $exceptionHandler service.
*
* @param name Event name to emit.
* @param args Optional one or more arguments which will be passed onto the event listeners.
*/
$emit(name: string, ...args: any[]): IAngularEvent;
$eval(): any;
@@ -716,17 +737,37 @@ declare module angular {
eventFn(element: Node, doneFn: () => void): Function;
}
///////////////////////////////////////////////////////////////////////////
// FilterService
// see http://docs.angularjs.org/api/ng.$filter
// see http://docs.angularjs.org/api/ng.$filterProvider
///////////////////////////////////////////////////////////////////////////
/**
* $filter - $filterProvider - service in module ng
*
* Filters are used for formatting data displayed to the user.
*
* see https://docs.angularjs.org/api/ng/service/$filter
*/
interface IFilterService {
/**
* Usage:
* $filter(name);
*
* @param name Name of the filter function to retrieve
*/
(name: string): Function;
}
/**
* $filterProvider - $filter - provider in module ng
*
* Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To achieve this a filter definition consists of a factory function which is annotated with dependencies and is responsible for creating a filter function.
*
* see https://docs.angularjs.org/api/ng/provider/$filterProvider
*/
interface IFilterProvider extends IServiceProvider {
register(name: string, filterFactory: Function): IServiceProvider;
/**
* register(name);
*
* @param name Name of the filter function, or an object map of filters where the keys are the filter names and the values are the filter factories. Note: Filter names must be valid angular Expressions identifiers, such as uppercase or orderBy. Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace your filters, then you can use capitalization (myappSubsectionFilterx) or underscores (myapp_subsection_filterx).
*/
register(name: string | {}): IServiceProvider;
}
///////////////////////////////////////////////////////////////////////////
@@ -1012,37 +1053,98 @@ declare module angular {
disableAutoScrolling(): void;
}
///////////////////////////////////////////////////////////////////////////
// CacheFactoryService
// see http://docs.angularjs.org/api/ng.$cacheFactory
///////////////////////////////////////////////////////////////////////////
/**
* $cacheFactory - service in module ng
*
* Factory that constructs Cache objects and gives access to them.
*
* see https://docs.angularjs.org/api/ng/service/$cacheFactory
*/
interface ICacheFactoryService {
// Lets not foce the optionsMap to have the capacity member. Even though
// it's the ONLY option considered by the implementation today, a consumer
// might find it useful to associate some other options to the cache object.
//(cacheId: string, optionsMap?: { capacity: number; }): CacheObject;
(cacheId: string, optionsMap?: { capacity: number; }): ICacheObject;
/**
* Factory that constructs Cache objects and gives access to them.
*
* @param cacheId Name or id of the newly created cache.
* @param optionsMap Options object that specifies the cache behavior. Properties:
*
* capacity — turns the cache into LRU cache.
*/
(cacheId: string, optionsMap?: { capacity?: number; }): ICacheObject;
// Methods bellow are not documented
/**
* Get information about all the caches that have been created.
* @returns key-value map of cacheId to the result of calling cache#info
*/
info(): any;
/**
* Get access to a cache object by the cacheId used when it was created.
*
* @param cacheId Name or id of a cache to access.
*/
get(cacheId: string): ICacheObject;
}
/**
* $cacheFactory.Cache - type in module ng
*
* A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data.
*
* see https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache
*/
interface ICacheObject {
/**
* Retrieve information regarding a particular Cache.
*/
info(): {
/**
* the id of the cache instance
*/
id: string;
/**
* the number of entries kept in the cache instance
*/
size: number;
// Not garanteed to have, since it's a non-mandatory option
//capacity: number;
//...: any additional properties from the options object when creating the cache.
};
/**
* Inserts a named entry into the Cache object to be retrieved later, and incrementing the size of the cache if the key was not already present in the cache. If behaving like an LRU cache, it will also remove stale entries from the set.
*
* It will not insert undefined values into the cache.
*
* @param key the key under which the cached data is stored.
* @param value the value to store alongside the key. If it is undefined, the key will not be stored.
*/
put<T>(key: string, value?: T): T;
/**
* Retrieves named data stored in the Cache object.
*
* @param key the key of the data to be retrieved
*/
get(key: string): any;
/**
* Removes an entry from the Cache object.
*
* @param key the key of the entry to be removed
*/
remove(key: string): void;
/**
* Clears the cache object of any entries.
*/
removeAll(): void;
/**
* Destroys the Cache object entirely, removing it from the $cacheFactory set.
*/
destroy(): void;
}
///////////////////////////////////////////////////////////////////////////
// CompileService
// see http://docs.angularjs.org/api/ng.$compile
@@ -0,0 +1,9 @@
/// <reference path="autoprefixer-core.d.ts" />
import autoprefixer = require("autoprefixer-core");
var css: string;
var prefixed = autoprefixer.process(css).css;
var processor = autoprefixer({ browsers: ['> 1%', 'IE 7'], cascade: false });
console.log(processor.info());
+44
View File
@@ -0,0 +1,44 @@
// Type definitions for Autoprefixer Core 5.1.11
// Project: https://github.com/postcss/autoprefixer-core
// Definitions by: Asana <https://asana.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "autoprefixer-core" {
interface Config {
browsers?: string[];
cascade?: boolean;
remove?: boolean;
}
interface Options {
from?: string;
to?: string;
safe?: boolean;
map?: {
inline?: boolean;
prev?: string | Object;
}
}
interface Result {
css: string;
map: string;
opts: Options;
}
interface Processor {
postcss: any;
info(): string;
process(css: string, opts?: Options): Result;
}
interface Exports {
(config: Config): Processor;
postcss: any;
info(): string;
process(css: string, opts?: Options): Result;
}
var exports: Exports;
export = exports;
}
+1 -3
View File
@@ -169,9 +169,7 @@ declare module Backbone {
**/
private static extend(properties: any, classProperties?: any): any;
// TODO: this really has to be typeof TModel
//model: typeof TModel;
model: { new(): TModel; }; // workaround
model: new (...args:any[]) => TModel;
models: TModel[];
length: number;
+87 -46
View File
@@ -8,12 +8,12 @@
declare module Backgrid {
interface GridOptions {
columns: Column[];
collection: Backbone.Collection<Backbone.Model>;
header: Header;
body: Body;
row: Row;
footer: Footer;
columns: Column[];
collection: Backbone.Collection<Backbone.Model>;
header: Header;
body: Body;
row: Row;
footer: Footer;
}
class Header extends Backbone.View<Backbone.Model> {
@@ -21,65 +21,106 @@ declare module Backgrid {
class Footer extends Backbone.View<Backbone.Model> {
}
class Row extends Backbone.View<Backbone.Model> {
}
class Command {
cancel();
moveDown();
moveLeft();
moveRight();
moveUp();
passThru();
save();
moveUp(): boolean;
moveDown(): boolean;
moveLeft(): boolean;
moveRight(): boolean;
save(): boolean;
cancel(): boolean;
passThru(): boolean;
}
class CellFormatter {
fromRaw(rawData: any, model: Backbone.Model);
toRaw(formattedData: any, model: Backbone.Model);
}
class NumberFormatter extends CellFormatter {}
class PercentFormatter extends NumberFormatter {}
class DateTimeFormatter extends CellFormatter {}
class StringFormatter extends CellFormatter {}
class EmailFormatter extends CellFormatter {}
class SelectFormatter extends CellFormatter {}
class CellEditor extends Backbone.View<Backbone.Model>{
initialize(options?: any);
postRender(model: Backbone.Model, column: Backbone.Model);
}
class InputCellEditor extends CellEditor {
render();
saveOrCancel(event: any);
}
class Cell extends Backbone.View<Backbone.Model>{
tagName: string;
formatter: CellFormatter;
editor: InputCellEditor;
enterEditMode();
renderError();
exitEditMode();
remove();
}
class StringCell extends Cell {
}
interface ColumnAttr {
name: string;
cell: string;
headerCell: string;
label: string;
sortable: boolean;
editable: boolean;
renderable: boolean;
formater: string;
name: string;
cell: string;
headerCell: string;
label: string;
sortable: boolean;
editable: boolean;
renderable: boolean;
formater: string;
}
class Column extends Backbone.Model {
initialize(options?: any);
initialize(options?: any);
}
class Body extends Backbone.View<Backbone.Model> {
tagName: string;
tagName: string;
initialize(options?: any);
insertRow(model: Backbone.Model, collection: Backbone.Collection<Backbone.Model>, options: any);
moveToNextCell(model: Backbone.Model, cell: Column, command: Command);
refresh(): Body;
remove(): Body;
removeRow(model: Backbone.Model, collection: Backbone.Collection<Backbone.Model>, options: any);
render(): Body;
initialize(options?: any);
insertRow(model: Backbone.Model, collection: Backbone.Collection<Backbone.Model>, options: any);
moveToNextCell(model: Backbone.Model, cell: Column, command: Command);
refresh(): Body;
remove(): Body;
removeRow(model: Backbone.Model, collection: Backbone.Collection<Backbone.Model>, options: any);
render(): Body;
}
class Grid extends Backbone.View<Backbone.Model> {
body: Backgrid.Body;
className: string;
footer: any;
header: any;
tagName: string;
body: Backgrid.Body;
className: string;
footer: any;
header: any;
tagName: string;
initialize(options: any);
getSelectedModels(): Backbone.Model[];
insertColumn(...options: any[]): Grid;
insertRow(model: Backbone.Model, collection: Backbone.Collection<Backbone.Model>, options: any);
remove():Grid;
removeColumn(...options: any[]): Grid;
removeRow(model: Backbone.Model, collection: Backbone.Collection<Backbone.Model>, options: any);
render():Grid;
initialize(options: any);
getSelectedModels(): Backbone.Model[];
insertColumn(...options: any[]): Grid;
insertRow(model: Backbone.Model, collection: Backbone.Collection<Backbone.Model>, options: any);
remove(): Grid;
removeColumn(...options: any[]): Grid;
removeRow(model: Backbone.Model, collection: Backbone.Collection<Backbone.Model>, options: any);
render(): Grid;
}
}
declare module "backgrid" {
export = Backgrid;
}
+322
View File
@@ -0,0 +1,322 @@
/// <reference path="blocks.d.ts" />
function test_blocks_methods() {
var extended: Object;
blocks.extend(extended, new Object());
blocks.each([3, 1, 4], function(value, index, collection) {
// value is the current item (3, 1 and 4)
// index is the current index (0, 1 and 2)
// collection points to the array passed to the function - [3, 1, 4]
});
blocks.eachRight([3, 1, 4], function(value, index, collection) {
// value is the current item (4, 1 and 3)
// index is the current index (2, 1 and 0)
// collection points to the array passed to the function - [3, 1, 4]
});
blocks.isArray([1, 2, 3]);
// -> true
function calculate() {
blocks.isArray(arguments);
// -> false
}
function max(collection: any, callback: any) {
callback = callback || blocks.noop;
}
blocks.type('a string');
// -> string
blocks.type(314);
// -> number
blocks.type([]);
// -> array
blocks.type({});
// -> object
blocks.type(blocks.noop);
// -> function
blocks.type(new RegExp(''));
// -> regexp
blocks.type(undefined);
// -> undefined
blocks.type(null);
// -> null
blocks.is([], 'array');
// -> true
blocks.is(function() { }, 'object');
// -> false
blocks.has({
price: undefined
}, 'price');
// -> true
blocks.has({
price: 314
}, 'ratio');
// -> false
blocks.unwrap(blocks.observable(314));
// -> 314
blocks.unwrap(blocks([3, 1, 4]));
// -> [3, 1, 4]
blocks.unwrap('a string or any other value will not be changed');
// -> 'a string or any other value will not be changed'
blocks.toArray(3);
// -> [3]
blocks.toArray([3, 1, 4]);
// -> [3, 1, 4]
blocks.toUnit(230);
// -> 230px
blocks.toUnit(230, '%');
// -> 230%
blocks.toUnit('60px', '%');
// -> 60%
var array = [3, 1, 4];
var cloned = blocks.clone(array);
// -> [3, 1, 4]
var areEqual = array == cloned;
// -> false
blocks.isElement(document.body);
// -> true
blocks.isElement({});
// -> false
blocks.isBoolean(true);
// -> true
blocks.isBoolean(new Boolean(false));
// -> true
blocks.isBoolean(1);
// -> false
blocks.isPlainObject({ property: true });
// -> true
blocks.isPlainObject(new Object());
// -> true
var car = new Object();
blocks.isPlainObject(car);
// -> false
var alert = blocks.bind(() => {
alert(this);
}, 'Hello bind method!');
alert();
// -> alerts 'Hello bind method'
var alertAll = blocks.bind((firstName: string, lastName: string) => {
alert('My name is ' + firstName + ' ' + lastName);
}, null, 'John', 'Doe');
alertAll();
// -> alerts 'My name is John Doe'
blocks.equals([3, 4], [3, 4]);
// -> true
blocks.equals({ value: 7 }, { value: 7, result: 1 });
// -> false
blocks.query({
message: 'Hello World!'
});
blocks.query({
items: ['John', 'Alf', 'Mega'],
alertIndex: (e: any) => {
alert('Clicked an item with index:' + blocks.context(e.target).$index);
}
});
blocks.query({
items: [1, 2, 3],
alertValue: (e: any) => {
alert('Clicked the value: ' + blocks.dataItem(e.target));
}
});
blocks.isObservable(blocks.observable(3));
// -> true
blocks.isObservable(3);
// -> false
blocks.unwrapObservable(blocks.observable(304));
// -> 304
blocks.unwrapObservable(305);
// -> 305
}
function test_observable_array() {
// creates an observable array with [1, 2, 3] as values
var items = blocks.observable([1, 2, 3]);
// removes the previous values and fills the observable array with [5, 6, 7] values
items.reset([5, 6, 7])
// results in observable array with [1, 2, 3, 4] values
items.add(4);
// results in observable array with [1, 2, 3, 4, 5, 6] values
items.addMany([4, 5, 6]);
var items = blocks.observable([4, 2, 3, 1]);
// results in observable array with [1, 2, 3, 4] values
items.swap(0, 3);
var items = blocks.observable([1, 4, 2, 3, 5]);
// results in observable array with [1, 2, 3, 4, 5] values
items.move(1, 4);
}
function test_Property() {
var App = blocks.Application();
var User = App.Model({
username: App.Property({
defaultValue: 'John Doe'
})
});
}
function test_Model() {
var App = blocks.Application();
var User = App.Model({
firstName: App.Property({
required: true,
validateOnChange: true
}),
lastName: App.Property({
required: true,
validateOnChange: true
}),
fullName: App.Property({
value: function() {
return this.firstName() + ' ' + this.lastName();
}
})
});
App.View('Profile', {
user: User({
firstName: 'John',
lastName: 'Doe'
})
});
}
function test_Collection() {
var App = blocks.Application();
var User = App.Model({
firstName: App.Property({
required: true,
validateOnChange: true
}),
lastName: App.Property({
required: true,
validateOnChange: true
}),
fullName: App.Property({
value: function() {
return this.firstName() + ' ' + this.lastName();
}
})
});
var Users = App.Collection(User, {
count: App.Property({
value: () => {
return this().length;
}
})
});
App.View('Profiles', {
users: Users([{
firstName: 'John',
lastName: 'Doe'
}, {
firstName: 'Johna',
lastName: 'Doa'
}])
});
}
function test_View() {
var App = blocks.Application();
App.View('Clicker', {
handleClick: () => {
alert('Clicky! Click!');
}
});
App.View('Statistics', {
init: () => {
this.loadRemoteData();
},
loadRemoteData: () => {
// ...stuff...
}
});
App.View('ContactUs', {
options: {
route: 'contactus'
},
routed: () => {
alert('Navigated to ContactUs page!')
}
});
App.View('ContactUs', {
options: {
route: 'contactus'
}
});
App.View('Navigation', {
navigateToContactUs: () => {
this.route('contactus')
}
});
}
+731
View File
@@ -0,0 +1,731 @@
// Type definitions for jsblocks v0.3.0
// Project: http://jsblocks.com/
// Definitions by: Krzysztof Śmigiel <https://github.com/ksmigiel>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/////////////////////////////////////////
// blocks methods
/////////////////////////////////////////
interface BlocksStatic {
(obj: any): any;
/**
* Performs a query operation on the DOM. Executes all data-query attributes
* and renders the html result to the specified HTMLElement if not specified
* uses document.body by default.
*
* @param model The model that will be used to query the DOM.
*/
query(model: any): void;
/**
* @param model The model that will be used to query the DOM.
* @param element Optional element on which to execute the query.
*/
query(model: any, element: HTMLElement): void;
/**
* Copies properties from all provided objects into the first object parameter
*/
extend(obj: Object, ...objects: any[]): void;
/**
* Iterates over the collection
*
* @param collection The array or object to iterate over
* @param callback The callback that will be executed for each element in the collection
* @param thisArg Optional this context for the callback
*/
each(collection: any, callback: (value: any, index: any, collection: any) => void, thisArg?: any): void;
/**
* Iterates over the collection from end to start
*
* @param collection The array or object to iterate over
* @param callback The callback that will be executed for each element in the collection
* @param thisArg Optional this context for the callback
*/
eachRight(collection: any, callback: (value: any, index: any, collection: any) => void, thisArg?: any): void;
/**
* Determines if a value is an array.
* Returns false for array like objects (for example arguments object).
*
* @param value The value to check if it is an array
*/
isArray(value: any): boolean;
/**
* Represents a dummy empty function
*/
noop(): Function;
/**
* Determines the true type of an object.
* Returns the type of the value as a string.
*
* @param value The value for which to determine its type
*/
type(value: any): string;
/**
* Determines if a specific value is the specified type
*
* @param value The value
* @param type The type
*/
is(value: any, type: string): boolean;
/**
* Checks if a variable has the specified property. Uses hasOwnProperty internally
*
* @param obj The object to call hasOwnPrototype for
* @param key The key to check if exists in the object
*/
has(obj: any, key: string): boolean;
/**
* Unwraps a jsblocks value to its raw representation.
* Unwraps blocks.observable() and blocks() values
*
* @param value The value that will be unwrapped
*/
unwrap(value: any): any;
/**
* Converts a value to an array. Arguments object is converted to array and primitive values
* are wrapped in an array.
* Does nothing when value is already an array
*
* @param value The value to be converted to an array
*/
toArray(value: any): any[];
/**
* Converts an integer or string to a unit. If the value could not be parsed to a number it is not converted
*
* @param value The value to be converted to the specified unit
*/
toUnit(value: any): any;
/**
* @param value The value to be converted to the specified unit
* @param unit Optionally provide a unit to convert to. Default value is 'px'
*/
toUnit(value: any, unit: string): any;
/**
* Clones value. If deepClone is set to true the value will be cloned recursively
*
* @param value Value/object to be cloned
*/
clone(value: any): any;
/**
* @param value Value/object to be cloned
* @param deepClone By default false
*/
clone(value: any, deepClone: boolean): any;
/**
* Determines if the specified value is a HTML elements collection.
* Returns whether the value is elements collection.
*
* @param value The value to check if it is elements collection
*/
isElements(value: any): boolean;
/**
* Determines if the specified value is a HTML element.
* Returns whether the value is a HTML element.
*
* @param value The value to check if it is a HTML element
*/
isElement(value: any): boolean;
/**
* Determines if a the specified value is a boolean.
* Whether the value is a boolean or not.
*
* @param value The value to be checked if it is a boolean
*/
isBoolean(value: any): boolean;
/**
* Determines if the specified value is an object.
* Returns whether the value is an object.
*
* @param obj The value to check for if it is an object
*/
isObject(obj: any): boolean;
/**
* Determines if a value is a object created using {} or new Object.
* Whether the value is a plain object or not.
*
* @param obj The value that will be checked
*/
isPlainObject(obj: any): boolean;
/**
* Changes the this binding to a function and optionally passes additional parameters to the function.
* Returns the newly created function having the new this binding and optional arguments.
*
* @param func The function for which to change the this binding and optionally add arguments
* @param thisArg The new this binding context value
* @param args Optional arguments that will be passed to the function
*/
bind(func: Function, thisArg: any, ...args: any[]): Function;
/**
* Determines if two values are deeply equal. Set deepEqual to false to stop recusively equality checking
*
* @param a The first object to be campared
* @param b The second object to be compared
*/
equals(a: any, b: any): boolean;
/**
* @param a The first object to be campared
* @param b The second object to be compared
* @param deepEqual Determines if the equality check will recursively check all child properties
*/
equals(a: any, b: any, deepEqual: boolean): boolean;
/**
* Gets the context for a particular element. Searches all parents until it finds the context.
*
* @param element The element from which to search for a context
*
*/
context(element: any): any;
/**
* Gets the associated dataItem for a particlar element. Searches all parents until it finds the context
*
* @param element The element from which to search for a dataItem
*/
dataItem(element: any): any;
/**
* Determines if particular value is an blocks.observable
*
* @param value The value to check if the value is observable
*/
isObservable(value: any): boolean;
/**
* Gets the raw value of an observable or returns the value if the specified object is not an observable
*
* @param value The value that could be any object observable or not
*/
unwrapObservable(value: any): any;
route(route: string): BlocksStatic;
optional(param: string): BlocksStatic;
optional(param: string, defaultValue: any): BlocksStatic;
range(start: number, end: number): BlocksStatic;
/**
* Creates the server which will automatically handle server-side rendering.
*/
server(): { express(): any };
/**
* @param options Overrides default jsblocks options
*/
server(options: Server): { express(): any };
/**
* Make observable property. You can specify initial value in parentheses.
*/
observable(): BlocksObservable;
observable(value: any[]): BlocksArray;
observable(value: any): BlocksObservable;
/**
* Use blocks.Application and its MVC(Model-View-Collection) structure to create better architecture and maintainability for your application.
*/
Application(): App;
Application(options: { history: string }): App;
}
/////////////////////////////////////////
// blocks observable
/////////////////////////////////////////
interface BlocksObservable extends Extendable<BlocksObservable> {
(arg: any): BlocksObservable;
/**
* Updates all elements, expressions and dependencies where the observable is used
*/
update(): BlocksObservable;
/**
* If event in prototype is not defined use this function instead.
*
* @param event Name of the event to raise
* @param trigger Function to be called when event is fired
*/
on(event: string, trigger: Function): BlocksObservable;
}
/////////////////////////////////////////
// blocks array
/////////////////////////////////////////
interface BlocksArray extends BlocksObservable {
/**
* Updates all elements, expressions and dependencies where the observable is used
*/
update(): BlocksArray;
/**
* Extends the current observable with particular functionality depending on the parameters specified.
* If the method is called without arguments and jsvalue framework is included the observable will be
* extended with the methods available in jsvalue for the current type.
*
* @param options Optional options
*/
extend(...options: any[]): BlocksArray;
/**
* @param name Name of the extender
* @param options Optional options
*/
extend(name: string, ...options: any[]): BlocksArray;
/**
* Removes all items from the collection and replaces them with the new value provided.
* The value could be Array, observable array or jsvalue.Array
*
* @param value The new value that will be populated
*/
reset(value: any[]): BlocksArray;
/**
* Adds values to the end of the observable array
*
* @param value The values that will be added to the end of the array
*/
add(value: any): BlocksArray;
/**
* @param value The values that will be added to the end of the array
* @param index Optional index specifying where to insert the value
*/
add(value: any, index: number): BlocksArray;
/**
* Adds the values from the provided array(s) to the end of the collection
*
* @param value The array that will be added to the end of the array
*/
addMany(value: any[]): BlocksArray;
/**
* @param value The array that will be added to the end of the array
* @param index Optional position where the array of values to be inserted
*/
addMany(value: any[], index: number): BlocksArray;
/**
* Swaps two values in the observable array. Note: Faster than removing the items and adding them at the locations
*
* @param indexA The first index that points to the index in the array that will be swapped
* @param indexB The second index that points to the index in the array that will be swapped
*/
swap(indexA: number, indexB: number): BlocksArray;
/**
* Moves an item from one location to another in the array. Note: Faster than removing the item and adding it at the location
*
* @param sourceIndex The index pointing to the item that will be moved
* @param targetIndex The index where the item will be moved to
*/
move(sourceIndex: number, targetIndex: number): BlocksArray;
/**
* Removes an item from the observable array
*
* @param value The value that will be removed or a callback function which returns true or false to determine if the value should be removed
*/
remove(value: any): BlocksArray;
/**
* @param value The value that will be removed or a callback function which returns true or false to determine if the value should be removed
* @param thisArg Optional this context for the callback
*/
remove(value: any, thisArg: Function): BlocksArray;
/**
* Removes an item at the specified index
*
* @param index The index location of the item that will be removed
*/
removeAt(index: number): BlocksArray;
/**
* @param index The index location of the item that will be removed
* @param count Optional parameter that if specified will remove the next items starting from the specified index
*/
removeAt(index: number, count: number): BlocksArray;
/**
* Removes all items from the observable array and optionally filter which items to be removed by providing a callback
*/
removeAll(): BlocksArray;
/**
* @param callback Optional callback function which filters which items to be removed. Returning a truthy value will remove the item and vice versa
*/
removeAll(callback: Function): BlocksArray;
/**
* @param callback Optional callback function which filters which items to be removed. Returning a truthy value will remove the item and vice versa
* @param thisArg Optional this context for the callback function
*/
removeAll(callback: Function, thisArg: any): BlocksArray;
/**
* The concat() method is used to join two or more arrays
*
* @param arrays The arrays to be joined
*/
concat(...arrays: any[]): any[]
/**
* The slice() method returns the selected elements in an array, as a new array object
*
* @param start An integer that specifies where to start the selection (The first element has an index of 0)
*/
slice(start: number): any[];
/**
* @param start An integer that specifies where to start the selection (The first element has an index of 0)
* @param end An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected.
* Use negative numbers to select from the end of an array
*/
slice(start: number, end: number): any[];
/**
* The join() method joins the elements of an array into a string, and returns the string
*/
join(): string;
/**
* @param separator The separator to be used. If omitted, the elements are separated with a comma
*/
join(seperator: string): string;
/**
* The pop() method removes the last element of a observable array, and returns that element
*/
pop(): any;
/**
* The push() method adds new items to the end of the observable array, and returns the new length
*
* @param values The item(s) to add to the observable array
*/
push(...values: any[]): number;
/**
* Reverses the order of the elements in the observable array
*/
reverse(): any[];
/**
* Removes the first element of a observable array, and returns that element
*/
shift(): any
/**
* Sorts the elements of an array
*/
sort(): any[];
/**
* @param sortfunction A function that defines the sort order
*/
sort(sortfunction: Function): any[];
/**
* Adds and/or removes elements from the observable array
* Returns A new array containing the removed items, if any.
*
* @param index An integer that specifies at what position to add/remove items. Use negative values to specify the position from the end of the array.
* @param howMany The number of items to be removed. If set to 0, no items will be removed.
* @param items The new item(s) to be added to the array.
*/
splice(index: number, howMany: number, ...items: any[]): any[];
/**
* The unshift() method adds new items to the beginning of an array, and returns the new length.
*
* @param items
*/
unshift(...items: any[]): number;
}
/////////////////////////////////////////
// blocks MVC App
/////////////////////////////////////////
interface App extends Extendable<App> {
/**
* Creates an application property for a Model.
*/
Property(): any;
/**
* @param options Configuration options for property
*/
Property(options: PropertyPrototype): any;
/**
* Defines a view that will be part of the Application.
*
* @param name The name of the View you are creating
* @param prototype The object that will represent the View
*/
View(name: string, prototype: ViewPrototype): any;
/**
* Defines a view that will be part of the Application.
*
* @param parentViewName Provide this parameter only if you are creating nested views. This is the name of the parent View
* @param name The name of the View you are creating
* @param prototype The object that will represent the View
*/
View(parentViewName: string, name: string, prototype: ViewPrototype): any;
/**
* Creates a new Model
*
* @param prototype The Model object properties that will be created
*/
Model(prototype: ModelPrototype): Model;
/**
* Creates a new Collection
*
* @param prototype The Collection object properties that will be created.
*/
Collection(prototype: CollectionPrototype): Collection;
Collection(model: Model, prototype: CollectionPrototype): Collection;
}
/////////////////////////////////////////
// App.Property
/////////////////////////////////////////
interface PropertyPrototype {
defaultValue?: any;
isObservable?: boolean;
field?: string;
value?: any;
validateOnChange?: boolean;
maxErrors?: number;
validateInitially?: boolean
// Validators
required?: Validator;
minlength?: Validator;
maxlength?: Validator;
min?: Validator;
max?: Validator;
email?: Validator;
url?: Validator;
date?: Validator;
creditcard?: Validator;
regexp?: Validator;
number?: Validator;
digits?: Validator;
letters?: Validator;
equals?: Validator;
}
interface Validator { }
/////////////////////////////////////////
// App.View
/////////////////////////////////////////
interface ViewPrototype {
parentView?: any;
/**
* Routes to a specific URL and actives the appropriate views associated with the URL
*
* @param name Name of the route
*/
route?(name: string): ViewPrototype;
/**
* Determines if the view is visible
*/
isActive?(): boolean;
/**
* Override the init method to perform actions when the View is first created and shown on the page
*/
init?: Function;
/**
* Override the routed method to perform actions when the View have routing and routing mechanism actives it.
*/
routed?: Function;
navigateTo?: Function;
/**
* Override the ready method to perform actions when the DOM is ready and
* all data-query have been executed.
*/
ready?: Function;
options?: {
route?: any;
url?: string
};
}
/////////////////////////////////////////
// App.Model
/////////////////////////////////////////
interface Model {
(): Model;
(props: Object): Model;
/**
* Fires a request to the server to populate the Model based on the read URL specified
*/
read(): Model;
/**
* @param params The parameters Object that will be used to populate the Model from the specified options.read URL. If the URL does not contain parameters
*/
read(params: Object): Model;
/**
* Synchronizes the changes with the server by sending requests to the provided URL's
*/
sync(): Model;
}
interface ModelPrototype {
/**
* Override the init method to perform actions on creation for each Model instance
*/
init?: Function;
/**
* Validates all observable properties that have validation and returns true if all values are valid otherwise returns false
*/
validate?(): boolean;
/**
* Extracts the raw(non observable) dataItem object values from the Model
*/
dataItem?(): Object;
/**
* Applies new properties to the Model by providing an Object
*
* @param dataItem The object from which the new values will be applied
*/
reset?(dataItem: ModelPrototype): ModelPrototype;
/**
* Determines whether the instance is new. If true when syncing the item will send for insertion instead of updating it.
* The check is determined by the idAttr value specified in the options. If idAttr is not specified the item will always be considered new.
*
*/
isNew?(): boolean;
options?: {
idAttr?: string;
baseUrl?: string;
read?: { url?: string };
create?: { url?: string };
destroy?: { url?: string };
update?: { url?: string };
};
}
/////////////////////////////////////////
// App.Collection
/////////////////////////////////////////
interface Collection extends Extendable<Collection> {
(): Collection;
(props: Object[]): Collection;
/**
* Fires a request to the server to populate the Model based on the read URL specified
*/
read(): Collection;
/**
* @param params The parameters Object that will be used to populate the Collection from the specified options.read URL. If the URL does not contain parameters
*/
read(params: Object): Collection;
/**
* Clear all changes made to the collection
*/
clearChanges(): Collection;
/**
* Performs an ajax request for all create, update and delete operations in order to sync them with a database.
*/
sync(): Collection;
update(id: number, newValues: Object): Collection;
}
interface CollectionPrototype {
options?: {
read?: { url?: string };
create?: { url?: string };
destroy?: { url?: string };
update?: { url?: string };
};
}
interface Extendable<T> {
/**
* Extends the current observable with particular functionality depending on the parameters specified.
* If the method is called without arguments and jsvalue framework is included the observable will be
* extended with the methods available in jsvalue for the current type.
*
* @param name Name of the extender
* @param options Optional options
*/
extend(name?: string, ...options: any[]): T;
extend(arg: any): T;
}
interface Server {
/**
* The port at which your application will be run
*/
port?: number;
/**
* The folder where your application files like .html; .js and .css are going to be.
* The value is passed to express.static() middleware.
*/
static?: string;
/**
* Caches pages result instead of executing them each time.
* Disabling cache could impact performance.
*/
cache?: boolean;
/**
* Provide an express middleware function or an array of middleware functions.
* Use: [compression(); bodyParser()]
*/
use?: any;
}
declare var blocks: BlocksStatic;
declare module "blocks" {
export = blocks;
}
+120
View File
@@ -0,0 +1,120 @@
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="bootstrap-slider.d.ts" />
$(function() {
// examples from http://seiyria.github.io/bootstrap-slider/
$('#ex1').slider({
formatter: function(value) {
return 'Current value: ' + value;
}
});
$("#ex2").slider({});
var RGBChange = function() {
$('#RGB').css('background', 'rgb('+r.getValue()+','+g.getValue()+','+b.getValue()+')')
};
var r = $('#R').slider()
.on('slide', RGBChange)
.data('slider');
var g = $('#G').slider()
.on('slide', RGBChange)
.data('slider');
var b = $('#B').slider()
.on('slide', RGBChange)
.data('slider');
$("#ex4").slider({
reversed : true
});
$("#ex5").slider();
$("#destroyEx5Slider").click(function() {
$("#ex5").slider('destroy');
});
$("#ex6").slider();
$("#ex6").on("slide", function(slideEvt) {
$("#ex6SliderVal").text(<number>slideEvt.value);
});
$("#ex7").slider();
$("#ex7-enabled").click(function() {
if(this.checked) {
// With JQuery
$("#ex7").slider("enable");
}
else {
// With JQuery
$("#ex7").slider("disable");
}
});
$("#ex8").slider({
tooltip: 'always'
});
$("#ex9").slider({
precision: 2,
value: 8.115 // Slider will instantiate showing 8.12 due to specified precision
});
$("#ex11").slider({step: 20000, min: 0, max: 200000});
$("#ex12a").slider({ id: "slider12a", min: 0, max: 10, value: 5 });
$("#ex12b").slider({ id: "slider12b", min: 0, max: 10, range: true, value: [3, 7] });
$("#ex12c").slider({ id: "slider12c", min: 0, max: 10, range: true, value: [3, 7] });
$("#ex13").slider({
ticks: [0, 100, 200, 300, 400],
ticks_labels: ['$0', '$100', '$200', '$300', '$400'],
ticks_snap_bounds: 30
});
$("#ex14").slider({
ticks: [0, 100, 200, 300, 400],
ticks_positions: [0, 30, 60, 70, 90, 100],
ticks_labels: ['$0', '$100', '$200', '$300', '$400'],
ticks_snap_bounds: 30
});
$("#ex15").slider({
min: 1000,
max: 10000000,
scale: 'logarithmic',
step: 10
});
$("#ex16a").slider({ min: 0, max: 10, value: 0, focus: true });
$("#ex16b").slider({ min: 0, max: 10, value: [0, 10], focus: true });
});
+200
View File
@@ -0,0 +1,200 @@
// Type definitions for bootstrap-slider.js 4.8.3
// Project: https://github.com/seiyria/bootstrap-slider
// Definitions by: Daniel Beckwith <https://github.com/dbeckwith>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../jquery/jquery.d.ts"/>
interface SliderOptions {
/**
* Default: ''
* set the id of the slider element when it's created
*/
id?: string;
/**
* Default: 0
* minimum possible value
*/
min?: number;
/**
* Default: 10
* maximum possible value
*/
max?: number;
/**
* Default: 1
* increment step
*/
step?: number;
/**
* Default: number of digits after the decimal of step value
* The number of digits shown after the decimal. Defaults to the number of digits after the decimal of step value.
*/
precision?: number;
/**
* Default: 'horizontal'
* set the orientation. Accepts 'vertical' or 'horizontal'
*/
orientation?: number;
/**
* Default: 5
* initial value. Use array to have a range slider.
*/
value?: number|number[];
/**
* Default: false
* make range slider. Optional if initial value is an array. If initial value is scalar, max will be used for second value.
*/
range?: boolean;
/**
* Default: 'before'
* selection placement. Accepts: 'before', 'after' or 'none'. In case of a range slider, the selection will be placed between the handles
*/
selection?: string;
/**
* Default: 'show'
* whether to show the tooltip on drag, hide the tooltip, or always show the tooltip. Accepts: 'show', 'hide', or 'always'
*/
tooltip?: string;
/**
* Default: false
* if false show one tootip if true show two tooltips one for each handler
*/
tooltip_split?: boolean;
/**
* Default: 'round'
* handle shape. Accepts: 'round', 'square', 'triangle' or 'custom'
*/
handle?: string;
/**
* Default: false
* whether or not the slider should be reversed
*/
reversed?: boolean;
/**
* Default: true
* whether or not the slider is initially enabled
*/
enabled?: boolean;
/**
* Default: returns the plain value
* formatter callback. Return the value wanted to be displayed in the tooltip
* @param val the current value to display
*/
formatter?(val:number): string;
/**
* Default: false
* The natural order is used for the arrow keys. Arrow up select the upper slider value for vertical sliders, arrow right the righter slider value for a horizontal slider - no matter if the slider was reversed or not. By default the arrow keys are oriented by arrow up/right to the higher slider value, arrow down/left to the lower slider value.
*/
natural_arrow_keys?: boolean;
/**
* Default: [ ]
* Used to define the values of ticks. Tick marks are indicators to denote special values in the range. This option overwrites min and max options.
*/
ticks?: number[];
/**
* Default: [ ]
* Defines the positions of the tick values in percentages. The first value should alwasy be 0, the last value should always be 100 percent.
*/
ticks_positions?: number[];
/**
* Default: [ ]
* Defines the labels below the tick marks. Accepts HTML input.
*/
ticks_labels?: string[];
/**
* Default: 0
* Used to define the snap bounds of a tick. Snaps to the tick if value is within these bounds.
*/
ticks_snap_bounds?: number;
/**
* Default: 'linear'
* Set to 'logarithmic' to use a logarithmic scale.
*/
scale?: string;
/**
* Default: false
* Focus the appropriate slider handle after a value change.
*/
focus?: boolean;
}
interface JQuery {
/**
* Creates a slider from the current element.
* @param options
*/
slider(options?:SliderOptions): JQuery;
slider(methodName:string, ...args:any[]): JQuery;
}
interface ChangeValue {
oldValue: number;
newValue: number;
}
interface JQueryEventObject {
value: number|ChangeValue;
}
/**
* This class is actually not used when using the jQuery version of bootstrap-slider
* The method documentation is still here thouh.
* When using jQuery, slider methods like setValue(3, true) have to be called like $slider.slider('setValue', 3, true)
*/
interface Slider extends JQuery {
/**
* Get the current value from the slider
*/
getValue(): number;
/**
* Set a new value for the slider. If optional triggerSlideEvent parameter is true, 'slide' events will be triggered. If optional triggerChangeEvent parameter is true, 'change' events will be triggered.
* @param newValue
* @param triggerSlideEvent
* @param triggerChangeEvent
*/
setValue(newValue:number, triggerSlideEvent?:boolean, triggerChangeEvent?:boolean): void;
/**
* Properly clean up and remove the slider instance
*/
destroy(): void;
/**
* Disables the slider and prevents the user from changing the value
*/
disable(): void;
/**
* Enables the slider
*/
enable(): void;
/**
* Returns true if enabled, false if disabled
*/
isEnabled(): boolean;
/**
* Updates the slider's attributes
* @param attribute
* @param value
*/
setAttribute(attribute:string, value:any): void;
/**
* Get the slider's attributes
* @param attribute
*/
getAttribute(attribute:string): any;
/**
* Refreshes the current slider
*/
refresh(): void;
/**
* Renders the tooltip again, after initialization. Useful in situations when the slider and tooltip are initially hidden.
*/
relayout(): void;
on: {
(eventType:string, callback:(eventObject:JQueryEventObject, ...args:any[]) => any): Slider;
(eventType:string, data:any, callback:(eventObject:JQueryEventObject, ...args:any[]) => any): Slider;
(eventType:string, selector:string, callback:(eventObject:JQueryEventObject, ...eventData:any[]) => any): Slider;
(eventType:string, selector:string, data:any, callback:(eventObject:JQueryEventObject, ...eventData:any[]) => any): Slider;
(eventType:{ [key: string]: any; }, selector?:string, data?:any): Slider;
(eventType:{ [key: string]: any; }, data?:any): Slider;
}
}
+10
View File
@@ -70,3 +70,13 @@ evt.on("init", function () {
});
browserSync(config);
var bs = browserSync.create();
bs.init({
server: "./app"
});
bs.reload();
+102 -85
View File
@@ -3,96 +3,113 @@
// Definitions by: Asana <https://asana.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../chokidar/chokidar.d.ts"/>
/// <reference path="../node/node.d.ts" />
declare module "browser-sync" {
import chokidar = require("chokidar");
import fs = require("fs");
import http = require("http");
function BrowserSync(config?: BrowserSync.Options, callback?: (err: Error, bs: Object) => any): void;
module BrowserSync {
export function reload(): void;
export function reload(file: string): void;
export function reload(files: string[]): void;
export function reload(options: {stream: boolean}): NodeJS.ReadWriteStream;
export function notify(message: string, timeout?: number): void;
export function exit(): void;
export var active: boolean;
export var emitter: NodeJS.EventEmitter;
interface Options {
files?: string | string[];
watchOptions?: GazeOptions;
server?: ServerOptions;
proxy?: string | boolean;
port?: number;
https?: boolean;
ghostMode?: GhostOptions | boolean;
logLevel?: string;
logPrefix?: string;
logConnections?: boolean;
logFileChanges?: boolean;
logSnippet?: boolean;
snippetOptions?: SnippetOptions;
tunnel?: string | boolean;
online?: boolean;
open?: string | boolean;
browser?: string | string[];
xip?: boolean;
notify?: boolean;
scrollProportionally?: boolean;
scrollThrottle?: number;
reloadDelay?: number;
injectChanges?: boolean;
startPath?: string;
minify?: boolean;
host?: string;
codeSync?: boolean;
timestamps?: boolean;
scriptPath?: (path: string) => string;
socket?: SocketOptions;
}
interface GazeOptions {
interval?: number;
debounceDelay?: number;
mode?: string;
cwd?: string;
}
interface ServerOptions {
baseDir?: string | string[];
directory?: boolean;
index?: string;
routes?: {[path: string]: string};
middleware?: MiddlewareHandler[];
}
interface MiddlewareHandler {
(req: http.ServerRequest, res: http.ServerResponse, next: Function): any;
}
interface GhostOptions {
clicks?: boolean;
scroll?: boolean;
forms?: boolean;
}
interface SnippetOptions {
ignorePaths?: string;
rule?: {match?: RegExp; fn?: (snippet: string, match: string) => any};
}
interface SocketOptions {
path?: string;
clientPath?: string;
namespace?: string;
}
interface Options {
files?: string | string[];
watchOptions?: GazeOptions;
server?: ServerOptions;
proxy?: string | boolean;
port?: number;
https?: boolean;
ghostMode?: GhostOptions | boolean;
logLevel?: string;
logPrefix?: string;
logConnections?: boolean;
logFileChanges?: boolean;
logSnippet?: boolean;
snippetOptions?: SnippetOptions;
rewriteRules?: boolean | RewriteRules[];
tunnel?: string | boolean;
online?: boolean;
open?: string | boolean;
browser?: string | string[];
xip?: boolean;
notify?: boolean;
scrollProportionally?: boolean;
scrollThrottle?: number;
reloadDelay?: number;
reloadDebounce?: number;
plugins?: any[];
injectChanges?: boolean;
startPath?: string;
minify?: boolean;
host?: string;
codeSync?: boolean;
timestamps?: boolean;
scriptPath?: (path: string) => string;
socket?: SocketOptions;
}
export = BrowserSync;
interface GazeOptions {
interval?: number;
debounceDelay?: number;
mode?: string;
cwd?: string;
}
interface ServerOptions {
baseDir?: string | string[];
directory?: boolean;
index?: string;
routes?: {[path: string]: string};
middleware?: MiddlewareHandler[];
}
interface MiddlewareHandler {
(req: http.ServerRequest, res: http.ServerResponse, next: Function): any;
}
interface GhostOptions {
clicks?: boolean;
scroll?: boolean;
forms?: boolean;
}
interface SnippetOptions {
ignorePaths?: string;
rule?: {match?: RegExp; fn?: (snippet: string, match: string) => any};
}
interface SocketOptions {
path?: string;
clientPath?: string;
namespace?: string;
}
interface RewriteRules {
match: RegExp;
fn: (match: string) => string;
}
interface BrowserSync {
init(config?: Options, callback?: (err: Error, bs: Object) => any): void;
reload(): void;
reload(file: string): void;
reload(files: string[]): void;
reload(options: {stream: boolean}): NodeJS.ReadWriteStream;
notify(message: string, timeout?: number): void;
exit(): void;
watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any): NodeJS.EventEmitter;
pause(): void;
resume(): void;
emitter: NodeJS.EventEmitter;
active: boolean;
paused: boolean;
}
interface Exports extends BrowserSync {
create(): BrowserSync;
(config?: Options, callback?: (err: Error, bs: Object) => any): void;
}
var browserSync: Exports;
export = browserSync;
}
@@ -9,6 +9,7 @@ chai.use(chaiAsPromised);
var promise: any;
chai.expect(promise).to.eventually.equal(3);
chai.expect(promise).to.become(3);
chai.expect(promise).to.be.fulfilled;
chai.expect(promise).to.be.rejected;
chai.expect(promise).to.be.rejectedWith(Error);
chai.expect(promise).to.notify(() => console.log('done'));
+1
View File
@@ -14,6 +14,7 @@ declare module Chai {
interface Assertion {
become(expected: any): Assertion;
fulfilled: Assertion;
rejected: Assertion;
rejectedWith(expected: any): Assertion;
notify(fn: Function): Assertion;
+62
View File
@@ -0,0 +1,62 @@
/// <reference path="chai-subset.d.ts" />
import chai = require('chai');
import chaiSubset = require('chai-subset');
chai.use(chaiSubset);
var expect = chai.expect;
var assert = chai.assert;
function test_containSubset() {
var obj: Object = {
a: 'b',
c: 'd',
e: {
foo: 'bar',
baz: {
qux: 'quux'
}
}
};
expect(obj).to.containSubset({
a: 'b',
e: {
baz: {
qux: 'quux'
}
}
});
obj.should.containSubset({ a: 'b' });
}
function test_notContainSubset() {
var obj: Object = {
a: 'b',
c: 'd',
e: {
foo: 'bar',
baz: {
qux: 'quux'
}
}
};
expect(obj).to.not.containSubset({ g: 'whatever' });
obj.should.not.containSubset({ g: 'whatever' });
}
function test_arrayContainSubset() {
var list: Array<Object> = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ];
expect(list).to.containSubset([{a:'a', b: 'b'}]);
list.should.containSubset([{a:'a', b: 'b'}]);
}
function test_arrayNotContainSubset() {
var list: Array<Object> = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ];
expect(list).not.to.containSubset([{a:'a', b: 'bd'}]);
list.should.not.containSubset([{a:'a', b: 'bd'}]);
}
+17
View File
@@ -0,0 +1,17 @@
// Type definitions for chai-subset 1.0.0
// Project: https://github.com/e-conomic/chai-subset
// Definitions by: Sam Noedel <https://github.com/delta62/>, Andrew Brown <https://github.com/AGBrown>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../chai/chai.d.ts" />
declare module Chai {
interface Assertion {
containSubset(obj: Object): Assertion;
}
}
declare module "chai-subset" {
function chaiSubset(chai: any, utils: any): void;
export = chaiSubset;
}
+346
View File
File diff suppressed because it is too large Load Diff
+26 -1
View File
@@ -1,12 +1,15 @@
// Type definitions for chai 2.0.0
// Project: http://chaijs.com/
// Definitions by: Jed Mao <https://github.com/jedmao/>, Bart van der Schoor <https://github.com/Bartvds>
// Definitions by: Jed Mao <https://github.com/jedmao/>,
// Bart van der Schoor <https://github.com/Bartvds>,
// Andrew Brown <https://github.com/AGBrown>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module Chai {
interface ChaiStatic {
expect: ExpectStatic;
should(): Should;
/**
* Provides a way to extend the internals of Chai
*/
@@ -25,6 +28,24 @@ declare module Chai {
(target: any, message?: string): Assertion;
}
interface ShouldAssertion {
equal(value1: any, value2: any, message?: string): void;
Throw: ShouldThrow;
throw: ShouldThrow;
exist(value: any, message?: string): void;
}
interface Should extends ShouldAssertion {
not: ShouldAssertion;
fail(actual: any, expected: any, message?: string, operator?: string): void;
}
interface ShouldThrow {
(actual: Function): void;
(actual: Function, expected: string|RegExp, message?: string): void;
(actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void;
}
interface Assertion extends LanguageChains, NumericComparison, TypeComparison {
not: Assertion;
deep: Deep;
@@ -281,3 +302,7 @@ declare var chai: Chai.ChaiStatic;
declare module "chai" {
export = chai;
}
interface Object {
should: Chai.Assertion;
}
+8
View File
@@ -28,6 +28,14 @@ var currentWindow: cwindow.AppWindow = chrome.app.window.current();
var otherWindow: cwindow.AppWindow = chrome.app.window.get('some-string');
var allWindows: cwindow.AppWindow[] = chrome.app.window.getAll();
// listening to window events
currentWindow.onBoundsChanged.addListener(function () { return; });
currentWindow.onClosed.addListener(function () { return; });
currentWindow.onFullscreened.addListener(function () { return; });
currentWindow.onMaximized.addListener(function () { return; });
currentWindow.onMinimized.addListener(function () { return; });
currentWindow.onRestored.addListener(function () { return; });
// check platform capabilities
var visibleEverywhere: boolean = chrome.app.window.canSetVisibleOnAllWorkspaces();
+6
View File
@@ -122,6 +122,12 @@ declare module chrome.app.window {
id: string;
innerBounds: Bounds;
outerBounds: Bounds;
onBoundsChanged: WindowEvent;
onClosed: WindowEvent;
onFullscreened: WindowEvent;
onMaximized: WindowEvent;
onMinimized: WindowEvent;
onRestored: WindowEvent;
}
export function create(url: string, options?: CreateWindowOptions, callback?: (created_window: AppWindow) => void): void;
Vendored
+36 -16
View File
@@ -304,7 +304,7 @@ declare module D3 {
* @param url Url to request
* @param callback Function to invoke when resource is loaded or the request fails
*/
(url: string, callback?: (xhr: XMLHttpRequest) => void ): Xhr;
(url: string, callback?: (error: any, xhr: XMLHttpRequest) => void ): Xhr;
/**
* Creates an asynchronous request for specified url
*
@@ -312,7 +312,7 @@ declare module D3 {
* @param mime MIME type to request
* @param callback Function to invoke when resource is loaded or the request fails
*/
(url: string, mime: string, callback?: (xhr: XMLHttpRequest) => void ): Xhr;
(url: string, mime: string, callback?: (error: any, xhr: XMLHttpRequest) => void ): Xhr;
};
/**
* Request a text file
@@ -324,7 +324,7 @@ declare module D3 {
* @param url Url to request
* @param callback Function to invoke when resource is loaded or the request fails
*/
(url: string, callback?: (response: string) => void ): Xhr;
(url: string, callback?: (error: any, responseText: string) => void ): Xhr;
/**
* Request a text file
*
@@ -332,7 +332,7 @@ declare module D3 {
* @param mime MIME type to request
* @param callback Function to invoke when resource is loaded or the request fails
*/
(url: string, mime: string, callback?: (response: string) => void ): Xhr;
(url: string, mime: string, callback?: (error: any, responseText: string) => void ): Xhr;
};
/**
* Request a JSON blob
@@ -351,7 +351,7 @@ declare module D3 {
* @param url Url to request
* @param callback Function to invoke when resource is loaded or the request fails
*/
(url: string, callback?: (response: Document) => void ): Xhr;
(url: string, callback?: (error: any, response: Document) => void ): Xhr;
/**
* Request an HTML document fragment.
*
@@ -359,7 +359,7 @@ declare module D3 {
* @param mime MIME type to request
* @param callback Function to invoke when resource is loaded or the request fails
*/
(url: string, mime: string, callback?: (response: Document) => void ): Xhr;
(url: string, mime: string, callback?: (error: any, response: Document) => void ): Xhr;
};
/**
* Request an XML document fragment.
@@ -367,7 +367,7 @@ declare module D3 {
* @param url Url to request
* @param callback Function to invoke when resource is loaded or the request fails
*/
html: (url: string, callback?: (response: DocumentFragment) => void ) => Xhr;
html: (url: string, callback?: (error: any, response: DocumentFragment) => void ) => Xhr;
/**
* Request a comma-separated values (CSV) file.
*/
@@ -654,7 +654,7 @@ declare module D3 {
*
* @param callback Function to invoke on completion of request
*/
get(callback?: (xhr: XMLHttpRequest) => void ): Xhr;
get(callback?: (error: any, xhr: XMLHttpRequest) => void ): Xhr;
/**
* Issue the request using the POST method
*/
@@ -664,14 +664,14 @@ declare module D3 {
*
* @param callback Function to invoke on completion of request
*/
(callback?: (xhr: XMLHttpRequest) => void ): Xhr;
(callback?: (error: any, xhr: XMLHttpRequest) => void ): Xhr;
/**
* Issue the request using the POST method
*
* @param data Data to post back in the request
* @param callback Function to invoke on completion of request
*/
(data: any, callback?: (xhr: XMLHttpRequest) => void ): Xhr;
(data: any, callback?: (error: any, xhr: XMLHttpRequest) => void ): Xhr;
};
/**
* Issues this request using the specified method
@@ -683,7 +683,7 @@ declare module D3 {
* @param method Method to use to make the request
* @param callback Function to invoke on completion of request
*/
(method: string, callback?: (xhr: XMLHttpRequest) => void ): Xhr;
(method: string, callback?: (eror: any, xhr: XMLHttpRequest) => void ): Xhr;
/**
* Issues this request using the specified method
*
@@ -691,7 +691,7 @@ declare module D3 {
* @param data Data to post back in the request
* @param callback Function to invoke on completion of request
*/
(method: string, data: any, callback?: (xhr: XMLHttpRequest) => void ): Xhr;
(method: string, data: any, callback?: (error: any, xhr: XMLHttpRequest) => void ): Xhr;
};
/**
* Aborts this request, if it is currently in-flight
@@ -787,8 +787,18 @@ declare module D3 {
(valueFunction: (data: T, index: number) => any): _Selection<T>;
};
append: (name: string) => _Selection<T>;
insert: (name: string, before: string) => _Selection<T>;
append: {
(name: string): _Selection<T>;
(elementFunction: (data: T, index: number) => any): _Selection<T>;
}
insert: {
(name: string, before: string): _Selection<T>;
(insertElementFunction: (data: T, index: number) => any, before: string): _Selection<T>;
(name: string, beforeElementFunction: (data: T, index: number) => any): _Selection<T>;
(insertElementFunction: (data: T, index: number) => any, beforeElementFunction: (data: T, index: number) => any): _Selection<T>;
}
remove: () => _Selection<T>;
empty: () => boolean;
@@ -874,8 +884,18 @@ declare module D3 {
export interface Selection extends _Selection<any> { }
export interface _EnterSelection<T> {
append: (name: string) => _Selection<T>;
insert: (name: string, before?: string) => _Selection<T>;
append: {
(name: string): _Selection<T>;
(elementFunction: (data: T, index: number) => any): _Selection<T>;
}
insert: {
(name: string, before?: string): _Selection<T>;
(insertElementFunction: (data: T, index: number) => any, before?: string): _Selection<T>;
(name: string, beforeElementFunction?: (data: T, index: number) => any): _Selection<T>;
(insertElementFunction: (data: T, index: number) => any, beforeElementFunction?: (data: T, index: number) => any): _Selection<T>;
}
select: (selector: string) => _Selection<T>;
empty: () => boolean;
node: () => Element;
+5 -5
View File
@@ -34291,7 +34291,7 @@ declare module dijit {
*
* @param id
*/
byId(id: String): any;
byId(id: String): dijit._WidgetBase;
/**
* A synthetic clone of array.every acting explicitly on this WidgetSet
*
@@ -105714,14 +105714,14 @@ declare module dijit {
*
* @param id
*/
byId(id: String): String;
byId(id: String): dijit._WidgetBase;
/**
* Find a widget by it's id.
* If passed a widget then just returns the widget.
*
* @param id
*/
byId(id: dijit._WidgetBase): String;
byId(id: dijit._WidgetBase): dijit._WidgetBase;
/**
* Returns the widget corresponding to the given DOMNode
*
@@ -105956,14 +105956,14 @@ declare module dijit {
*
* @param id
*/
byId(id: String): String;
byId(id: String): dijit._WidgetBase;
/**
* Find a widget by it's id.
* If passed a widget then just returns the widget.
*
* @param id
*/
byId(id: dijit._WidgetBase): String;
byId(id: dijit._WidgetBase): dijit._WidgetBase;
/**
* Returns the widget corresponding to the given DOMNode
*
+3 -3
View File
@@ -6,9 +6,9 @@ function testEach() {
return {
paused: true,
readable: false,
started: true,
done: true,
total: true,
started: 11,
done: 12,
total: 22,
on: function (eventName: string, cb: (a: any, b?: () => void) => void) {
return EachStaticClass([]);
},
+4 -4
View File
@@ -6,9 +6,9 @@
interface Each {
paused: boolean;
readable: boolean;
started: boolean;
done: boolean;
total: boolean;
started: number;
done: number;
total: number;
on(eventName: string, onCallback: Function): Each;
on(eventName: "item", onItem: (item: any, next: (error?: Error) => void) => void): Each;
on(eventName: "error", onError: (error: Error[]) => void): Each;
@@ -36,4 +36,4 @@ declare var each: EachStatic;
declare module "each" {
export = each;
}
}
+3 -3
View File
@@ -58,7 +58,7 @@ declare module EmberStates {
@arg {String} label optional string for labeling the promise. Useful for tooling.
@return {Promise}
*/
then(onFulfilled: Function, onRejected: Function, label?: string): Ember.RSVP.Promise;
then(onFulfilled: Function, onRejected?: Function, label?: string): Ember.RSVP.Promise;
/**
Forwards to the internal `promise` property which you can
@@ -2830,7 +2830,7 @@ declare module Ember {
function compare(v: any, w: any): number;
// ReSharper disable once DuplicatingLocalDeclaration
var computed: {
(callback: Function): ComputedProperty;
(...args: any[]): ComputedProperty;
alias(dependentKey: string): ComputedProperty;
and(...args: string[]): ComputedProperty;
any(...args: string[]): ComputedProperty;
@@ -2916,7 +2916,7 @@ declare module Ember {
**/
var none: typeof deprecateFunc;
function normalizeTuple(target: any, path: string): any[];
function observer(func: Function, ...args: string[]): Function;
function observer(...args: any[]): Function;
function observersFor(obj: any, path: string): any[];
function onLoad(name: string, callback: Function): void;
function oneWay(obj: any, to: string, from: string): Binding;
+5
View File
@@ -349,6 +349,11 @@ declare module "express" {
/**
* Parse the "Host" header field hostname.
*/
hostname: string;
/**
* @deprecated Use hostname instead.
*/
host: string;
/**
+954 -956
View File
File diff suppressed because it is too large Load Diff
+4590 -893
View File
File diff suppressed because it is too large Load Diff
+100
View File
@@ -0,0 +1,100 @@
/// <reference path="farbtastic.d.ts" />
var callback = () => {};
var domNode = document.createElement("div");
// Basic usage
// Can add a ready() handler to the document which initializes the color picker and links it to the text field
$(document).ready(function() {
$("#colorpicker").farbtastic("#color");
});
// Advanced Usage: jQuery Method
// Create color pickers in the selected objects
$("#colorpicker").farbtastic();
// Optional callback using a callback function
$("#colorpicker").farbtastic(callback);
$("#colourpicker").farbtastic(function (color) {
console.log(typeof color === "string");
});
// Optional callback using a DOM node
$("#colorpicker").farbtastic(domNode);
// Optional callback using a jQuery object
$("#colorpicker").farbtastic($("#color"));
// Optional callback using a jQuery selector
$("#colorpicker").farbtastic("#color");
// Advanced Usage: Object
// Can invoke method for returning Farbtastic object instead of a jQuery object
$.farbtastic(domNode);
$.farbtastic($("#color"));
$.farbtastic("#color");
// Optional callback using a callback function
$.farbtastic(domNode, callback);
$.farbtastic($("#color"), callback);
$.farbtastic("#color", callback);
// Optional callback using a DOM node
$.farbtastic(domNode, domNode);
$.farbtastic($("#color"), domNode);
$.farbtastic("#color", domNode);
// Optional callback using a jQuery object
$.farbtastic(domNode, $("#color"));
$.farbtastic($("#color"), $("#color"));
$.farbtastic("#color", $("#color"));
// Optional callback using a jQuery selector
$.farbtastic(domNode, "#color");
$.farbtastic($("#color"), "#color");
$.farbtastic("#color", "#color");
// Advanced Usage: Options
$("#colorpicker").farbtastic({
callback: (color) => {
console.log(color);
}
});
$.farbtastic(domNode, {
width: 500
});
$.farbtastic($("#color"), {
wheelWidth: 300
});
$.farbtastic("#color", {});
// Advanced Usage: Methods
$.farbtastic("#colorpicker").linkTo(callback);
$.farbtastic("#colorpicker").linkTo(domNode);
$.farbtastic("#colorpicker").linkTo("#color");
$.farbtastic("#colorpicker").linkTo($("#color"));
$.farbtastic("#colorpicker").setColor("#aabbcc");
$.farbtastic("#colorpicker").setColor([0.1, 0.2, 0.3]);
$.farbtastic("#colorpicker").setHSL([0.1, 0.2, 0.3]);
// Advanced Usage: Properties
$.farbtastic("#colorpicker").color === "#aabbcc";
$.farbtastic("#colorpicker").hsl === [0.1, 0.2, 0.3];
$.farbtastic("#colorpicker").linked === $("#colorpicker");
$.farbtastic("#colorpicker").linked === callback;
// Can chain jQuery methods
$("#colorpicker")
.farbtastic()
.addClass("color-picker");
// Can chain Farbtastic methods
$.farbtastic("#colorpicker")
.linkTo(domNode)
.setColor("#000000")
.setHSL([0, 0, 0]);
+40
View File
@@ -0,0 +1,40 @@
// Type definitions for Farbtastic: jQuery Color Wheel v2.0.0-alpha.1
// Project: http://mattfarina.github.io/farbtastic/
// Definitions by: Matt Brooks <https://github.com/EnableSoftware>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
declare module JQueryFarbtastic {
type Placeholder = string | Element | JQuery;
type CallbackFunction = (color: string) => any;
type Callback = CallbackFunction | Placeholder;
interface Options {
callback?: Callback;
width?: number;
wheelWidth?: number;
}
interface Farbtastic {
linked: CallbackFunction | JQuery;
color: string;
hsl: number[];
linkTo(callback: Callback): Farbtastic;
setColor(color: string | number[]): Farbtastic;
setHSL(hsl: number[]): Farbtastic;
}
}
interface JQueryStatic {
farbtastic(placeholder: JQueryFarbtastic.Placeholder, callback: JQueryFarbtastic.Callback): JQueryFarbtastic.Farbtastic;
farbtastic(placeholder: JQueryFarbtastic.Placeholder, options: JQueryFarbtastic.Options): JQueryFarbtastic.Farbtastic;
farbtastic(placeholder: JQueryFarbtastic.Placeholder): JQueryFarbtastic.Farbtastic;
}
interface JQuery {
farbtastic(callback: JQueryFarbtastic.Callback): JQuery;
farbtastic(options: JQueryFarbtastic.Options): JQuery;
farbtastic(): JQuery;
}
+39
View File
@@ -65,6 +65,45 @@ declare module gapi.auth {
* @param token The token to set.
*/
export function setToken(token: GoogleApiOAuth2TokenObject): void;
/**
* Initiates the client-side Google+ Sign-In OAuth 2.0 flow.
* When the method is called, the OAuth 2.0 authorization dialog is displayed to the user and when they accept, the callback function is called.
* @param params
*/
export function signIn(params: {
/**
* Your OAuth 2.0 client ID that you obtained from the Google Developers Console.
*/
clientid?: string;
/**
* Directs the sign-in button to store user and session information in a session cookie and HTML5 session storage on the user's client for the purpose of minimizing HTTP traffic and distinguishing between multiple Google accounts a user might be signed into.
*/
cookiepolicy?: string;
/**
* A function in the global namespace, which is called when the sign-in button is rendered and also called after a sign-in flow completes.
*/
callback?: Function;
/**
* If true, all previously granted scopes remain granted in each incremental request, for incremental authorization. The default value true is correct for most use cases; use false only if employing delegated auth, where you pass the bearer token to a less-trusted component with lower programmatic authority.
*/
includegrantedscopes?: boolean;
/**
* If your app will write moments, list the full URI of the types of moments that you intend to write.
*/
requestvisibleactions?: any;
/**
* The OAuth 2.0 scopes for the APIs that you would like to use as a space-delimited list.
*/
scope?: any;
/**
* If you have an Android app, you can drive automatic Android downloads from your web sign-in flow.
*/
apppackagename?: string;
}): void;
/**
* Signs a user out of your app without logging the user out of Google. This method will only work when the user is signed in with Google+ Sign-In.
*/
export function signOut(): void;
}
declare module gapi.client {
+107
View File
@@ -0,0 +1,107 @@
// Test file for Google Maps JavaScript API Definition file
/// <reference path="google.maps.d.ts" />
var map = new google.maps.Map(document.querySelector("☺"));
/***** Data *****/
new google.maps.Data();
new google.maps.Data({ map: map });
var latLng = new google.maps.LatLng(52.201203, -1.724370),
feature = new google.maps.Data.Feature(),
geometry = new google.maps.Data.Geometry();
var data = map.data;
data.add(feature);
data.add({
geometry: latLng,
id: "Test feature",
properties: {}
});
var isIn: boolean = map.data.contains(feature);
data.forEach((feature: google.maps.Data.Feature) => {
console.log(feature.getId());
});
var map: google.maps.Map = data.getMap();
data.setMap(map);
var style = data.getStyle();
data.setStyle(style);
data.setStyle({
clickable: true,
cursor: "pointer",
fillColor: "#79B55B",
fillOpacity: 1,
icon: {},
shape: { coords: [1, 2, 3], type: "circle" },
strokeColor: "#79B55B",
strokeOpacity: 1,
strokeWeight: 1,
title: "string",
visible: true,
zIndex: 1
});
data.overrideStyle(feature, { visible: true });
data.revertStyle(feature);
data.addGeoJson({});
data.addGeoJson({}, { idPropertyName: "Test feature" });
data.loadGeoJson("http://magicGeoJsonSource.com");
data.loadGeoJson(
"http://magicGeoJsonSource.com",
{ idPropertyName: "test" });
data.loadGeoJson(
"http://magicGeoJsonSource.com",
{ idPropertyName: "test" },
(features) => {
for (var i = 0, len = features.length; i < len; i++) {
console.log(features[i].getId());
}
});
data.toGeoJson((feature) => { });
var dataMouseEvent: google.maps.Data.MouseEvent = {
feature: feature,
latLng: latLng,
stop: (): void => {}
};
var addFeatureEvent : google.maps.Data.AddFeatureEvent = {
feature: feature
};
var removeFeatureEvent: google.maps.Data.RemoveFeatureEvent = {
feature: feature
};
var setGeometryEvent: google.maps.Data.SetGeometryEvent = {
feature: feature,
newGeometry: geometry,
oldGeometry: geometry,
};
var setPropertyEvent: google.maps.Data.SetPropertyEvent = {
feature: feature,
name: "test",
newValue: {},
oldValue: {}
};
var removePropertyEvent: google.maps.Data.RemovePropertyEvent = {
feature: feature,
name: "test",
oldValue: {}
};
+267 -67
View File
@@ -1,6 +1,6 @@
// Type definitions for Google Geolocation 0.4.8
// Type definitions for Google Maps JavaScript API 3.19
// Project: https://developers.google.com/maps/
// Definitions by: Folia A/S <http://www.folia.dk>
// Definitions by: Folia A/S <http://www.folia.dk>, Chris Wrench <https://github.com/cgwrench>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/*
@@ -80,9 +80,10 @@ declare module google.maps {
setStreetView(panorama: StreetViewPanorama): void;
setTilt(tilt: number): void;
setZoom(zoom: number): void;
controls: MVCArray[]; //Array.<MVCArray.<Node >>
controls: MVCArray[]; //Array<MVCArray.<Node >>
data: Data;
mapTypes: MapTypeRegistry;
overlayMapTypes: MVCArray; // MVCArray.<MapType>
overlayMapTypes: MVCArray; // MVCArray<MapType>
}
export interface MapOptions {
@@ -206,6 +207,159 @@ declare module google.maps {
ZOOM_PAN
}
/***** Data *****/
export class Data extends MVCObject {
constructor(options?: Data.DataOptions);
add(feature: Data.Feature|Data.FeatureOptions): Data.Feature;
addGeoJson(geoJson: Object, options?: Data.GeoJsonOptions): Data.Feature[];
contains(feature: Data.Feature): boolean;
forEach(callback: (feature: Data.Feature) => void): void;
getFeatureById(id: number|string): Data.Feature;
getMap(): Map;
getStyle(): Data.StylingFunction|Data.StyleOptions;
loadGeoJson(url: string, options?: Data.GeoJsonOptions, callback?: (features: Data.Feature[]) => void): void;
overrideStyle(feature: Data.Feature, style: Data.StyleOptions): void;
remove(feature: Data.Feature): void;
revertStyle(feature?: Data.Feature): void;
setMap(map: Map): void;
setStyle(style: Data.StylingFunction|Data.StyleOptions): void;
toGeoJson(callback: (feature: Object) => void): void;
}
export module Data {
export interface DataOptions {
map?: Map;
style?: Data.StylingFunction|Data.StyleOptions;
}
export interface GeoJsonOptions {
idPropertyName?: string;
}
export interface StyleOptions {
clickable?: boolean;
cursor?: string;
fillColor?: string;
fillOpacity?: number;
icon?: any; // TODO string|Icon|Symbol;
shape?: MarkerShape;
strokeColor?: string;
strokeOpacity?: number;
strokeWeight?: number;
title?: string;
visible?: boolean;
zIndex?: number;
}
export type StylingFunction = (feature: Data.Feature) => Data.StyleOptions;
export class Feature {
constructor(options?: Data.FeatureOptions);
forEachProperty(callback: (value: any, name: string) => void): void;
getGeometry(): Data.Geometry;
getId(): number|string;
getProperty(name: string): any;
removeProperty(name: string): void;
setGeometry(newGeometry: Data.Geometry|LatLng): void; // TODO LatLngLiteral
setProperty(name: string, newValue: any): void
toGeoJson(callback: (feature: Object) => void): void
}
export interface FeatureOptions {
geometry?: Data.Geometry|LatLng; // TODO LatLngLiteral
id?: number|string;
properties?: Object;
}
export class Geometry {
getType(): string;
}
export class Point extends Data.Geometry {
constructor(latLng: LatLng); // TODO LatLngLiteral
get(): LatLng;
}
export class MultiPoint extends Data.Geometry {
constructor(elements: LatLng[]); // TODO LatLngLiteral
getAt(n: number): LatLng;
getLength(): number;
}
export class LineString extends Data.Geometry {
constructor(elements: LatLng[]); // TODO LatLngLiteral
getArray(): LatLng[];
getAt(n: number): LatLng;
getLength(): number;
}
export class MultiLineString extends Data.Geometry {
constructor(elements: Data.LineString[]|LatLng[]); // TODO LatLngLiteral
getArray(): Data.LineString[];
getAt(n: number): Data.LineString;
getLength(): number;
}
export class LinearRing extends Data.Geometry {
constructor(elements: LatLng[]); // TODO LatLngLiteral
getArray(): LatLng[];
getAt(n: number): LatLng;
getLength(): number;
}
export class Polygon extends Data.Geometry {
constructor(elements: LinearRing[]|LatLng[][]); // TODO LatLngLiteral
getArray(): LinearRing[];
getAt(n: number): LinearRing;
getLength(): number;
}
export class MultiPolygon extends Data.Geometry {
constructor(elements: Data.Polygon[]|LinearRing[][]|LatLng[][][]); // TODO LatLngLiteral
getArray(): Data.Polygon[];
getAt(n: number): Data.Polygon;
getLength(): number;
}
export class GeometryCollection extends Data.Geometry {
constructor(elements: Data.Geometry[]|LatLng[]); // TODO LatLngLiteral
getArray(): Data.Geometry[];
getAt(n: number): Data.Geometry;
getLength(): number;
}
export interface MouseEvent extends google.maps.MouseEvent {
feature: Data.Feature;
}
export interface AddFeatureEvent {
feature: Data.Feature;
}
export interface RemoveFeatureEvent {
feature: Data.Feature;
}
export interface SetGeometryEvent {
feature: Data.Feature;
newGeometry: Data.Geometry;
oldGeometry: Data.Geometry;
}
export interface SetPropertyEvent {
feature: Data.Feature;
name: string;
newValue: any;
oldValue: any;
}
export interface RemovePropertyEvent {
feature: Data.Feature;
name: string;
oldValue: any;
}
}
/***** Overlays *****/
export class Marker extends MVCObject {
static MAX_ZINDEX: number;
@@ -470,7 +624,7 @@ declare module google.maps {
visible?: boolean;
zIndex?: number;
}
export enum StrokePosition {
CENTER,
INSIDE,
@@ -1345,54 +1499,54 @@ declare module google.maps {
}
export module places {
export class AutocompleteService extends MVCObject {
constructor();
getPlacePredictions(request: AutocompletionRequest, callback: (result: AutocompletePrediction[], status: PlacesServiceStatus) => void): void;
getQueryPredictions(request: QueryAutocompletionRequest, callback: (result: QueryAutocompletePrediction[], status: PlacesServiceStatus) => void): void;
}
export interface AutocompletionRequest {
input: string;
bounds?: LatLngBounds;
componentRestrictions?: ComponentRestrictions;
location?: LatLng;
offset?: number;
radius?: number;
types?: string[];
}
export interface QueryAutocompletionRequest {
input: string;
bounds?: LatLngBounds;
location?: LatLng;
offset?: number;
radius?: number;
}
export interface AutocompletePrediction {
description: string;
matched_substrings: PredictionSubstring[];
place_id: string;
terms: PredictionTerm[];
types: string[]
}
export interface PredictionTerm {
offset: number;
value: string;
}
export interface PredictionSubstring {
length: number;
offset: number;
}
export interface QueryAutocompletePrediction {
description: string;
matched_substrings: PredictionSubstring[];
place_id: string;
terms: PredictionTerm[];
export class AutocompleteService extends MVCObject {
constructor();
getPlacePredictions(request: AutocompletionRequest, callback: (result: AutocompletePrediction[], status: PlacesServiceStatus) => void): void;
getQueryPredictions(request: QueryAutocompletionRequest, callback: (result: QueryAutocompletePrediction[], status: PlacesServiceStatus) => void): void;
}
export interface AutocompletionRequest {
input: string;
bounds?: LatLngBounds;
componentRestrictions?: ComponentRestrictions;
location?: LatLng;
offset?: number;
radius?: number;
types?: string[];
}
export interface QueryAutocompletionRequest {
input: string;
bounds?: LatLngBounds;
location?: LatLng;
offset?: number;
radius?: number;
}
export interface AutocompletePrediction {
description: string;
matched_substrings: PredictionSubstring[];
place_id: string;
terms: PredictionTerm[];
types: string[]
}
export interface PredictionTerm {
offset: number;
value: string;
}
export interface PredictionSubstring {
length: number;
offset: number;
}
export interface QueryAutocompletePrediction {
description: string;
matched_substrings: PredictionSubstring[];
place_id: string;
terms: PredictionTerm[];
}
export class Autocomplete extends MVCObject {
@@ -1414,8 +1568,19 @@ declare module google.maps {
country: string;
}
export interface PhotoOptions {
maxHeight?: number;
maxWidth?: number;
}
export interface PlaceAspectRating {
rating: number;
type: string;
}
export interface PlaceDetailsRequest {
reference: string;
placeId: string;
reference?: string;
}
export interface PlaceGeometry {
@@ -1423,29 +1588,53 @@ declare module google.maps {
viewport: LatLngBounds;
}
export interface PlacePhoto {
height: number;
html_attributions: string[];
width: number;
getUrl(opts: PhotoOptions): string;
}
export interface PlaceResult {
address_components: GeocoderAddressComponent[];
aspects: PlaceAspectRating[];
formatted_address: string;
formatted_phone_number: string;
geometry: PlaceGeometry;
html_attributions: string[];
icon: string;
id: string;
id?: string;
international_phone_number: string;
name: string;
permanently_closed: boolean;
photos: PlacePhoto[];
place_id: string;
price_level: number;
rating: number;
reference: string;
reference?: string;
reviews: PlaceReview[];
types: string[];
url: string;
vicinity: string;
website: string;
}
export interface PlaceReview {
aspects: PlaceAspectRating[];
author_name: string;
author_url: string;
language: string;
text: string;
}
export interface PlaceSearchRequest {
bounds: LatLngBounds;
keyword: string;
location: LatLng;
maxPriceLevel?: number;
minPriceLevel?: number;
name: string;
openNow: boolean;
radius: number;
rankBy: RankBy;
types: string[];
@@ -1461,6 +1650,7 @@ declare module google.maps {
constructor (attrContainer: Map);
getDetails(request: PlaceDetailsRequest, callback: (result: PlaceResult, status: PlacesServiceStatus) => void ): void;
nearbySearch(request: PlaceSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus, pagination: PlaceSearchPagination) => void ): void;
radarSearch(request: RadarSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void ): void;
textSearch(request: TextSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void ): void;
}
@@ -1473,27 +1663,37 @@ declare module google.maps {
ZERO_RESULTS
}
export interface RadarSearchRequest {
bounds: LatLngBounds;
keyword: string;
location: LatLng;
name: string;
radius: number;
types: string[];
}
export enum RankBy {
DISTANCE,
PROMINENCE
}
export class SearchBox {
constructor(inputField: HTMLInputElement, opts?: SearchBoxOptions);
getBounds(): LatLngBounds;
setBounds(bounds: LatLngBounds): void;
getPlaces(): PlaceResult[];
}
export interface SearchBoxOptions {
bounds: LatLngBounds;
}
export class SearchBox extends MVCObject {
constructor(inputField: HTMLInputElement, opts?: SearchBoxOptions);
getBounds(): LatLngBounds;
setBounds(bounds: LatLngBounds): void;
getPlaces(): PlaceResult[];
}
export interface SearchBoxOptions {
bounds: LatLngBounds;
}
export interface TextSearchRequest {
bounds: LatLngBounds;
location: LatLng;
query: string;
radius: number;
types: string[];
}
}
@@ -1643,6 +1843,6 @@ declare module google.maps {
export class MapsEventListener {
}
}
}
}
+51
View File
@@ -0,0 +1,51 @@
// Type definitions for gulp-istanbul v0.8.1
// Project: https://github.com/SBoudrias/gulp-istanbul
// Definitions by: Asana <https://asana.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts"/>
declare module "gulp-istanbul" {
function GulpIstanbul(opts?: GulpIstanbul.Options): NodeJS.ReadWriteStream;
module GulpIstanbul {
export function hookRequire(): NodeJS.ReadWriteStream;
export function summarizeCoverage(opts?: {coverageVariable?: string}): Coverage;
export function writeReports(opts?: ReportOptions): NodeJS.ReadWriteStream;
interface Options {
coverageVariable?: string;
includeUntested?: boolean;
embedSource?: boolean;
preserveComments?: boolean;
noCompact?: boolean;
noAutoWrap?: boolean;
codeGenerationOptions?: Object;
debug?: boolean;
walkDebug?: boolean;
}
interface Coverage {
lines: CoverageStats;
statements: CoverageStats;
functions: CoverageStats;
branches: CoverageStats;
}
interface CoverageStats {
total: number;
covered: number;
skipped: number;
pct: number;
}
interface ReportOptions {
dir?: string;
reporters?: string[];
reportOpts?: {dir?: string};
coverageVariable?: string;
}
}
export = GulpIstanbul;
}
+13
View File
@@ -29,4 +29,17 @@ gulp.task('test', function (cb) {
.pipe(istanbul.writeReports({reporters: ['text']})) // Creating the reports after tests runned
.on('end', cb);
});
});
gulp.task('test', function (cb) {
gulp.src(['lib/**/*.js', 'main.js'])
.pipe(istanbul({includeUntested: true})) // Covering files
.pipe(istanbul.hookRequire())
.on('finish', function () {
gulp.src(['test/*.html'])
.pipe(testFramework())
.pipe(istanbul.writeReports({reporters: ['text']})) // Creating the reports after tests runned
.pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } })) //
.on('end', cb);
});
});
+15 -2
View File
@@ -1,4 +1,4 @@
// Type definitions for gulp-istanbul
// Type definitions for gulp-istanbul v0.9.0
// Project: https://github.com/SBoudrias/gulp-istanbul
// Definitions by: Asana <https://asana.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -12,6 +12,7 @@ declare module "gulp-istanbul" {
export function hookRequire(): NodeJS.ReadWriteStream;
export function summarizeCoverage(opts?: {coverageVariable?: string}): Coverage;
export function writeReports(opts?: ReportOptions): NodeJS.ReadWriteStream;
export function enforceThresholds(opts?: ThresholdOptions): NodeJS.ReadWriteStream;
interface Options {
coverageVariable?: string;
@@ -45,7 +46,19 @@ declare module "gulp-istanbul" {
reportOpts?: {dir?: string};
coverageVariable?: string;
}
interface ThresholdOptions {
coverageVariable?: string;
thresholds?: { global?: Coverage|number; each?: Coverage|number };
}
interface CoverageOptions {
lines?: number;
statements?: number;
functions?: number;
branches?: number;
}
}
export = GulpIstanbul;
}
}
+4 -4
View File
@@ -16,9 +16,9 @@ var interactable = interact(button);
interactable.draggable();
interactable.draggable(true);
interactable.draggable({
onstart: (event: InteractEvent) => {},
onmove : (event: InteractEvent) => {},
onend : (event: InteractEvent) => {}
onstart: (event: Interact.InteractEvent) => {},
onmove : (event: Interact.InteractEvent) => {},
onend : (event: Interact.InteractEvent) => {}
});
interactable.dropzone();
interactable.dropzone(true);
@@ -45,7 +45,7 @@ interactable.inertia({
});
interactable.inertia(true);
interactable.actionChecker();
interactable.actionChecker((event: MouseEvent, defaultAction: string, interactable2: Interactable) => defaultAction);
interactable.actionChecker((event: MouseEvent, defaultAction: string, interactable2: Interact.Interactable) => defaultAction);
var rect: ClientRect = interactable.getRect();
interactable.rectChecker();
interactable.styleCursor();
+234 -234
View File
@@ -1,245 +1,245 @@
// Type definitions for Interacting for interact.js v1.0.25
// Project: https://github.com/taye/interact.js
// Definitions by: Douglas Eichelberger <https://github.com/dduugg>, Adi Dahiya <https://github.com/adidahiya>
// Definitions by: Douglas Eichelberger <https://github.com/dduugg>, Adi Dahiya <https://github.com/adidahiya>, Tom Hasner <https://github.com/thasner>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// API documentation: http://interactjs.io/docs
interface Interactable {
// returns Element or string
accept(): any;
accept(newValue: Element): Interactable;
accept(newValue: string): Interactable;
actionChecker(): Function;
actionChecker(checker: Function): Interactable;
// returns boolean or {[key: string]: any}
autoScroll(): any;
autoScroll(options: boolean): Interactable;
autoScroll(options: {[key: string]: any}): Interactable;
context(): Node;
defaultActionChecker(event: any): string;
deltaSource(): string;
// returns Interactable if newValue is "page" or "client", otherwise returns string
deltaSource(newValue: String): Interactable;
draggable(): boolean;
draggable(options: boolean): Interactable;
draggable(options: {[key: string]: any}): Interactable;
dropCheck(event: MouseEvent): boolean;
dropCheck(event: TouchEvent): boolean;
dropChecker(): Function;
dropChecker(checker: Function): Interactable;
// returns boolean or {[key: string]: any}
dropzone(): any;
dropzone(options: boolean): Interactable;
dropzone(options: {[key: string]: any}): Interactable;
// return HTMLElement or SVGElement
element(): Element;
fire(iEvent: InteractEvent): Interactable;
// returns boolean or {[key: string]: any}
gesturable(): any;
gesturable(options: boolean): Interactable;
gesturable(options: {[key: string]: any}): Interactable;
getRect(): ClientRect;
// returns Element or string
ignoreFrom(): any;
ignoreFrom(newValue: string): Interactable;
ignoreFrom(newValue: Element): Interactable;
// returns boolean or {[key: string]: any}
inertia(): any;
inertia(options: boolean): Interactable;
inertia(options: {[key: string]: any}): Interactable;
off(eventType: string, listener: Function, useCapture?: boolean): Interactable;
on(eventType: string, listener: Function, useCapture?: boolean): Interactable;
origin(): Point;
origin(newValue: HTMLElement): Interactable;
origin(newValue: SVGElement): Interactable;
origin(newValue: Point): Interactable;
rectChecker(): Function;
rectChecker(newValue: Function): Interactable;
resizable(): Interactable;
resizable(options: boolean): Interactable;
resizable(options: {[key: string]: any}): Interactable;
restrict(): Restrict;
restrict(newValue: Restrict): Interactable;
set(options: {[key: string]: any}): Interactable;
// returns boolean or {[key: string]: any}
snap(): any;
snap(options: boolean): Interactable;
snap(options: {[key: string]: any}): Interactable;
squareResize(): boolean;
squareResize(newValue: boolean): Interactable;
styleCursor(): boolean;
styleCursor(newValue: boolean): Interactable;
unset(): InteractStatic;
validateSetting(context: string, option: string, value: any): any;
declare module Interact {
interface Interactable {
// returns Element or string
accept(): any;
accept(newValue: Element): Interactable;
accept(newValue: string): Interactable;
actionChecker(): Function;
actionChecker(checker: Function): Interactable;
// returns boolean or {[key: string]: any}
autoScroll(): any;
autoScroll(options: boolean): Interactable;
autoScroll(options: {[key: string]: any}): Interactable;
context(): Node;
defaultActionChecker(event: any): string;
deltaSource(): string;
// returns Interactable if newValue is "page" or "client", otherwise returns string
deltaSource(newValue: String): Interactable;
draggable(): boolean;
draggable(options: boolean): Interactable;
draggable(options: {[key: string]: any}): Interactable;
dropCheck(event: MouseEvent): boolean;
dropCheck(event: TouchEvent): boolean;
dropChecker(): Function;
dropChecker(checker: Function): Interactable;
// returns boolean or {[key: string]: any}
dropzone(): any;
dropzone(options: boolean): Interactable;
dropzone(options: {[key: string]: any}): Interactable;
// return HTMLElement or SVGElement
element(): Element;
fire(iEvent: InteractEvent): Interactable;
// returns boolean or {[key: string]: any}
gesturable(): any;
gesturable(options: boolean): Interactable;
gesturable(options: {[key: string]: any}): Interactable;
getRect(): ClientRect;
// returns Element or string
ignoreFrom(): any;
ignoreFrom(newValue: string): Interactable;
ignoreFrom(newValue: Element): Interactable;
// returns boolean or {[key: string]: any}
inertia(): any;
inertia(options: boolean): Interactable;
inertia(options: {[key: string]: any}): Interactable;
off(eventType: string, listener: Function, useCapture?: boolean): Interactable;
on(eventType: string, listener: Function, useCapture?: boolean): Interactable;
origin(): Point;
origin(newValue: HTMLElement): Interactable;
origin(newValue: SVGElement): Interactable;
origin(newValue: Point): Interactable;
rectChecker(): Function;
rectChecker(newValue: Function): Interactable;
resizable(): Interactable;
resizable(options: boolean): Interactable;
resizable(options: {[key: string]: any}): Interactable;
restrict(): Restrict;
restrict(newValue: Restrict): Interactable;
set(options: {[key: string]: any}): Interactable;
// returns boolean or {[key: string]: any}
snap(): any;
snap(options: boolean): Interactable;
snap(options: {[key: string]: any}): Interactable;
squareResize(): boolean;
squareResize(newValue: boolean): Interactable;
styleCursor(): boolean;
styleCursor(newValue: boolean): Interactable;
unset(): InteractStatic;
validateSetting(context: string, option: string, value: any): any;
}
interface Coordinates {
clientX: number;
clientY: number;
pageX: number;
pageY: number;
timeStamp: number;
}
interface Debug {
target: any;
dragging: any;
resizing: any;
gesturing: any;
prepared: any;
prevCoords: Coordinates;
downCoords: Coordinates;
pointerIds: any[];
pointerMoves: any[];
addPointer: any;
removePointer: any;
recordPointers: any;
inertia: InertiaStatus;
downTime: any;
downEvent: any;
prevEvent: any;
Interactable: any;
IOptions: any;
interactables: any;
dropzones: any;
pointerIsDown: any;
defaultOptions: any;
defaultActionChecker: any;
actions: any;
dragMove: any;
resizeMove: any;
gestureMove: any;
pointerUp: any;
pointerDown: any;
pointerMove: any;
pointerHover: any;
events: any;
globalEvents: any;
delegatedEvents: any;
}
interface InertiaStatus {
active: boolean;
target: any;
targetElement: any;
startEvent: any;
pointerUp: any
xe: number;
ye: number;
duration: number;
t0: number;
vx0: number;
vys: number;
lambda_v0: number;
one_ve_v0: number;
i: any;
}
interface Point {
x: number;
y: number;
}
// value types are either ClientRect or Element
interface Restrict {
drag?: any;
gesture?: any;
resize?: any;
elementRect?: {[direction: string]: number};
}
interface InteractEvent {
altKey: boolean;
axes: string;
button: number
clientX0: number;
clientX: number
clientY0: number;
clientY: number
ctrlKey: boolean
dt: number;
duration: number;
dx: number;
dy: number;
metaKey: boolean;
pageX: number;
pageY: number;
shiftKey: boolean;
speed: number;
t0: number;
target: any;
timeStamp: number;
type: string;
velocityX: number;
velocityY: number;
x0: number;
y0: number;
}
interface TouchEvent {
pageX: number;
pageY: number;
type: string;
}
interface InteractStatic {
(element: HTMLElement): Interactable;
(element: SVGElement): Interactable;
(element: string): Interactable;
// returns boolean or {[key: string]: any}
autoScroll(): any;
autoScroll(options: boolean): InteractStatic;
autoScroll(options: {[key: string]: any}): InteractStatic;
currentAction(): string
debug(): Debug;
deltaSource(): string;
// "page" and "client" are the valid parameters
deltaSource(newValue: string): InteractStatic;
dynamicDrop(): boolean;
dynamicDrop(newValue: boolean): InteractStatic;
enableDragging(): boolean;
enableDragging(newValue: boolean): InteractStatic;
enableGesturing(): boolean;
enableGesturing(newValue: boolean): InteractStatic;
enableResizing(): boolean;
enableResizing(newValue: boolean): InteractStatic;
// returns boolean or {[key: string]: any}
inertia(): any;
inertia(options: boolean): InteractStatic;
inertia(options: {[key: string]: any}): InteractStatic;
isSet(element: Element): boolean;
margin(): number;
margin(newvalue: number): InteractStatic;
off(type: string, listener: Function, useCapture?: boolean): InteractStatic;
on(type: string, listener: Function, useCapture?: boolean): InteractStatic;
restrict(): Restrict;
restrict(newValue: Restrict): InteractStatic;
simulate(action: string, element: Element, pointerEvent?: any): InteractStatic;
// returns boolean or {[key: string]: any}
snap(): any;
snap(options: boolean): InteractStatic;
snap(options: {[key: string]: any}): InteractStatic;
stop(event: Event): InteractStatic;
styleCursor(): boolean;
styleCursor(newValue: boolean): InteractStatic;
supportsTouch(): boolean
}
}
interface Coordinates {
clientX: number;
clientY: number;
pageX: number;
pageY: number;
timeStamp: number;
}
interface Debug {
target: any;
dragging: any;
resizing: any;
gesturing: any;
prepared: any;
prevCoords: Coordinates;
downCoords: Coordinates;
pointerIds: any[];
pointerMoves: any[];
addPointer: any;
removePointer: any;
recordPointers: any;
inertia: InertiaStatus;
downTime: any;
downEvent: any;
prevEvent: any;
Interactable: any;
IOptions: any;
interactables: any;
dropzones: any;
pointerIsDown: any;
defaultOptions: any;
defaultActionChecker: any;
actions: any;
dragMove: any;
resizeMove: any;
gestureMove: any;
pointerUp: any;
pointerDown: any;
pointerMove: any;
pointerHover: any;
events: any;
globalEvents: any;
delegatedEvents: any;
}
interface InertiaStatus {
active: boolean;
target: any;
targetElement: any;
startEvent: any;
pointerUp: any
xe: number;
ye: number;
duration: number;
t0: number;
vx0: number;
vys: number;
lambda_v0: number;
one_ve_v0: number;
i: any;
}
interface Point {
x: number;
y: number;
}
// value types are either ClientRect or Element
interface Restrict {
drag?: any;
gesture?: any;
resize?: any;
elementRect?: {[direction: string]: number};
}
interface InteractEvent {
altKey: boolean;
axes: string;
button: number
clientX0: number;
clientX: number
clientY0: number;
clientY: number
ctrlKey: boolean
dt: number;
duration: number;
dx: number;
dy: number;
metaKey: boolean;
pageX: number;
pageY: number;
shiftKey: boolean;
speed: number;
t0: number;
target: any;
timeStamp: number;
type: string;
velocityX: number;
velocityY: number;
x0: number;
y0: number;
}
interface TouchEvent {
changedTouches: any[];
pageX: number;
pageY: number;
touches: any[];
type: string;
}
interface InteractStatic {
(element: HTMLElement): Interactable;
(element: SVGElement): Interactable;
(element: string): Interactable;
// returns boolean or {[key: string]: any}
autoScroll(): any;
autoScroll(options: boolean): InteractStatic;
autoScroll(options: {[key: string]: any}): InteractStatic;
currentAction(): string
debug(): Debug;
deltaSource(): string;
// "page" and "client" are the valid parameters
deltaSource(newValue: string): InteractStatic;
dynamicDrop(): boolean;
dynamicDrop(newValue: boolean): InteractStatic;
enableDragging(): boolean;
enableDragging(newValue: boolean): InteractStatic;
enableGesturing(): boolean;
enableGesturing(newValue: boolean): InteractStatic;
enableResizing(): boolean;
enableResizing(newValue: boolean): InteractStatic;
// returns boolean or {[key: string]: any}
inertia(): any;
inertia(options: boolean): InteractStatic;
inertia(options: {[key: string]: any}): InteractStatic;
isSet(element: Element): boolean;
margin(): number;
margin(newvalue: number): InteractStatic;
off(type: string, listener: Function, useCapture?: boolean): InteractStatic;
on(type: string, listener: Function, useCapture?: boolean): InteractStatic;
restrict(): Restrict;
restrict(newValue: Restrict): InteractStatic;
simulate(action: string, element: Element, pointerEvent?: any): InteractStatic;
// returns boolean or {[key: string]: any}
snap(): any;
snap(options: boolean): InteractStatic;
snap(options: {[key: string]: any}): InteractStatic;
stop(event: Event): InteractStatic;
styleCursor(): boolean;
styleCursor(newValue: boolean): InteractStatic;
supportsTouch(): boolean
}
declare var interact: InteractStatic;
declare var interact: Interact.InteractStatic;
declare module "interact" {
export = interact;
+54
View File
@@ -0,0 +1,54 @@
/// <reference path="irc.d.ts" />
// https://github.com/martynsmith/node-irc/blob/master/example/bot.js
import irc = require('irc');
var bot = new irc.Client('irc.dollyfish.net.nz', 'nodebot', {
debug: true,
channels: ['#blah', '#test']
});
bot.addListener('error', <irc.handlers.IError> ((message: irc.IMessage) => {
console.error('ERROR: %s: %s', message.command, message.args.join(' '));
}));
bot.addListener('message#blah', <irc.handlers.IMessageChannel> ((from: string, message: string) => {
console.log('<%s> %s', from, message);
}));
bot.addListener('message', <irc.handlers.IRecievedMessage> ((from: string, to: string, message: string) => {
console.log('%s => %s: %s', from, to, message);
if (to.match(/^[#&]/)) {
// channel message
if (message.match(/hello/i)) {
bot.say(to, 'Hello there ' + from);
}
if (message.match(/dance/)) {
setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D\\-<\u0001'); }, 1000);
setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 2000);
setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D/-<\u0001'); }, 3000);
setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 4000);
}
}
else {
// private message
console.log('private message');
}
}));
bot.addListener('pm', <irc.handlers.IPm> ((nick: string, message: string) => {
console.log('Got private message from %s: %s', nick, message);
}));
bot.addListener('join', <irc.handlers.IJoin> ((channel: string, who: string) => {
console.log('%s has joined %s', who, channel);
}));
bot.addListener('part', <irc.handlers.IPart> ((channel: string, who: string, reason: string) => {
console.log('%s has left %s: %s', who, channel, reason);
}));
bot.addListener('kick', <irc.handlers.IKick> ((channel: string, who: string, by: string, reason: string) => {
console.log('%s was kicked from %s by %s: %s', who, channel, by, reason);
}));
+879
View File
@@ -0,0 +1,879 @@
// Type definitions for irc v0.3.12
// Project: https://github.com/martynsmith/node-irc
// Definitions by: phillips1012 <https://github.com/phillips1012>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node-0.10.d.ts" />
/** This library provides IRC client functionality. */
declare module 'irc' {
import events = require('events');
import crypto = require('crypto');
import net = require('net');
/** This library provides IRC client functionality. */
module NodeIRC {
/** A nick connect to an IRC server. */
export class Client extends events.EventEmitter {
/**
* Socket to the server. Rarely, if ever needed. Use Client#send
* instead.
*/
public conn: net.Socket
/**
* Channels joined. Includes channel modes, user list, and topic
* information. Only updated after the server recognizes the join.
*/
public chans: {
[index: string]: {
key: string;
serverName: string;
users: {
[index: string]: string;
};
mode: string;
created: string;
}
}
/** Features supported by the server */
public supported: {
channel: {
idlength: string[];
length: number;
limit: string[];
modes: {
[index: string]: string;
}
types: string;
};
kicklength: number;
maxlist: number[];
maxtargets: string[];
modes: number;
nicklength: number
topiclength: number;
usermodes: string;
}
/**
* The current nick of the client. Updated if the nick changes
*/
public nick: string;
/** Channel listing data. */
public channellist: IChannel[];
/** IRC server MOTD */
public motd: string;
/** Maximum line length */
public maxLineLength: number;
/** Bot options */
public opt: IClientOpts;
/** Host mask */
public hostMask: string;
/**
* Connect to an IRC server
* @param server - server hostname
* @param nick - nickname
* @param opts
*/
constructor(
server: string,
nick: string,
opts?: IClientOpts
);
/**
* Send a raw message to the server; generally speaking, its best
* not to use this method unless you know what youre doing.
* @param command - irc command
* @param args - command arguments (splat)
*/
public send(
command: string,
...args: string[]
): void;
/**
* Join the specified channel
* @param channel - channel to join
* @param callback
*/
public join(
channel: string,
callback?: handlers.IJoinChannel
): void;
/**
* Part the specified channel
* @param channel - channel to part
* @param message - optional message to send
* @param callback
*/
public part(
channel: string,
message: string,
callback: handlers.IPartChannel
): void;
/**
* Send a message to the specified target
* @param target - nick or channel
* @param message - message to send
*/
public say(
target: string,
message: string
): void;
/**
* Send a CTCP message to the specified target
* @param target - nick or channel
* @param type - "privmsg" for PRIVMSG, anything else for NOTICE
* @param text - CTCP message
*/
public ctcp(
target: string,
type: string,
text: string
): void;
/**
* Send an action to the specified target
* @param target - target
* @param message - message
*/
public action(
target: string,
message: string
): void;
/**
* Send a notice to the specified target.
* @param target - nick or channel
* @param message - message to send
*/
public notice(
target: string,
message: string
): void;
/**
* Request a whois for the specified nick
* @param nick - nickname
* @param callback
*/
public whois(
nick: string,
callback: handlers.IWhois
): void;
/**
* Request a channel listing from the server. The arguments for this
* are farily server specific, this method passes them as specified.
*
* Responses from the server are available via `channellist_start`,
* `channellist_item`, and `channellist` events.
*
* @param args - arguments
*/
public list(
...args: string[]
): void;
/**
* Connect to the server. Use when `autoConnect` is false.
* @param retryCount - times to retry
* @param callback
*/
public connect(
retryCount?: number,
callback?: handlers.IRaw
): void;
/**
* Disconnect from the IRC server
* @param message - message to send
* @param callback
*/
public disconnect(
message: string,
callback: () => void
): void;
/**
* Activate flood protection “after the fact”. You can also use
* floodProtection while instantiating the Client to enable flood
* protection, and floodProtectionDelay to set the default message
* interval.
* @param interval - ms to wait between messages
*/
public activateFloodProtection(
interval: number
): void;
}
/** Client options object */
export interface IClientOpts {
/**
* IRC username
* @default 'nodebot'
*/
userName?: string;
/**
* IRC "real name"
* @default 'nodeJS IRC client'
*/
realName?: string;
/**
* IRC connection port. See
* https://nodejs.org/api/net.html#net_socket_remoteport
* @default 6667
*/
port?: number;
/**
* Local interface to bind to for network connections. See
* https://nodejs.org/api/net.html#net_socket_localaddress
*/
localAddress?: string;
/**
* Should we output debug messages to STDOUT?
* @default false
*/
debug?: boolean;
/**
* Should we output IRC errors?
* @default false
*/
showErrors?: boolean;
/**
* Should we auto-rejoin channels?
* @default false
*/
autoRejoin?: boolean;
/**
* Should we auto-reconnect to networks?
* @default true
*/
autoConnect?: boolean;
/**
* Channels to join
* @default []
*/
channels?: string[];
/**
* Should SSL be used? Can either be true or crypto credentials.
* @default false
*/
secure?: boolean | crypto.Credentials;
/**
* Should we accept self-signed certificates?
* @default false
*/
selfSigned?: boolean;
/**
* Should we accept expired certificates?
* @default false
*/
certExpired?: boolean;
/**
* Should we queue our messages to ensure we don't get kicked?
* @default false
*/
floodProtection?: boolean;
/**
* Delay between messages when flood protection is active
* @default 1000
*/
floodProtectionDelay?: number;
/**
* Should we use SASL authentication?
* @default false
*/
sasl?: boolean;
/**
* Should we strip mIRC colors from the output messages?
* @default false
*/
stripColors?: boolean;
/**
* Channel prefix
* @default '&#'
*/
channelPrefixes?: string;
/**
* Characters to split a message at.
* @default 512
*/
messageSplit?: number;
/**
* Encoding to use. See
* https://nodejs.org/api/stream.html#stream_readable_setencoding_encoding
* @default 'utf-8'
*/
encoding?: string;
}
/** Command types */
export enum CommandType {
normal, reply, error
}
/** Parsed IRC message. */
export interface IMessage {
/** Prefix */
prefix?: string;
/** Mapped IRC command */
command: string;
/** Raw IRC command */
rawCommand: string;
/** Command type */
commandType: CommandType;
/** Command arguments */
args: string[];
}
/** Whois data */
export interface IWhoisData {
/** Nickname */
nick: string;
/** Username */
user: string;
/** Hostnamej */
host: string;
/** Real name" */
realname: string;
/** Channels */
channels: string[];
/** Server */
server: string;
/** Server description string */
serverinfo: string;
/** Is this user an operator? */
operator: string;
}
/** A channel returned by a channel listing. */
export interface IChannel {
/** Channel name */
name: string;
/** User count */
users: string;
/** Topic string */
topic: string;
}
/**
* Handler functions for Client.
*/
module handlers {
/**
* 'registered': Emitted when the server sends the initial 001 line,
* indicating youve connected to the server. See the raw event for
* details on the message object.
*/
export interface IRegistered {
/**
* @param message - raw message
*/
(message: IMessage): void;
}
/**
* 'motd': Emitted when the server sends the message of the day to
* clients.
*/
export interface IMotd {
/**
* @param motd - motd string
*/
(motd: string): void;
}
/**
* 'names': Emitted when the server sends a list of nicks for a channel
* (which happens immediately after joining and on request. The nicks
* object passed to the callback is keyed by nick names, and has
* values ‘’, +, or @ depending on the level of that nick in the
* channel.
*/
export interface INames {
/**
* @param channel - channel name
* @param nicks - nicks list
*/
(channel: string, nicks: string[]): void;
}
/**
* 'names#*' As per names event but only emits for the subscribed
* channel.
*/
export interface INamesChannel {
/**
* @param channel - channel name
* @param nicks - nicks list
*/
(nicks: string[]): void;
}
/**
* 'topic': Emitted when the server sends the channel topic on joining
* a channel, or when a user changes the topic on a channel. See the
* raw event for details on the message object.
*/
export interface ITopic {
/**
* @param channel - channel name
* @param topic - topic
* @param nick - nick
* @param message - raw message
*/
(
channel: string,
topic: string,
nick: string,
message: IMessage
): void;
}
/**
* 'join': Emitted when a user joins a channel (including when the
* client itself joins a channel). See the raw event for details on the
* message object.
*/
export interface IJoin {
/**
* @param channel - channel name
* @param nick - who joined
* @param message - raw message
*/
(channel: string, nick: string, message: IMessage): void;
}
/**
* 'join#*': As per join event but only emits for the subscribed
* channel. See the raw event for details on the message object.
*/
export interface IJoinChannel {
/**
* @param nick - who joined
* @param message - raw message
*/
(nick: string, message: IMessage): void;
}
/**
* 'part': Emitted when a user parts a channel (including when the
* client itself parts a channel). See the raw event for details on the
* message object.
*/
export interface IPart {
/**
* @param channel - channel name
* @param nick - who parted
* @param reason - part reason
* @param message - raw message
*/
(
channel: string,
nick: string,
reason: string,
message: IMessage
): void
}
/**
* 'part': As per part event but only emits for the subscribed
* channel. See the raw event for details on the message object.
*/
export interface IPartChannel {
/**
* @param nick - who parted
* @param reason - part reason
* @param message - raw message
*/
(
nick: string,
reason: string,
message: IMessage
): void
}
/**
* 'kick': Emitted when a user is kicked from a channel. See the raw
* event for details on the message object.
*/
export interface IKick {
/**
* @param channel - channel name
* @param nick - who was kicked
* @param by - kicker
* @param reason - kick reason
* @param message - raw message
*/
(
channel: string,
nick: string,
by: string,
reason: string,
message: IMessage
): void;
}
/**
* 'kick#*': Emitted when a user is kicked from a channel. See the raw
* event for details on the message object.
*/
export interface IKickChannel {
/**
* @param nick - who was kicked
* @param by - kicker
* @param reason - kick reason
* @param message - raw message
*/
(
nick: string,
by: string,
reason: string,
message: IMessage
): void;
}
/**
* 'message': Emitted when a message is sent. to can be either a nick
* (which is most likely this clients nick and means a private message),
* or a channel (which means a message to that channel). See the raw
* event for details on the message object.
*/
export interface IRecievedMessage {
/**
* @param nick - who sent the message
* @param to - to whom was the message sent
* @param text - message text
* @param message - raw message
*/
(
nick: string, to: string, text: string, message: IMessage
): void;
}
/**
* 'message#': Emitted when a message is sent to any channel (i.e.
* exactly the same as the message event but excluding private
* messages. See the raw event for details on the message object.
*/
export interface IMessageAllChannels {
/**
* @param nick - who sent the message
* @param to - to whom was the message sent
* @param text - message text
* @param message - raw message
*/
(
nick: string, to: string, text: string, message: IMessage
): void;
}
/**
* 'message#*': As per message event but only emits for the
* subscribed channel. See the raw event for details on the message
* object.
*/
export interface IMessageChannel {
/**
* @param nick - who sent the message
* @param text - message text
* @param message - raw message
*/
(nick: string, text: string, message: IMessage): void;
}
/**
* 'selfMessage': Emitted when a message is sent from the client.
* `to` is who the message was sent to. It can be either a nick
* (which most likely means a private message), or a channel (which
* means a message to that channel).
*/
export interface ISelfMessage {
(to: string, text: string): void;
}
/**
* 'notice': Emitted when a notice is sent. to can be either a nick
* (which is most likely this clients nick and means a private
* message), or a channel (which means a message to that channel). nick
* is either the senders nick or null which means that the notice comes
* from the server. See the raw event for details on the message object.
*/
export interface INotice {
/**
* @param nick - from
* @param to - to
* @param text - text
* @param message - raw message
*/
(nick: string, to: string, text: string, message: IMessage): void;
}
/**
* 'ping': Emitted when a server PINGs the client. The client will
* automatically send a PONG request just before this is emitted.
*/
export interface IPing {
/**
* @param server - server that adiministered the ping
*/
(server: string): void;
}
/**
* 'pm': As per message event but only emits when the message is
* direct to the client. See the raw event for details on the message
* object.
*/
export interface IPm {
/**
* @param nick - sender
* @param text - message text
* @param message - raw message
*/
(nick: string, text: string, message: IMessage): void;
}
/**
* 'ctcp': Emitted when a CTCP notice or privmsg was received (type
* is either notice or privmsg). See the raw event for details
* on the message object.
*/
export interface ICtcp {
/**
* @param from - sender
* @param to - recievier
* @param text - ctcp text
* @param type - ctcp type
* @param message - raw message
*/
(
from: string,
to: string,
text: string,
type: string,
message: IMessage
): void;
}
/**
* 'ctcp-*': Emitted when a specific type of CTCP request was
* recieved.
*/
export interface ICtcpSpecific {
/**
* @param from - sender
* @param to - recievier
* @param message - raw message
*/
(
from: string,
to: string,
text: string,
message: IMessage
): void;
(
from: string,
to: string,
text: string,
type: string,
message: IMessage
): void;
}
/**
* 'nick': Emitted when a user changes nick along with the channels
* the user is in. See the raw event for details on the message
* object.
*/
export interface INick {
/**
* @param oldnick - old nickname
* @param newnick - new nickname
* @param channels - channels the nick changed in
* @param message - raw message
*/
(
oldnick: string,
newnick: string,
channels: string[],
message: IMessage
): void;
}
/**
* 'invite': Emitted when the client receives an /invite. See the
* raw event for details on the message object.
*/
export interface IInvite {
/**
* @param channel - channel user was invited to
* @param from - user who invited
* @param message - raw message
*/
(channel: string, from: string, message: IMessage): void;
}
/**
* '+mode'/'-mode': Emitted when a mode is added or removed from a user or
* channel. channel is the channel which the mode is being set on/in
* . by is the user setting the mode. mode is the single character
* mode identifier. If the mode is being set on a user, argument is
* the nick of the user. If the mode is being set on a channel,
* argument is the argument to the mode. If a channel mode doesnt
* have any arguments, argument will be undefined. See the raw
* event for details on the message object.
*/
export interface IModeChange {
/**
* @param channel - channel
* @param by - nick that changed mode
* @param mode - single character mode identifier
* @param argument - mode argument
* @param message - raw message
*/
(
channel: string,
by: string,
mode: string,
argument: string,
message: IMessage
): void;
}
/**
* 'whois': Emitted whenever the server finishes outputting a WHOIS
* response.
*/
export interface IWhois {
(info: IWhoisData): void;
}
/**
* 'channellist': Emitted when the server has finished returning a
* channel list. The channel_list array is simply a list of the
* objects that were returned in the intervening channellist_item
* events.
*
* This data is also available via the Client.channellist property
* after this event has fired.
*/
export interface IChannelList {
/**
* @param list - channels
*/
(
list: IChannel[]
): void;
}
/**
* 'raw': Emitted when ever the client receives a “message” from
* the server. A message is a parsed line from the server.
*/
export interface IRaw {
/**
* @param message - raw message
*/
(message: IMessage): void;
}
/**
* 'error': Emitted when ever the server responds with an error-type message. The message parameter is exactly as in the raw event.
*/
export interface IError {
/**
* @param message - raw message
*/
(message: IMessage): void;
}
/**
* 'action': Emitted whenever a user performs an action
* (e.g. /me waves).
*/
export interface IAction {
/**
* @param from - sender
* @param to - reciever
* @param text - text
* @param message - raw message
*/
(
from: string, to: string, text: string, message: IMessage
): void;
}
}
}
/** Colors */
module NodeIRC.colors {
/**
* Takes a color by name, text, and optionally what color to return.
* @param color - name of color
* @param text - text to color
* @param reset_color - color to set after text
*/
export function wrap(
color: string, text: string, reset_color?: string
): string;
/**
* This contains the set of colors available and a function to wrap
* text in a color.
*/
export var codes: {
[index: string]: string;
};
}
export = NodeIRC;
}
+11 -2
View File
@@ -61,6 +61,11 @@ declare module 'joi' {
options?: ValidationOptions;
}
export interface ValidationResult<T> {
error: ValidationError;
value: T;
}
export interface SchemaMap {
[key: string]: Schema;
}
@@ -252,6 +257,11 @@ declare module 'joi' {
* Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed.
*/
trim(): StringSchema;
/**
* Requires the string value to be a valid uri with the passed scheme.
*/
uri(options?: { scheme?: string }): StringSchema;
}
export interface ArraySchema extends AnySchema<ArraySchema> {
@@ -461,8 +471,7 @@ declare module 'joi' {
*/
export function validate<T>(value: T, schema: Schema, callback: (err: ValidationError, value: T) => void): void;
export function validate<T>(value: T, schema: Object, callback: (err: ValidationError, value: T) => void): void;
export function validate<T>(value: T, schema: Schema, options?: ValidationOptions, callback?: (err: ValidationError, value: T) => void): void;
export function validate<T>(value: T, schema: Object, options?: ValidationOptions, callback?: (err: ValidationError, value: T) => void): void;
export function validate<T>(value: T, schema: Object, options?: ValidationOptions, callback?: (err: ValidationError, value: T) => void): ValidationResult<T>;
/**
* Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object).
+225
View File
@@ -0,0 +1,225 @@
/// <reference path="jquery-sortable.d.ts" />
/**
* http://johnny.github.io/jquery-sortable/#connected
*/
function connectedListsWithDropAnimation() {
var adjustment: any;
$('ol.simple_with_animation').sortable({
group: 'simple_with_animation',
pullPlaceholder: false,
// animation on drop
onDrop: function (item, targetContainer, _super) {
var clonedItem = $('<li/>').css({height: 0})
item.before(clonedItem)
clonedItem.animate({'height': item.height()})
item.animate(clonedItem.position(), function () {
clonedItem.detach();
_super(item);
})
},
// set item relative to cursor position
onDragStart: function ($item, container, _super) {
var offset = $item.offset(),
pointer = container.rootGroup.pointer;
adjustment = {
left: pointer.left - offset.left,
top: pointer.top - offset.top
};
_super($item, container);
},
onDrag: function ($item, position) {
$item.css({
left: position.left - adjustment.left,
top: position.top - adjustment.top
})
}
});
}
/**
* http://johnny.github.io/jquery-sortable/#handle
*/
function sortHandleAndLimitedDragDrop() {
$('ol.simple_with_drop').sortable({
group: 'no-drop',
handle: 'i.icon-move',
onDragStart: function (item, container, _super) {
// Duplicate items of the no drop area
if(!container.options.drop)
item.clone().insertAfter(item)
_super(item)
}
});
$('ol.simple_with_no_drop').sortable({
group: 'no-drop',
drop: false
});
$('ol.simple_with_no_drag').sortable({
group: 'no-drop',
drag: false
});
}
/**
* http://johnny.github.io/jquery-sortable/#nested
*/
function toggleNestedLists() {
var oldContainer: any;
$('ol.nested_with_switch').sortable({
group: 'nested',
afterMove: function (placeholder, container) {
if(oldContainer != container){
if(oldContainer)
oldContainer.el.removeClass('active')
container.el.addClass('active')
oldContainer = container
}
},
onDrop: function (item, container, _super) {
container.el.removeClass('active')
_super(item)
}
});
$('.switch-container').on('click', '.switch', function (e) {
var method = $(this).hasClass('active') ? 'enable' : 'disable'
$(e.delegateTarget).next().sortable(method)
});
}
/**
* http://johnny.github.io/jquery-sortable/#limited-target
*/
function connectedListsWithLimitedDropTargets() {
var group = $('ol.limited_drop_targets').sortable({
group: 'limited_drop_targets',
isValidTarget: function (item, container) {
if(item.is('.highlight'))
return true
else {
return item.parent('ol')[0] == container.el[0]
}
},
onDrop: function (item, container, _super) {
$('#serialize_output').text(group.sortable('serialize').get().join('\n'));
_super(item, container);
},
serialize: function (parent, children, isContainer) {
return isContainer ? children.join() : 24;
},
tolerance: 6,
distance: 10
});
}
/**
* http://johnny.github.io/jquery-sortable/#bootstrap
*/
function sortingABootstrapMenu() {
$('ol.nav').sortable({
group: 'nav',
nested: false,
vertical: false,
exclude: '.divider-vertical',
onDragStart: function($item, container, _super) {
$item.find('ol.dropdown-menu').sortable('disable');
_super($item, container);
},
onDrop: function($item, container, _super) {
$item.find('ol.dropdown-menu').sortable('enable');
_super($item, container);
}
});
$('ol.dropdown-menu').sortable({
group: 'nav'
});
}
/**
* http://johnny.github.io/jquery-sortable#serialization
*/
function serializationAndDelay() {
var group = $('ol.serialization').sortable({
group: 'serialization',
delay: 500,
onDrop: function (item, container, _super) {
var data = group.sortable('serialize').get();
var jsonString = JSON.stringify(data, null, ' ');
$('#serialize_output2').text(jsonString);
_super(item, container);
}
});
}
/**
* http://johnny.github.io/jquery-sortable/#table
*/
function sortTables() {
// Sortable rows
$('.sorted_table').sortable({
containerSelector: 'table',
itemPath: '> tbody',
itemSelector: 'tr',
placeholder: '<tr class="placeholder"/>'
});
// Sortable column heads
var oldIndex: any;
$('.sorted_head tr').sortable({
containerSelector: 'tr',
itemSelector: 'th',
placeholder: '<th class="placeholder"/>',
vertical: false,
onDragStart: function (item, group, _super) {
oldIndex = item.index();
item.appendTo(item.parent());
_super(item);
},
onDrop: function (item, container, _super) {
var field: any,
newIndex = item.index()
if (newIndex != oldIndex)
item.closest('table').find('tbody tr').each(function (i, row) {
var $row = $(row);
field = $row.children().eq(oldIndex);
if(newIndex)
field.before($row.children()[newIndex]);
else
$row.prepend(field);
});
_super(item);
}
});
}
/**
* http://johnny.github.io/jquery-sortable/#docs
*/
function api() {
$('.horatio').sortable().sortable('disable').sortable('enable')
.sortable('refresh').sortable('serialize').sortable('destroy');
}
+104
View File
@@ -0,0 +1,104 @@
// Type definitions for jQuery Sortable v0.9.12
// Project: http://johnny.github.io/jquery-sortable/
// Definitions by: Nathan Pitman <https://github.com/Seltzer>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
declare module JQuerySortable {
interface Position {
top: number;
left: number;
}
type Dimensions = number[];
interface ContainerGroup {
$document: JQuery;
containerDimensions: Dimensions[]
containers: Container[];
delayMet: boolean;
dragInitDone: boolean;
dragProxy: any;
dragging: boolean;
dropProxy: any;
item: JQuery;
itemContainer: Container;
lastAppendedItem: JQuery;
lastPointer: Position;
lastRelativePointer: Position;
offsetParent: JQuery;
options: Options;
placeholder: JQuery;
pointer: Position;
relativePointer: Position;
sameResultBox: { bottom: number; left: number; right: number; top: number; };
scrollProxy: any;
}
interface Container {
el: JQuery;
options: Options;
group: ContainerGroup;
rootGroup: ContainerGroup;
handle: string;
target: JQuery;
itemDimensions: Dimensions[];
items: HTMLElement[];
}
type GenericEventHandler = ($item?: JQuery, container?: Container, _super?: GenericEventHandler, event?: Event) => void;
type OnDragEventHandler = ($item?: JQuery, position?: Position, _super?: OnDragEventHandler, event?: Event) => void;
type OnMousedownHandler = ($item?: JQuery, _super?: OnMousedownHandler, event?: Event) => void;
type OnCancelHandler = ($item?: JQuery, container?: Container, _super?: OnCancelHandler, event?: Event) => void;
// Deliberately typing $children as an any here as it makes it much easier to use. Actual type is JQuery | any[]
type SerializeFunc = ($parent: JQuery, $children: any, parentIsContainer: boolean) => void;
interface GroupOptions {
afterMove?: ($placeholder: JQuery, container: Container, $closestItemOrContainer: JQuery) => void;
containerPath?: string;
containerSelector?: string;
distance?: number;
delay?: number;
handle?: string;
itemPath?: string;
itemSelector?: string;
isValidTarget?: ($item: JQuery, container: Container) => boolean;
onCancel?: OnCancelHandler;
onDrag?: OnDragEventHandler;
onDragStart?: GenericEventHandler;
onDrop?: GenericEventHandler;
onMousedown?: OnMousedownHandler;
placeholder?: JQuery | any[] | Element | string;
pullPlaceholder?: boolean;
serialize?: SerializeFunc;
tolerance?: number;
}
interface ContainerOptions {
drag?: boolean;
drop?: boolean;
exclude?: string;
nested?: boolean;
vertical?: boolean;
}
interface Options extends GroupOptions, ContainerOptions {
}
}
interface JQuery {
sortable(options?: JQuerySortable.Options): JQuery;
sortable(methodName: 'enable'): JQuery;
sortable(methodName: 'disable'): JQuery;
sortable(methodName: 'refresh'): JQuery;
sortable(methodName: 'destroy'): JQuery;
sortable(methodName: 'serialize'): JQuery;
sortable(methodName: string): JQuery;
}
@@ -2,3 +2,7 @@
/// <reference path="jquery.placeholder.d.ts"/>
$('input').placeholder();
// specify custom class
$('input').placeholder({ customClass: 'my-placeholder' });
+4 -5
View File
@@ -1,13 +1,12 @@
// Type definitions for jquery.placeholder.js 2.0.7
// Type definitions for jquery.placeholder.js 2.1.1
// Project: https://github.com/mathiasbynens/jquery-placeholder
// Definitions by: Peter Gill <https://github.com/majorsilence>
// Definitions by: Peter Gill <https://github.com/majorsilence>, Neil Culver <https://github.com/EnableSoftware>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface JQuery {
placeholder() : void;
placeholder(options: { customClass: string }) : JQuery
placeholder() : JQuery
}
+4
View File
@@ -5,6 +5,10 @@
declare var signals: SignalWrapper;
declare module "signals" {
export = signals;
}
interface SignalWrapper {
Signal: Signal
}
+32 -13
View File
@@ -33,18 +33,18 @@ function testJSZip() {
var folder = newJszip.folder("test");
if(folder.file("test.txt").asText() == "test string") {
log(SEVERITY.INFO, "all ok");
}
}
else {
log(SEVERITY.ERROR, "wrong file");
}
var folders = newJszip.folder(new RegExp("^test"));
if(folders.length == 1) {
log(SEVERITY.INFO, "all ok");
if(folders[0].dir == true) {
log(SEVERITY.INFO, "all ok");
}
}
else {
log(SEVERITY.ERROR, "wrong file");
}
@@ -59,14 +59,14 @@ function testJSZip() {
log(SEVERITY.INFO, "all ok");
}
else {
log(SEVERITY.ERROR, "wrong data in files");
log(SEVERITY.ERROR, "wrong data in files");
}
}
}
else {
log(SEVERITY.ERROR, "wrong number of files");
}
var filterFiles = newJszip.filter((relativePath: string, file: JSZipObject) => {
var filterFiles = newJszip.filter((relativePath: string, file: JSZipObject) => {
if (file.asText() == "test string") {
return true;
}
@@ -82,7 +82,7 @@ function testJSZip() {
newJszip.remove("test/test.txt");
filterFiles = newJszip.filter((relativePath: string, file: JSZipObject) => {
filterFiles = newJszip.filter((relativePath: string, file: JSZipObject) => {
if (file.asText() == "test string") {
return true;
}
@@ -95,24 +95,43 @@ function testJSZip() {
else {
log(SEVERITY.ERROR, "wrong number of files");
}
var uncompressedStr = JSZip.compressions.DEFLATE.uncompress(
JSZip.compressions.DEFLATE.compress("\0\1\2\3\4\5\6\7",{level:9}));
var uncompressedArr = JSZip.compressions.DEFLATE.uncompress(
JSZip.compressions.DEFLATE.compress([0,1,2,3,4,5,6,7],{level:9}));
var uncompressedUint8Arr = JSZip.compressions.DEFLATE.uncompress(
JSZip.compressions.DEFLATE.compress(new Uint8Array([0,1,2,3,4,5,6,7]),{level:9}));
var every_match = [0,1,2,3,4,5,6,7].every(function(val, i){
return uncompressedStr[i] === val &&
uncompressedArr[i] === val &&
uncompressedUint8Arr[i] === val;
});
if(every_match) {
log(SEVERITY.INFO, "compress and uncompress ok.");
}else{
log(SEVERITY.ERROR, "compress or uncompress failed.");
}
}
function log(severity:number, message: any) {
var log = "";
switch(severity) {
case 0:
case 0:
log += "[DEBUG] ";
break;
case 1:
case 1:
log += "[INFO] ";
break;
case 2:
case 2:
log += "[WARN] ";
break;
case 3:
case 3:
log += "[ERROR] ";
break;
case 4:
case 4:
log += "[FATAL] ";
break;
default:
@@ -122,4 +141,4 @@ function log(severity:number, message: any) {
console.log(log += message);
}
testJSZip();
testJSZip();
+18 -3
View File
@@ -32,7 +32,7 @@ interface JSZip {
/**
* Return an new JSZip instance with the given folder as root
*
*
* @param name Name of the folder
* @return New JSZip object with the given folder as root or null
*/
@@ -40,7 +40,7 @@ interface JSZip {
/**
* Returns new JSZip instances with the matching folders as root
*
*
* @param name RegExp to match
* @return New array of JSZipFile objects which match the RegExp
*/
@@ -56,7 +56,7 @@ interface JSZip {
/**
* Removes the file or folder from the archive
*
*
* @param path Relative path of file or folder
* @return Returns the JSZip instance
*/
@@ -140,6 +140,18 @@ interface JSZipSupport {
nodebuffer: boolean;
}
interface DEFLATE {
/** pako.deflateRaw, level:0-9 */
compress(input: string, compressionOptions: {level:number}): Uint8Array;
compress(input: number[], compressionOptions: {level:number}): Uint8Array;
compress(input: Uint8Array, compressionOptions: {level:number}): Uint8Array;
/** pako.inflateRaw */
uncompress(input: string): Uint8Array;
uncompress(input: number[]): Uint8Array;
uncompress(input: Uint8Array): Uint8Array;
}
declare var JSZip: {
/**
* Create JSZip instance
@@ -169,6 +181,9 @@ declare var JSZip: {
prototype: JSZip;
support: JSZipSupport;
compressions: {
DEFLATE: DEFLATE;
}
}
declare module "jszip" {
+90
View File
@@ -0,0 +1,90 @@
/// <reference path="knockout-paging.d.ts" />
// Different option formats
var emptyOptions = {};
var pageNumberOptions = { pageNumber: 2 };
var pageSizeOptions = { pageSize: 10 };
var generatorOptions = { pageGenerator: 'sliding' };
var allOptions = { pageNumber: 2, pageSize: 10, pageGenerator: 'sliding' };
function defaults() {
ko.paging.defaults.pageNumber = 1;
ko.paging.defaults.pageSize = 50;
}
function pageGenerators() {
// Allow to set the windowSize on sliding page generator
ko.paging.generators['sliding'].windowSize(5);
// Add custom page generator
ko.paging.generators['custom'] = {
generate: function(pagedObservable: KnockoutObservable<any>) {
return [0, 1];
}
}
}
function usingPagedObservableArrayFunctionOnKnockoutStatic() {
var simplePaged = ko.pagedObservableArray();
var initializedPaged = ko.pagedObservableArray([1, 2, 3]);
var emptyOptionsPaged = ko.pagedObservableArray([1, 2, 3], emptyOptions);
var pageNumberOptionsPaged = ko.pagedObservableArray([1, 2, 3], pageNumberOptions);
var pageSizeOptionsPaged = ko.pagedObservableArray([1, 2, 3], pageSizeOptions);
var generatorOptionsPaged = ko.pagedObservableArray([1, 2, 3], generatorOptions);
var allOptionsPaged = ko.pagedObservableArray([1, 2, 3], allOptions);
// Here we verify that the returned type is the paged observable array
simplePaged.pageSize();
initializedPaged.pageSize();
emptyOptionsPaged.pageSize();
pageNumberOptionsPaged.pageSize();
pageSizeOptionsPaged.pageSize();
generatorOptionsPaged.pageSize();
allOptionsPaged.pageSize();
}
function usingExtend() {
var emptyOptionsPaged = ko.observableArray([]).extend({ paged: emptyOptions });
var pageNumberOptionsPaged = ko.observableArray([]).extend({ paged: pageNumberOptions });
var pageSizeOptionsPaged = ko.observableArray([]).extend({ paged: pageSizeOptions });
var generatorOptionsPaged = ko.observableArray([]).extend({ paged: generatorOptions });
var allOptionsPaged = ko.observableArray([]).extend({ paged: allOptions });
var withInitialArrayValue = ko.observableArray([1, 2, 3]).extend({ paged: emptyOptions });
// Here we verify that the returned type is the paged observable array
emptyOptionsPaged.pageSize();
pageNumberOptionsPaged.pageSize();
pageSizeOptionsPaged.pageSize();
generatorOptionsPaged.pageSize();
allOptionsPaged.pageSize();
}
function observables() {
var paged = ko.pagedObservableArray([]);
var pageSize = paged.pageSize();
var pageNumber = paged.pageNumber();
}
function computed() {
var paged = ko.pagedObservableArray([]);
var pageItems = paged.pageItems();
var pageCount = paged.pageCount();
var itemCount = paged.itemCount();
var firstItemOnPage = paged.firstItemOnPage();
var lastItemOnPage = paged.lastItemOnPage();
var hasPreviousPage = paged.hasPreviousPage();
var hasNextPage = paged.hasNextPage();
var isFirstPage = paged.isFirstPage();
var isLastPage = paged.isLastPage();
var pages = paged.pages();
}
function functions() {
var paged = ko.pagedObservableArray([]);
paged.toNextPage();
paged.toLastPage();
paged.toNextPage();
paged.toPreviousPage();
paged.toFirstPage();
}
+67
View File
@@ -0,0 +1,67 @@
// Type definitions for knockout-paging
// Project: https://github.com/ErikSchierboom/knockout-paging
// Definitions by: Erik Schierboom <https://github.com/ErikSchierboom>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../knockout/knockout.d.ts" />
interface KnockoutStatic {
paging: KnockoutPagingOptions;
pagedObservableArray<T>(initialValue?: T[], options?: KnockoutPagedOptions): KnockoutPagedObservableArray<T>;
}
interface KnockoutPagingOptions {
defaults: KnockoutPagingDefaultOptions;
generators: {
[name: string]: KnockoutPageGenerator;
'sliding': KnockoutSlidingPageGenerator
}
}
interface KnockoutPagingDefaultOptions {
pageNumber: number;
pageSize: number;
}
interface KnockoutPagedObservableArray<T> extends KnockoutObservableArray<T> {
pageSize: KnockoutObservable<number>;
pageNumber: KnockoutObservable<number>;
pageItems: KnockoutComputed<T[]>;
pageCount: KnockoutComputed<number>;
itemCount: KnockoutComputed<number>;
firstItemOnPage: KnockoutComputed<number>;
lastItemOnPage: KnockoutComputed<number>;
hasPreviousPage: KnockoutComputed<boolean>;
hasNextPage: KnockoutComputed<boolean>;
isFirstPage: KnockoutComputed<boolean>;
isLastPage: KnockoutComputed<boolean>;
pages: KnockoutComputed<number[]>;
toNextPage(): void;
toPreviousPage(): void;
toLastPage(): void;
toFirstPage(): void;
}
interface KnockoutPagedOptions {
pageSize?: number;
pageNumber?: number;
pageGenerator?: string;
}
interface KnockoutObservableArray<T> {
extend(requestedExtenders: { 'paged': any; }): KnockoutPagedObservableArray<T>;
}
interface KnockoutPageGenerator {
generate<T>(pagedObservable: KnockoutPagedObservableArray<T>): number[];
}
interface KnockoutSlidingPageGenerator extends KnockoutPageGenerator {
windowSize: KnockoutObservable<number>;
}
interface KnockoutExtenders {
paged(target: KnockoutObservableArray<any>, options: KnockoutPagedOptions): KnockoutObservableArray<any>;
}
@@ -0,0 +1,15 @@
/// <reference path="knockout-pre-rendered.d.ts" />
function initBindingHandler() {
ko.bindingHandlers.init = {
init: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => {},
update: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => {}
};
}
function foreachInitBindingHandler() {
ko.bindingHandlers.foreachInit = {
init: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => { },
update: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => { }
};
}
+11
View File
@@ -0,0 +1,11 @@
// Type definitions for knockout-pre-rendered
// Project: https://github.com/ErikSchierboom/knockout-pre-rendered
// Definitions by: Erik Schierboom <https://github.com/ErikSchierboom>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../knockout/knockout.d.ts" />
interface KnockoutBindingHandlers {
init: KnockoutBindingHandler;
foreachInit: KnockoutBindingHandler;
}
+2 -2
View File
@@ -248,9 +248,9 @@ interface KnockoutUtils {
removeDisposeCallback(node: Element, callback: Function): void;
cleanNode(node: Element): Element;
cleanNode(node: Node): Element;
removeNode(node: Element): void;
removeNode(node: Node): void;
};
//////////////////////////////////
+61 -27
View File
@@ -1,34 +1,68 @@
/// <reference path="localForage.d.ts" />
/// <reference path="localForage.d.ts" />
declare var localForage: lf.ILocalForage<string>
declare var callback: lf.ICallback<string>
declare var promise: lf.IPromise<string>
declare var localForage: lf.ILocalForage<string>;
declare var callback: lf.ICallback<string>;
declare var iterateCallback: lf.IIterateCallback<string>;
declare var errorCallback: lf.IErrorCallback;
declare var keyCallback: lf.IKeyCallback;
declare var keysCallback: lf.IKeysCallback;
declare var numberCallback: lf.INumberCallback;
declare var promise: lf.IPromise<string>;
() => {
localForage.clear()
localForage.length
localForage.key(0)
localForage.clear((err: any) => {
var newError: any = err;
});
localForage.iterate((str: string, key: string, num: number) => {
var newStr: string = str;
var newKey: string = key;
var newNum: number = num;
});
localForage.length((err: any, num: number) => {
var newError: any = err;
var newNumber: number = num;
});
localForage.key(0,(err: any, value: string) => {
var newError: any = err;
var newValue: string = value;
});
localForage.keys((err: any, keys: Array<string>) => {
var newError: any = err;
var newArray: Array<string> = keys;
});
localForage.getItem("key",(err: any, str: string) => {
var newError: any = err;
var newStr: string = str
});
localForage.getItem("key").then((err: any, str: string) => {
var newError: any = err;
var newStr: string = str
});
localForage.getItem("key", (str: string) => {
var newStr: string = str
})
localForage.getItem("key").then((str: string) => {
var newStr: string = str
})
localForage.setItem("key", "value",(err: any, str: string) => {
var newError: any = err;
var newStr: string = str
});
localForage.setItem("key", "value").then((err: any, str: string) => {
var newError: any = err;
var newStr: string = str;
});
localForage.setItem("key", "value", (str: string) => {
var newStr: string = str
})
localForage.setItem("key", "value").then((str: string) => {
var newStr: string = str
})
localForage.removeItem("key",(err: any) => {
var newError: any = err;
});
localForage.removeItem("key").then((err: any, str: string) => {
var newError: any = err;
var newStr: string = str
});
localForage.removeItem("key", (str: string) => {
var newStr: string = str
})
localForage.removeItem("key").then((str: string) => {
var newStr: string = str
})
promise.then(callback)
promise.then(callback);
}
+54 -7
View File
@@ -1,23 +1,70 @@
// Type definitions for Mozilla's localForage
// Type definitions for Mozilla's localForage
// Project: https://github.com/mozilla/localforage
// Definitions by: david pichsenmeister <https://github.com/3x14159265>
// Definitions by: yuichi david pichsenmeister <https://github.com/3x14159265>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module lf {
interface ILocalForage<T> {
clear(): void
key(index: number): T
length: number
/**
* Removes every key from the database, returning it to a blank slate.
*/
clear(callback: IErrorCallback): void
/**
* Iterate over all value/key pairs in datastore.
*/
iterate(iterateCallback: IIterateCallback<T>): void
/**
* Get the name of a key based on its ID.
*/
key(keyIndex: number, callback: IKeyCallback): void
/**
* Get the list of all keys in the datastore.
*/
keys(callback: IKeysCallback): void;
/**
* Gets the number of keys in the offline store (i.e. its “length”).
*/
length(callback: INumberCallback): void
/**
* Gets an item from the storage library and supplies the result to a callback.
* If the key does not exist, getItem() will return null.
*/
getItem(key: string, callback: ICallback<T>): void
getItem(key: string): IPromise<T>
/**
* Saves data to an offline store.
*/
setItem(key: string, value: T, callback: ICallback<T>): void
setItem(key: string, value: T): IPromise<T>
removeItem(key: string, callback: ICallback<T>): void
/**
* Removes the value of a key from the offline store.
*/
removeItem(key: string, callback: IErrorCallback): void
removeItem(key: string): IPromise<T>
}
interface ICallback<T> {
(data: T): void
(err: any, value: T): void
}
interface IIterateCallback<T> {
(value: T, key: string, iterationNumber: number): void
}
interface IErrorCallback {
(err: any): void
}
interface IKeyCallback {
(err: any, keyName: string): void
}
interface IKeysCallback {
(err: any, keys: Array<string>): void
}
interface INumberCallback {
(err: any, numberOfKeys: number): void
}
interface IPromise<T> {
+39 -3
View File
@@ -39,6 +39,10 @@ interface IKey {
code: number;
}
interface IDictionary<T> {
[index: string]: T;
}
var foodsOrganic: IFoodOrganic[] = [
{ name: 'banana', organic: true },
{ name: 'beet', organic: false },
@@ -61,7 +65,10 @@ var stoogesAges: IStoogesAge[] = [
{ 'name': 'moe', 'age': 40 },
{ 'name': 'larry', 'age': 50 }
];
var stoogesAgesDict: IDictionary<IStoogesAge> = {
first: { 'name': 'moe', 'age': 40 },
second: { 'name': 'larry', 'age': 50 }
};
var stoogesCombined: IStoogesCombined[] = [
{ 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
{ 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] }
@@ -264,8 +271,14 @@ result = <IFoodType[]>_.last(foodsType, { 'type': 'vegetable' });
result = <number>_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
result = <number>_.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
result = <{ [key: string]: any }>_.zipObject(['moe', 'larry'], [30, 40]);
result = <{ [key: string]: any }>_.object(['moe', 'larry'], [30, 40]);
result = <_.Dictionary<any>>_.zipObject(['moe', 'larry'], [30, 40]);
result = <_.LoDashObjectWrapper<_.Dictionary<any>>>_(['moe', 'larry']).zipObject([30, 40]);
result = <_.Dictionary<any>>_.object(['moe', 'larry'], [30, 40]);
result = <_.LoDashObjectWrapper<_.Dictionary<any>>>_(['moe', 'larry']).object([30, 40]);
result = <_.Dictionary<any>>_.zipObject([['moe', 30], ['larry', 40]]);
result = <_.LoDashObjectWrapper<_.Dictionary<any>>>_([['moe', 30], ['larry', 40]]).zipObject();
result = <_.Dictionary<any>>_.object([['moe', 30], ['larry', 40]]);
result = <_.LoDashObjectWrapper<_.Dictionary<any>>>_([['moe', 30], ['larry', 40]]).object();
result = <number[]>_.pull([1, 2, 3, 1, 2, 3], 2, 3);
@@ -501,6 +514,23 @@ result = <_.LoDashWrapper<number>>_([4, 2, 8, 6]).min();
result = <_.LoDashWrapper<IStoogesAge>>_(stoogesAges).min(function (stooge) { return stooge.age; });
result = <_.LoDashWrapper<IStoogesAge>>_(stoogesAges).min('age');
result = <number>_.sum([4, 2, 8, 6]);
result = <number>_.sum([4, 2, 8, 6], function(v) { return v; });
result = <number>_.sum({a: 2, b: 4});
result = <number>_.sum({a: 2, b: 4}, function(v) { return v; });
result = <number>_.sum(stoogesAges, function (stooge) { return stooge.age; });
result = <number>_.sum(stoogesAges, 'age');
result = <number>_.sum(stoogesAgesDict, function(stooge) { return stooge.age; });
result = <number>_.sum(stoogesAgesDict, 'age');
result = <number>_([4, 2, 8, 6]).sum();
result = <number>_([4, 2, 8, 6]).sum(function(v) { return v; });
result = <number>_({a: 2, b: 4}).sum();
result = <number>_({a: 2, b: 4}).sum(function(v) { return v; });
result = <number>_(stoogesAges).sum(function (stooge) { return stooge.age; });
result = <number>_(stoogesAges).sum('age');
result = <number>_(stoogesAgesDict).sum(function (stooge) { return stooge.age; });
result = <number>_(stoogesAgesDict).sum('age');
result = <string[]>_.pluck(stoogesAges, 'name');
result = <string[]>_(stoogesAges).pluck('name').value();
@@ -611,6 +641,12 @@ result = <IStoogesCombined[]>_.where(stoogesCombined, { 'quotes': ['Poifect!'] }
result = <IStoogesCombined[]>_(stoogesCombined).where({ 'age': 40 }).value();
result = <IStoogesCombined[]>_(stoogesCombined).where({ 'quotes': ['Poifect!'] }).value();
/********
* Date *
********/
result = <number>_.now();
/*************
* Functions *
*************/
+175 -11
View File
@@ -41,6 +41,7 @@ declare module _ {
(value: number): LoDashWrapper<number>;
(value: string): LoDashWrapper<string>;
(value: boolean): LoDashWrapper<boolean>;
(value: Array<number>): LoDashNumberArrayWrapper;
<T>(value: Array<T>): LoDashArrayWrapper<T>;
<T extends {}>(value: T): LoDashObjectWrapper<T>;
(value: any): LoDashWrapper<any>;
@@ -205,6 +206,8 @@ declare module _ {
unshift(...items: any[]): LoDashWrapper<number>;
}
interface LoDashNumberArrayWrapper extends LoDashArrayWrapper<number> { }
//_.chain
interface LoDashStatic {
/**
@@ -2066,23 +2069,45 @@ declare module _ {
//_.zipObject
interface LoDashStatic {
/**
* Creates an object composed from arrays of keys and values. Provide either a single
* two dimensional array, i.e. [[key1, value1], [key2, value2]] or two arrays, one of
* keys and one of corresponding values.
* @param keys The array of keys.
* @param values The array of values.
* @return An object composed of the given keys and corresponding values.
* The inverse of _.pairs; this method returns an object composed from arrays of property
* names and values. Provide either a single two dimensional array, e.g. [[key1, value1],
* [key2, value2]] or two arrays, one of property names and one of corresponding values.
* @param props The property names.
* @param values The property values.
* @return Returns the new object.
**/
zipObject<TResult extends {}>(
keys: List<string>,
values: List<any>): TResult;
props: List<string>,
values?: List<any>): TResult;
/**
* @see _.object
* @see _.zipObject
**/
zipObject<TResult extends {}>(props: List<List<any>>): Dictionary<any>;
/**
* @see _.zipObject
**/
object<TResult extends {}>(
keys: List<string>,
values: List<any>): TResult;
props: List<string>,
values?: List<any>): TResult;
/**
* @see _.zipObject
**/
object<TResult extends {}>(props: List<List<any>>): Dictionary<any>;
}
interface LoDashArrayWrapper<T> {
/**
* @see _.zipObject
**/
zipObject(values?: List<any>): _.LoDashObjectWrapper<Dictionary<any>>;
/**
* @see _.zipObject
**/
object(values?: List<any>): _.LoDashObjectWrapper<Dictionary<any>>;
}
/* *************
@@ -3843,6 +3868,131 @@ declare module _ {
whereValue: W): LoDashWrapper<T>;
}
//_.sum
interface LoDashStatic {
/**
* Gets the sum of the values in collection.
*
* @param collection The collection to iterate over.
* @param iteratee The function invoked per iteration.
* @param thisArg The this binding of iteratee.
* @return Returns the sum.
**/
sum(
collection: Array<number>): number;
/**
* @see _.sum
**/
sum(
collection: List<number>): number;
/**
* @see _.sum
**/
sum(
collection: Dictionary<number>): number;
/**
* @see _.sum
**/
sum<T>(
collection: Array<T>,
iteratee: ListIterator<T, number>,
thisArg?: any): number;
/**
* @see _.sum
**/
sum<T>(
collection: List<T>,
iteratee: ListIterator<T, number>,
thisArg?: any): number;
/**
* @see _.sum
**/
sum<T>(
collection: Dictionary<T>,
iteratee: ObjectIterator<T, number>,
thisArg?: any): number;
/**
* @see _.sum
* @param property _.property callback shorthand.
**/
sum<T>(
collection: Array<T>,
property: string): number;
/**
* @see _.sum
* @param property _.property callback shorthand.
**/
sum<T>(
collection: List<T>,
property: string): number;
/**
* @see _.sum
* @param property _.property callback shorthand.
**/
sum<T>(
collection: Dictionary<T>,
property: string): number;
}
interface LoDashNumberArrayWrapper {
/**
* @see _.sum
**/
sum(): number
/**
* @see _.sum
**/
sum(
iteratee: ListIterator<number, number>,
thisArg?: any): number;
}
interface LoDashArrayWrapper<T> {
/**
* @see _.sum
**/
sum(
iteratee: ListIterator<T, number>,
thisArg?: any): number;
/**
* @see _.sum
* @param property _.property callback shorthand.
**/
sum(
property: string): number;
}
interface LoDashObjectWrapper<T> {
/**
* @see _.sum
**/
sum(): number
/**
* @see _.sum
**/
sum(
iteratee: ObjectIterator<any, number>,
thisArg?: any): number;
/**
* @see _.sum
* @param property _.property callback shorthand.
**/
sum(
property: string): number;
}
//_.pluck
interface LoDashStatic {
/**
@@ -4795,6 +4945,20 @@ declare module _ {
where<T, U extends {}>(properties: U): LoDashArrayWrapper<T>;
}
/********
* Date *
********/
//_.now
interface LoDashStatic {
/**
* Gets the number of milliseconds that have elapsed since the Unix epoch
* (1 January 1970 00:00:00 UTC).
* @return The number of milliseconds.
**/
now(): number;
}
/*************
* Functions *
*************/
+26
View File
@@ -0,0 +1,26 @@
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="magicsuggest.d.ts"/>
function basicTest() {
$('#magicSuggest').magicSuggest();
}
function testWithConfigurationOptions() {
$('#magicSuggest').magicSuggest({
data: [
{ id: 1, name: "Buenos Aires" },
{ id: 2, name: "New York" },
{ id: 3, name: "Madrid" },
],
maxDropHeight: 500,
maxSelection: 2,
expandOnFocus: true,
});
}
function testSomeMethods() {
var ms = $('#magicSuggest').magicSuggest();
ms.addToSelection([{ id: 1, name: "Mexico" }]);
console.info(ms.getSelection());
ms.disable()
}
+467
View File
@@ -0,0 +1,467 @@
// Type definitions for MagicSuggest 2.1.4
// Project: http://nicolasbize.com/magicsuggest
// Definitions by: Leonardo Chaia <http://github.com/leonardochaia>
// Definitions: http://github.com/leonardochaia/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface JQuery {
/**
* Initialize MagicSuggest on this selector
*/
magicSuggest(configurationObject?: MagicSuggest.Configuration): MagicSuggest.Instance;
}
declare module MagicSuggest {
interface Configuration {
/********** CONFIGURATION PROPERTIES ************/
/**
* Restricts or allows the user to validate typed entries.
* Defaults to true.
*/
allowFreeEntries?: boolean;
/**
* Restricts or allows the user to add the same entry more than once
* Defaults to false.
*/
allowDuplicates?: boolean;
/**
* Additional config object passed to each $.ajax call
*/
ajaxConfig?: JQueryAjaxSettings;
/**
* If a single suggestion comes out, it is preselected.
*/
autoSelect?: boolean;
/**
* Auto select the first matching item with multiple items shown
*/
selectFirst?: boolean;
/**
* Allow customization of query parameter
*/
queryParam?: string;
/**
* A function triggered just before the ajax request is sent, similar to jQuery
*/
beforeSend?: () => void;
/**
* A custom CSS class to apply to the field's underlying element.
*/
cls?: string;
/**
* JSON Data source used to populate the combo box. 3 options are available here:
* No Data Source (default)
* When left null, the combo box will not suggest anything. It can still enable the user to enter
* multiple entries if allowFreeEntries is * set to true (default).
* Static Source
* You can pass an array of JSON objects, an array of strings or even a single CSV string as the
* data source.For ex. data: [* {id:0,name:"Paris"}, {id: 1, name: "New York"}]
* You can also pass any json object with the results property containing the json array.
* Url
* You can pass the url from which the component will fetch its JSON data.Data will be fetched
* using a POST ajax request that will * include the entered text as 'query' parameter. The results
* fetched from the server can be:
* - an array of JSON objects (ex: [{id:...,name:...},{...}])
* - a string containing an array of JSON objects ready to be parsed (ex: "[{id:...,name:...},{...}]")
* - a JSON object whose data will be contained in the results property
* (ex: {results: [{id:...,name:...},{...}]
* Function
* You can pass a function which returns an array of JSON objects (ex: [{id:...,name:...},{...}])
* The function can return the JSON data or it can use the first argument as function to handle the data.
* Only one (callback function or return value) is needed for the function to succeed.
* See the following example:
* function (response) { var myjson = [{name: 'test', id: 1}]; response(myjson); return myjson; }
*/
data?: any;
/**
* Additional parameters to the ajax call
*/
dataUrlParams?: Object;
/**
* Start the component in a disabled state.
*/
disabled?: boolean;
/**
* Name of JSON object property that defines the disabled behaviour
*/
disabledField?: string;
/**
* Name of JSON object property displayed in the combo list
*/
displayField?: string;
/**
* Set to false if you only want mouse interaction. In that case the combo will
* automatically expand on focus.
*/
editable?: boolean;
/**
* Set starting state for combo.
*/
expanded?: boolean;
/**
* Automatically expands combo on focus.
*/
expandOnFocus?: boolean;
/**
* JSON property by which the list should be grouped
*/
groupBy?: string;
/**
* Set to true to hide the trigger on the right
*/
hideTrigger?: boolean;
/**
* Set to true to highlight search input within displayed suggestions
*/
highlight?: boolean;
/**
* A custom ID for this component
*/
id?: string;
/**
* A class that is added to the info message appearing on the top-right part of the component
*/
infoMsgCls?: string;
/**
* Additional parameters passed out to the INPUT tag. Enables usage of AngularJS's custom tags for ex.
*/
inputCfg?: any;
/**
* The class that is applied to show that the field is invalid
*/
invalidCls?: string;
/**
* Set to true to filter data results according to case. Useless if the data is fetched remotely
*/
matchCase?: boolean;
/**
* Once expanded, the combo's height will take as much room as the # of available results.
* In case there are too many results displayed, this will fix the drop down height.
*/
maxDropHeight?: number;
/**
* Defines how long the user free entry can be. Set to null for no limit.
*/
maxEntryLength?: number;
/**
* A function that defines the helper text when the max entry length has been surpassed.
*/
maxEntryRenderer?: (v?: number) => void;
/**
* The maximum number of results displayed in the combo drop down at once.
*/
maxSuggestions?: number;
/**
* The maximum number of items the user can select if multiple selection is allowed.
* Set to null to remove the limit.
*/
maxSelection?: number;
/**
* A function that defines the helper text when the max selection amount has been reached. The function has a single
* parameter which is the number of selected elements.
*/
maxSelectionRenderer?: (v: number) => void;
/**
* The method used by the ajax request.
*/
method?: string;
/**
* The minimum number of characters the user must type before the combo expands and offers suggestions.
*/
minChars?: number;
/**
* A function that defines the helper text when not enough letters are set. The function has a single
* parameter which is the difference between the required amount of letters and the current one.
*/
minCharsRenderer?: (v: number) => void;
/**
* Whether or not sorting / filtering should be done remotely or locally.
* Use either 'local' or 'remote'
*/
mode?: string;
/**
* The name used as a form element.
*/
name?: string;
/**
* The text displayed when there are no suggestions.
*/
noSuggestionText?: string;
/**
* The default placeholder text when nothing has been entered
*/
placeholder?: string;
/**
* A function used to define how the items will be presented in the combo
*/
renderer?: (item: any) => void;
/**
* Whether or not this field should be required
*/
required?: boolean;
/**
* Set to true to render selection as a delimited string
*/
resultAsString?: boolean;
/**
* Text delimiter to use in a delimited string.
*/
resultAsStringDelimiter?: string;
/**
* Name of JSON object property that represents the list of suggested objects
*/
resultsField?: string;
/**
* A custom CSS class to add to a selected item
*/
selectionCls?: string;
/**
* An optional element replacement in which the selection is rendered
*/
selectionContainer?: JQuery;
/**
* Where the selected items will be displayed. Only 'right', 'bottom' and 'inner' are valid values
*/
selectionPosition?: string;
/**
* A function used to define how the items will be presented in the tag list
*/
selectionRenderer?: (item: any) => void;
/**
* Set to true to stack the selectioned items when positioned on the bottom
* Requires the selectionPosition to be set to 'bottom'
*/
selectionStacked?: boolean;
/**
* Direction used for sorting. Only 'asc' and 'desc' are valid values
*/
sortDir?: string;
/**
* name of JSON object property for local result sorting.
* Leave null if you do not wish the results to be ordered or if they are already ordered remotely.
*/
sortOrder?: string;
/**
* If set to boolean; suggestions will have to start by user input (and not simply contain it as a substring)
*/
strictSuggest?: boolean;
/**
* Custom style added to the component container.
*/
style?: string;
/**
* If set to boolean; the combo will expand / collapse when clicked upon
*/
toggleOnClick?: boolean;
/**
* Amount (in ms) between keyboard registers.
*/
typeDelay?: number;
/**
* If set to boolean; tab won't blur the component but will be registered as the ENTER key
*/
useTabKey?: boolean;
/**
* If set to boolean; using comma will validate the user's choice
*/
useCommaKey?: boolean;
/**
* Determines whether or not the results will be displayed with a zebra table style
*/
useZebraStyle?: boolean;
/**
* initial value for the field
*/
value?: any;
/**
* name of JSON object property that represents its underlying value
*/
valueField?: string;
/**
* regular expression to validate the values against
*/
vregex?: any;
/**
* type to validate against
*/
vtype?: any;
}
interface Instance {
/**
* Add one or multiple json items to the current selection
* @param items - json object or array of json objects
* @param isSilent - (optional) set to true to suppress 'selectionchange' event from being triggered
*/
addToSelection(objs: Array<any>, isSilent?: boolean): void;
/**
* Clears the current selection
* @param isSilent - (optional) set to true to suppress 'selectionchange' event from being triggered
*/
clear(isSilent?: boolean): void;
/**
* Collapse the drop down part of the combo
*/
collapse(): void;
/**
* Set the component in a disabled state.
*/
disable(): void;
/**
* Empties out the combo user text
*/
empty(): void;
/**
* Set the component in a enable state.
*/
enable(): void;
/**
* Retrieve component enabled status
* @return {boolean}
*/
isDisabled(): boolean;
/**
* Checks whether the field is valid or not
* @return {boolean}
*/
isValid(): boolean;
/**
* Gets the data params for current ajax request
*/
getDataUrlParams(): Object;
/**
* Gets the name given to the form input
*/
getName(): string;
/**
* Retrieve an array of selected json objects
* @return {Array}
*/
getSelection(): Array<any>;
/**
* Retrieve the current text entered by the user
*/
getRawValue(): string;
/**
* Retrieve an array of selected values
*/
getValue(): Array<any>;
/**
* Remove one or multiples json items from the current selection
* @param items - json object or array of json objects
* @param isSilent - (optional) set to true to suppress 'selectionchange' event from being triggered
*/
removeFromSelection(items: any, isSilent: boolean): void;
/**
* Set up some combo data after it has been rendered
* @param data
*/
setData(data: any): void;
/**
* Get current data
*/
getData(): any;
/**
* Sets the name for the input field so it can be fetched in the form
* @param name
*/
setName(name: string): void;
/**
* Sets the current selection with the JSON items provided
* @param items
* @param isSilent - (optional)
*/
setSelection(items: Array<any>, isSilet?: boolean): void;
/**
* Sets a value for the combo box. Value must be an array of values with data type matching valueField one.
* @param data
*/
setValue(values: Array<any>): void;
/**
* Sets data params for subsequent ajax requests
* @param params
*/
setDataUrlParams(params: any): void;
}
}
+9
View File
@@ -1291,6 +1291,15 @@ declare module Marionette {
options: any;
/**
* Behaviors can have their own ui hash, which will be mixed into the ui
* hash of its associated View instance. ui elements defined on either the
* Behavior or the View will be made available within events and triggers.
* They also are attached directly to the Behavior and can be accessed within
* Behavior methods as this.ui.
*/
ui: any;
/**
* Any triggers you define on the Behavior will be triggered in response to the appropriate event on the view.
*/
File diff suppressed because it is too large Load Diff
+834
View File
@@ -0,0 +1,834 @@
// Type definitions for MarkerClustererPlus for Google Maps V3 2.1.1
// Project: http://github.com/mahnunchik/markerclustererplus
// Definitions by: Mathias Rodriguez <http://github.com/enanox>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../googlemaps/google.maps.d.ts" />
/**
* @name ClusterIconStyle
* @class This class represents the object for values in the <code>styles</code> array passed
* to the {@link MarkerClusterer} constructor. The element in this array that is used to
* style the cluster icon is determined by calling the <code>calculator</code> function.
*
* @property {string} url The URL of the cluster icon image file. Required.
* @property {number} height The display height (in pixels) of the cluster icon. Required.
* @property {number} width The display width (in pixels) of the cluster icon. Required.
* @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to
* where the text label is to be centered and drawn. The format is <code>[yoffset, xoffset]</code>
* where <code>yoffset</code> increases as you go down from center and <code>xoffset</code>
* increases to the right of center. The default is <code>[0, 0]</code>.
* @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the
* spot on the cluster icon that is to be aligned with the cluster position. The format is
* <code>[yoffset, xoffset]</code> where <code>yoffset</code> increases as you go down and
* <code>xoffset</code> increases to the right of the top-left corner of the icon. The default
* anchor position is the center of the cluster icon.
* @property {string} [textColor="black"] The color of the label text shown on the
* cluster icon.
* @property {number} [textSize=11] The size (in pixels) of the label text shown on the
* cluster icon.
* @property {string} [textDecoration="none"] The value of the CSS <code>text-decoration</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontWeight="bold"] The value of the CSS <code>font-weight</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontStyle="normal"] The value of the CSS <code>font-style</code>
* property for the label text shown on the cluster icon.
* @property {string} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code>
* property for the label text shown on the cluster icon.
* @property {string} [backgroundPosition="0 0"] The position of the cluster icon image
* within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code>
* (the same format as for the CSS <code>background-position</code> property). You must set
* this property appropriately when the image defined by <code>url</code> represents a sprite
* containing multiple images. Note that the position <i>must</i> be specified in px units.
*/
declare class ClusterIconStyle {
url: string;
height: number;
width: number;
anchorText: number[];
anchorIcon: number[];
textColor: string;
textSize: number;
textDecoration: string;
fontWeight: string;
fontStyle: string;
fontFamily: string;
backgroundPosition: string;
}
/**
* @name ClusterIconInfo
* @class This class is an object containing general information about a cluster icon. This is
* the object that a <code>calculator</code> function returns.
*
* @property {string} text The text of the label to be shown on the cluster icon.
* @property {number} index The index plus 1 of the element in the <code>styles</code>
* array to be used to style the cluster icon.
* @property {string} title The tooltip to display when the mouse moves over the cluster icon.
* If this value is <code>undefined</code> or <code>""</code>, <code>title</code> is set to the
* value of the <code>title</code> property passed to the MarkerClusterer.
*/
declare class ClusterIconInfo extends google.maps.OverlayView {
text: string;
index: number;
title: string;
/**
* A cluster icon.
*
* @constructor
* @extends google.maps.OverlayView
* @param {Cluster} cluster The cluster with which the icon is to be associated.
* @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons
* to use for various cluster sizes.
* @private
*/
constructor(cluster: Cluster, styles: ClusterIconStyle[]);
/**
* Adds the icon to the DOM.
*/
onAdd(): void;
/**
* Removes the icon from the DOM.
*/
onRemove(): void;
/**
* Draws the icon.
*/
draw(): void;
/**
* Hides the icon.
*/
hide(): void;
/**
* Positions and shows the icon.
*/
show(): void;
/**
* Sets the icon styles to the appropriate element in the styles array.
*
* @param {ClusterIconInfo} sums The icon label text and styles index.
*/
useStyle(sums: ClusterIconInfo[]): void;
/**
* Sets the position at which to center the icon.
*
* @param {google.maps.LatLng} center The latlng to set as the center.
*/
setCenter(center: google.maps.LatLng): void;
/**
* Creates the cssText style parameter based on the position of the icon.
*
* @param {google.maps.Point} pos The position of the icon.
* @return {string} The CSS style text.
*/
createCss(pos: google.maps.Point): string;
/**
* Returns the position at which to place the DIV depending on the latlng.
*
* @param {google.maps.LatLng} latlng The position in latlng.
* @return {google.maps.Point} The position in pixels.
*/
getPosFromLatLng_(latLng: google.maps.LatLng): google.maps.Point;
}
interface Cluster {
/**
* Creates a single cluster that manages a group of proximate markers.
* Used internally, do not call this constructor directly.
* @constructor
* @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this
* cluster is associated.
*/
new (mc: MarkerClusterer): Cluster;
/**
* Returns the number of markers managed by the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {number} The number of markers in the cluster.
*/
getSize(): number;
/**
* Returns the array of markers managed by the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {Array} The array of markers in the cluster.
*/
getMarkers(): google.maps.Marker[];
/**
* Returns the center of the cluster. You can call this from
* a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
* for the <code>MarkerClusterer</code> object.
*
* @return {google.maps.LatLng} The center of the cluster.
*/
getCenter(): google.maps.LatLng;
/**
* Returns the map with which the cluster is associated.
*
* @return {google.maps.Map} The map.
* @ignore
*/
getMap(): google.maps.Map;
/**
* Returns the <code>MarkerClusterer</code> object with which the cluster is associated.
*
* @return {MarkerClusterer} The associated marker clusterer.
* @ignore
*/
getMarkerClusterer(): MarkerClusterer;
/**
* Returns the bounds of the cluster.
*
* @return {google.maps.LatLngBounds} the cluster bounds.
* @ignore
*/
getBounds(): google.maps.LatLngBounds;
/**
* Removes the cluster from the map.
*
* @ignore
*/
remove(): void;
/**
* Adds a marker to the cluster.
*
* @param {google.maps.Marker} marker The marker to be added.
* @return {boolean} True if the marker was added.
* @ignore
*/
addMarker(marker: google.maps.Marker): boolean;
/**
* Determines if a marker lies within the cluster's bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker lies in the bounds.
* @ignore
*/
isMarkerInClusterBounds(marker: google.maps.Marker): boolean;
/**
* Calculates the extended bounds of the cluster with the grid.
*/
calculateBounds_(): void;
/**
* Updates the cluster icon.
*/
updateIcon_(): void;
/**
* Determines if a marker has already been added to the cluster.
*
* @param {google.maps.Marker} marker The marker to check.
* @return {boolean} True if the marker has already been added.
*/
isMarkerAlreadyAdded_(marker: google.maps.Marker): boolean;
}
/**
* @name MarkerClustererOptions
* @class This class represents the optional parameter passed to
* the {@link MarkerClusterer} constructor.
* @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square.
* @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or
* <code>null</code> if clustering is to be enabled at all zoom levels.
* @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is
* clicked. You may want to set this to <code>false</code> if you have installed a handler
* for the <code>click</code> event and it deals with zooming on its own.
* @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be
* the average position of all markers in the cluster. If set to <code>false</code>, the
* cluster marker is positioned at the location of the first marker added to the cluster.
* @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster
* before the markers are hidden and a cluster marker appears.
* @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You
* may want to set this to <code>true</code> to ensure that hidden markers are not included
* in the marker count that appears on a cluster marker (this count is the value of the
* <code>text</code> property of the result returned by the default <code>calculator</code>).
* If set to <code>true</code> and you change the visibility of a marker being clustered, be
* sure to also call <code>MarkerClusterer.repaint()</code>.
* @property {string} [title=""] The tooltip to display when the mouse moves over a cluster
* marker. (Alternatively, you can use a custom <code>calculator</code> function to specify a
* different tooltip for each cluster marker.)
* @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine
* the text to be displayed on a cluster marker and the index indicating which style to use
* for the cluster marker. The input parameters for the function are (1) the array of markers
* represented by a cluster marker and (2) the number of cluster icon styles. It returns a
* {@link ClusterIconInfo} object. The default <code>calculator</code> returns a
* <code>text</code> property which is the number of markers in the cluster and an
* <code>index</code> property which is one higher than the lowest integer such that
* <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles
* array, whichever is less. The <code>styles</code> array element used has an index of
* <code>index</code> minus 1. For example, the default <code>calculator</code> returns a
* <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code>
* for a cluster icon representing 125 markers so the element used in the <code>styles</code>
* array is <code>2</code>. A <code>calculator</code> may also return a <code>title</code>
* property that contains the text of the tooltip to be used for the cluster marker. If
* <code>title</code> is not defined, the tooltip is set to the value of the <code>title</code>
* property for the MarkerClusterer.
* @property {string} [clusterClass="cluster"] The name of the CSS class defining general styles
* for the cluster markers. Use this class to define CSS styles that are not set up by the code
* that processes the <code>styles</code> array.
* @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles
* of the cluster markers to be used. The element to be used to style a given cluster marker
* is determined by the function defined by the <code>calculator</code> property.
* The default is an array of {@link ClusterIconStyle} elements whose properties are derived
* from the values for <code>imagePath</code>, <code>imageExtension</code>, and
* <code>imageSizes</code>.
* @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that
* have sizes that are some multiple (typically double) of their actual display size. Icons such
* as these look better when viewed on high-resolution monitors such as Apple's Retina displays.
* Note: if this property is <code>true</code>, sprites cannot be used as cluster icons.
* @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the
* number of markers to be processed in a single batch when using a browser other than
* Internet Explorer (for Internet Explorer, use the batchSizeIE property instead).
* @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is
* being used, markers are processed in several batches with a small delay inserted between
* each batch in an attempt to avoid Javascript timeout errors. Set this property to the
* number of markers to be processed in a single batch; select as high a number as you can
* without causing a timeout error in the browser. This number might need to be as low as 100
* if 15,000 markers are being managed, for example.
* @property {string} [imagePath=MarkerClusterer.IMAGE_PATH]
* The full URL of the root name of the group of image files to use for cluster icons.
* The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code>
* where n is the image file number (1, 2, etc.).
* @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION]
* The extension name for the cluster icon image files (e.g., <code>"png"</code> or
* <code>"jpg"</code>).
* @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES]
* An array of numbers containing the widths of the group of
* <code>imagePath</code>n.<code>imageExtension</code> image files.
* (The images are assumed to be square.)
**/
interface MarkerClustererOptions {
gridSize: number;
maxZoom: number;
zoomOnClick: boolean;
averageCenter: boolean;
minimumClusterSize: number;
ignoreHidden: boolean;
title: string;
calculator(): Function;
clusterClass: string;
styles: ClusterIconStyle[];
enableRetinaIcons: boolean;
batchSize: number;
batchSizeIE: number;
imagePath: string;
imageExtension: string;
imageSizes: number[];
}
interface MarkerClusterer extends google.maps.OverlayView {
/**
* Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}.
* @constructor
* @extends google.maps.OverlayView
* @param {google.maps.Map} map The Google map to attach to.
* @param {Array.<google.maps.Marker>} [opt_markers] The markers to be added to the cluster.
* @param {MarkerClustererOptions} [opt_options] The optional parameters.
*/
new (map: google.maps.Map, opt_markers: google.maps.Marker[], opt_options?: MarkerClustererOptions): MarkerClusterer;
/**
* Implementation of the onAdd interface method.
* @ignore
*/
onAdd(): void;
/**
* Implementation of the onRemove interface method.
* Removes map event listeners and all cluster icons from the DOM.
* All managed markers are also put back on the map.
* @ignore
*/
onRemove(): void;
/**
* Implementation of the draw interface method.
* @ignore
*/
draw(): void;
/**
* Sets up the styles object.
*/
setupStyles_(): void;
/**
* Fits the map to the bounds of the markers managed by the clusterer.
*/
fitMapToMarkers(): void;
/**
* Returns the value of the <code>gridSize</code> property.
*
* @return {number} The grid size.
*/
getGridSize(): number;
/**
* Sets the value of the <code>gridSize</code> property.
*
* @param {number} gridSize The grid size.
*/
setGridSize(gridSize: number): void;
/**
* Returns the value of the <code>minimumClusterSize</code> property.
*
* @return {number} The minimum cluster size.
*/
getMinimumClusterSize(): number;
/**
* Sets the value of the <code>minimumClusterSize</code> property.
*
* @param {number} minimumClusterSize The minimum cluster size.
*/
setMinimumClusterSize(minimumClusterSize: number): void;
/**
* Returns the value of the <code>maxZoom</code> property.
*
* @return {number} The maximum zoom level.
*/
getMaxZoom(): number;
/**
* Sets the value of the <code>maxZoom</code> property.
*
* @param {number} maxZoom The maximum zoom level.
*/
setMaxZoom(maxZoom: number): void;
/**
* Returns the value of the <code>styles</code> property.
*
* @return {Array} The array of styles defining the cluster markers to be used.
*/
getStyles(): ClusterIconStyle[];
/**
* Sets the value of the <code>styles</code> property.
*
* @param {Array.<ClusterIconStyle>} styles The array of styles to use.
*/
setStyles(styles: ClusterIconStyle[]): void;
/**
* Returns the value of the <code>title</code> property.
*
* @return {string} The content of the title text.
*/
getTitle(): string;
/**
* Sets the value of the <code>title</code> property.
*
* @param {string} title The value of the title property.
*/
setTitle(title: string): void;
/**
* Returns the value of the <code>zoomOnClick</code> property.
*
* @return {boolean} True if zoomOnClick property is set.
*/
getZoomOnClick(): boolean;
/**
* Sets the value of the <code>zoomOnClick</code> property.
*
* @param {boolean} zoomOnClick The value of the zoomOnClick property.
*/
setZoomOnClick(zoomOnClick: boolean): void;
/**
* Returns the value of the <code>averageCenter</code> property.
*
* @return {boolean} True if averageCenter property is set.
*/
getAverageCenter(): boolean;
/**
* Sets the value of the <code>averageCenter</code> property.
*
* @param {boolean} averageCenter The value of the averageCenter property.
*/
setAverageCenter(averageCenter: boolean): void;
/**
* Returns the value of the <code>ignoreHidden</code> property.
*
* @return {boolean} True if ignoreHidden property is set.
*/
getIgnoreHidden(): boolean;
/**
* Sets the value of the <code>ignoreHidden</code> property.
*
* @param {boolean} ignoreHidden The value of the ignoreHidden property.
*/
setIgnoreHidden(ignoreHidden: boolean): void;
/**
* Returns the value of the <code>enableRetinaIcons</code> property.
*
* @return {boolean} True if enableRetinaIcons property is set.
*/
getEnableRetinaIcons(): boolean;
/**
* Sets the value of the <code>enableRetinaIcons</code> property.
*
* @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property.
*/
setEnableRetinaIcons(enableRetinaIcons: boolean): void;
/**
* Returns the value of the <code>imageExtension</code> property.
*
* @return {string} The value of the imageExtension property.
*/
getImageExtension(): string;
/**
* Sets the value of the <code>imageExtension</code> property.
*
* @param {string} imageExtension The value of the imageExtension property.
*/
setImageExtension(imageExtension: string): void;
/**
* Returns the value of the <code>imagePath</code> property.
*
* @return {string} The value of the imagePath property.
*/
getImagePath(): string;
/**
* Sets the value of the <code>imagePath</code> property.
*
* @param {string} imagePath The value of the imagePath property.
*/
setImagePath(imagePath: string): void;
/**
* Returns the value of the <code>imageSizes</code> property.
*
* @return {Array} The value of the imageSizes property.
*/
getImageSizes(): number[];
/**
* Sets the value of the <code>imageSizes</code> property.
*
* @param {Array} imageSizes The value of the imageSizes property.
*/
setImageSizes(imageSizes: number[]): void;
/**
* Returns the value of the <code>calculator</code> property.
*
* @return {function} the value of the calculator property.
*/
getCalculator(): Function;
/**
* Sets the value of the <code>calculator</code> property.
*
* @param {function(Array.<google.maps.Marker>, number)} calculator The value
* of the calculator property.
*/
setCalculator(calculator: (marker: google.maps.Marker, value: number) => Function): void;
/**
* Sets the value of the <code>hideLabel</code> property.
*
* @param {boolean} printable The value of the hideLabel property.
*/
setHideLabel(printable: boolean): void;
/**
* Returns the value of the <code>hideLabel</code> property.
*
* @return {boolean} the value of the hideLabel property.
*/
getHideLabel(): boolean;
/**
* Returns the value of the <code>batchSizeIE</code> property.
*
* @return {number} the value of the batchSizeIE property.
*/
getBatchSizeIE(): number;
/**
* Sets the value of the <code>batchSizeIE</code> property.
*
* @param {number} batchSizeIE The value of the batchSizeIE property.
*/
setBatchSizeIE(batchSizeIE: number): void;
/**
* Returns the value of the <code>clusterClass</code> property.
*
* @return {string} the value of the clusterClass property.
*/
getClusterClass(): string;
/**
* Sets the value of the <code>clusterClass</code> property.
*
* @param {string} clusterClass The value of the clusterClass property.
*/
setClusterClass(clusterClass: string): void;
/**
* Returns the array of markers managed by the clusterer.
*
* @return {Array} The array of markers managed by the clusterer.
*/
getMarkers(): google.maps.Marker[];
/**
* Returns the number of markers managed by the clusterer.
*
* @return {number} The number of markers.
*/
getTotalMarkers(): number;
/**
* Returns the current array of clusters formed by the clusterer.
*
* @return {Array} The array of clusters formed by the clusterer.
*/
getClusters(): Cluster[];
/**
* Returns the number of clusters formed by the clusterer.
*
* @return {number} The number of clusters formed by the clusterer.
*/
getTotalClusters(): number;
/**
* Adds a marker to the clusterer. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>.
*
* @param {google.maps.Marker} marker The marker to add.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
*/
addMarker(marker: google.maps.Marker, opt_nodraw: boolean): void;
/**
* Adds an array of markers to the clusterer. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>.
*
* @param {Array.<google.maps.Marker>} markers The markers to add.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
*/
addMarkers(markers: google.maps.Marker[], opt_nodraw: boolean): void;
/**
* Pushes a marker to the clusterer.
*
* @param {google.maps.Marker} marker The marker to add.
*/
pushMarkerTo_(marker: google.maps.Marker): void;
/**
* Removes a marker from the cluster and map. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the
* marker was removed from the clusterer.
*
* @param {google.maps.Marker} marker The marker to remove.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
* @param {boolean} [opt_noMapRemove] Set to <code>true</code> to prevent removal from map but still removing from cluster management
* @return {boolean} True if the marker was removed from the clusterer.
*/
removeMarker(marker: google.maps.Marker, opt_nodraw: boolean, noMapRemove: boolean): boolean;
/**
* Removes an array of markers from the cluster and map. The clusters are redrawn unless
* <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers
* were removed from the clusterer.
*
* @param {Array.<google.maps.Marker>} markers The markers to remove.
* @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
* @param {boolean} [opt_noMapRemove] Set to <code>true</code> to prevent removal from map but still removing from cluster management
* @return {boolean} True if markers were removed from the clusterer.
*/
removeMarkers(markers: google.maps.Marker[], opt_nodraw: boolean, opt_noMapRemove: boolean): boolean;
/**
* Removes a marker and returns true if removed, false if not.
*
* @param {google.maps.Marker} marker The marker to remove
* @param {boolean} removeFromMap set to <code>true</code> to explicitly remove from map as well as cluster manangement
* @return {boolean} Whether the marker was removed or not
*/
removeMarker_(marker: google.maps.Marker, removeFromMap: boolean): boolean;
/**
* Removes all clusters and markers from the map and also removes all markers
* managed by the clusterer.
*/
clearMarkers(): void;
/**
* Recalculates and redraws all the marker clusters from scratch.
* Call this after changing any properties.
*/
repaint(): void;
/**
* Returns the current bounds extended by the grid size.
*
* @param {google.maps.LatLngBounds} bounds The bounds to extend.
* @return {google.maps.LatLngBounds} The extended bounds.
* @ignore
*/
getExtendedBounds(bounds: google.maps.LatLngBounds): google.maps.LatLngBounds;
/**
* Redraws all the clusters.
*/
redraw_(): void;
/**
* Removes all clusters from the map. The markers are also removed from the map
* if <code>opt_hide</code> is set to <code>true</code>.
*
* @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers
* from the map.
*/
resetViewport_(opt_hide: boolean): void;
/**
* Calculates the distance between two latlng locations in km.
*
* @param {google.maps.LatLng} p1 The first lat lng point.
* @param {google.maps.LatLng} p2 The second lat lng point.
* @return {number} The distance between the two points in km.
* @see http://www.movable-type.co.uk/scripts/latlong.html
*/
distanceBetweenPoints_(p1: google.maps.LatLng, p2: google.maps.LatLng): number;
/**
* Determines if a marker is contained in a bounds.
*
* @param {google.maps.Marker} marker The marker to check.
* @param {google.maps.LatLngBounds} bounds The bounds to check against.
* @return {boolean} True if the marker is in the bounds.
*/
isMarkerInBounds_(marker: google.maps.Marker, bounds: google.maps.LatLngBounds): boolean;
/**
* Adds a marker to a cluster, or creates a new cluster.
*
* @param {google.maps.Marker} marker The marker to add.
*/
addToClosestCluster_(marker: google.maps.Marker): void;
/**
* Creates the clusters. This is done in batches to avoid timeout errors
* in some browsers when there is a huge number of markers.
*
* @param {number} iFirst The index of the first marker in the batch of
* markers to be added to clusters.
*/
createClusters_(iFirst: number): void;
/**
* Extends an object's prototype by another's.
*
* @param {Object} obj1 The object to be extended.
* @param {Object} obj2 The object to extend with.
* @return {Object} The new extended object.
* @ignore
*/
extend(obj1: Object, obj2: Object): Object;
/**
* The default function for determining the label text and style
* for a cluster icon.
*
* @param {Array.<google.maps.Marker>} markers The array of markers represented by the cluster.
* @param {number} numStyles The number of marker styles available.
* @return {ClusterIconInfo} The information resource for the cluster.
* @constant
* @ignore
*/
CALCULATOR(markers: google.maps.Marker[], numStyles: number): ClusterIconInfo;
/**
* The number of markers to process in one batch.
*
* @type {number}
* @constant
*/
BATCH_SIZE: number;
/**
* The number of markers to process in one batch (IE only).
*
* @type {number}
* @constant
*/
BATCH_SIZE_IE: number;
/**
* The default root name for the marker cluster images.
*
* @type {string}
* @constant
*/
IMAGE_PATH: string;
/**
* The default extension name for the marker cluster images.
*
* @type {string}
* @constant
*/
IMAGE_EXTENSION: string;
/**
* The default array of sizes for the marker cluster images.
*
* @type {Array.<number>}
* @constant
*/
IMAGE_SIZES: number[];
}
declare var MarkerClusterer: MarkerClusterer;
interface String {
trim(): string;
}
+1 -1
View File
@@ -272,7 +272,7 @@ Posts.allow({
Posts.deny({
update: function (userId, docs, fields, modifier) {
// can't change owners
return docs.userId = userId;
return docs.userId !== userId;
},
remove: function (userId, doc) {
// can't remove locked documents
+51 -51
View File
@@ -16,17 +16,17 @@ interface JSONable {
interface EJSON extends EJSONable {}
declare module Match {
var Any;
var String;
var Integer;
var Boolean;
var undefined;
var Any:any;
var String:any;
var Integer:any;
var Boolean:any;
var undefined:any;
//function null(); // not allowed in TypeScript
var Object;
function Optional(pattern):boolean;
function ObjectIncluding(dico):boolean;
function OneOf(...patterns);
function Where(condition);
var Object:any;
function Optional(pattern:any):boolean;
function ObjectIncluding(dico:any):boolean;
function OneOf(...patterns:any[]):any;
function Where(condition:any):any;
}
declare module Meteor {
@@ -89,8 +89,8 @@ declare module Meteor {
}
interface Tinytest {
add(name:string, func:Function);
addAsync(name:string, func:Function);
add(name:string, func:Function):any;
addAsync(name:string, func:Function):any;
}
enum StatusEnum {
@@ -145,9 +145,9 @@ declare module Mongo {
MONGO
}
interface AllowDenyOptions {
insert?: (userId:string, doc) => boolean;
update?: (userId, doc, fieldNames, modifier) => boolean;
remove?: (userId, doc) => boolean;
insert?: (userId:string, doc:any) => boolean;
update?: (userId:string, doc:any, fieldNames:string[], modifier:any) => boolean;
remove?: (userId:string, doc:any) => boolean;
fetch?: string[];
transform?: Function;
}
@@ -184,10 +184,10 @@ declare module HTTP {
declare module Email {
interface EmailMessage {
from: string;
to: any; // string or string[]
cc?: any; // string or string[]
bcc?: any; // string or string[]
replyTo?: any; // string or string[]
to: string|string[];
cc?: string|string[];
bcc?: string|string[];
replyTo?: string|string[];
subject: string;
text?: string;
html?: string;
@@ -197,14 +197,14 @@ declare module Email {
declare module DDP {
interface DDPStatic {
subscribe(name, ...rest);
call(method:string, ...parameters):void;
apply(method:string, ...parameters):void;
methods(IMeteorMethodsDictionary);
subscribe(name:string, ...rest:any[]):void;
call(method:string, ...parameters:any[]):void;
apply(method:string, ...parameters:any[]):void;
methods(IMeteorMethodsDictionary:any):any;
status():DDPStatus;
reconnect();
disconnect();
onReconnect();
reconnect():void;
disconnect():void;
onReconnect():void;
}
interface DDPStatus {
@@ -344,7 +344,7 @@ declare module Accounts {
declare module App {
function accessRule(domainRule: string, options?: {
launchExternal?: boolean;
}); /** TODO: add return value **/
}):any; /** TODO: add return value **/
function configurePlugin(pluginName: string, config: Object): void;
function icons(icons: Object): void;
function info(options: {
@@ -393,7 +393,7 @@ declare module Blaze {
findAll(selector: string): Blaze.TemplateInstance[];
firstNode: Object;
lastNode: Object;
subscribe(name: string, ...args): Meteor.SubscriptionHandle;
subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle;
subscriptionsReady(): boolean;
view: Object;
}
@@ -475,7 +475,7 @@ declare module Meteor {
wait?: boolean;
onResultReceived?: Function;
}, asyncCallback?: Function): any;
function call(name: string, ...args): any;
function call(name: string, ...args: any[]): any;
function clearInterval(id: number): void;
function clearTimeout(id: number): void;
function disconnect(): void;
@@ -503,7 +503,7 @@ declare module Meteor {
var settings: {[id:string]: any};
function startup(func: Function): void;
function status(): Meteor.StatusEnum;
function subscribe(name: string, ...args): Meteor.SubscriptionHandle;
function subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle;
function user(): Meteor.User;
function userId(): string;
var users: Mongo.Collection<User>;
@@ -521,16 +521,16 @@ declare module Mongo {
}
interface Collection<T> {
allow(options: {
insert?: (userId:string, doc) => boolean;
update?: (userId, doc, fieldNames, modifier) => boolean;
remove?: (userId, doc) => boolean;
insert?: (userId:string, doc:any) => boolean;
update?: (userId:string, doc:any, fieldNames:string[], modifier:any) => boolean;
remove?: (userId:string, doc:any) => boolean;
fetch?: string[];
transform?: Function;
}): boolean;
deny(options: {
insert?: (userId:string, doc) => boolean;
update?: (userId, doc, fieldNames, modifier) => boolean;
remove?: (userId, doc) => boolean;
insert?: (userId:string, doc:any) => boolean;
update?: (userId:string, doc:any, fieldNames:string[], modifier:any) => boolean;
remove?: (userId:string, doc:any) => boolean;
fetch?: string[];
transform?: Function;
}): boolean;
@@ -684,30 +684,30 @@ interface CompileStepStatic {
}
interface CompileStep {
addAsset(options: {
}, path: string, data: any /** Buffer **/ | string); /** TODO: add return value **/
}, path: string, data: any /** Buffer **/ | string): any; /** TODO: add return value **/
addHtml(options: {
section?: string;
data?: string;
}); /** TODO: add return value **/
}): any; /** TODO: add return value **/
addJavaScript(options: {
path?: string;
data?: string;
sourcePath?: string;
}); /** TODO: add return value **/
}): any; /** TODO: add return value **/
addStylesheet(options: {
}, path: string, data: string, sourceMap: string); /** TODO: add return value **/
arch; /** TODO: add return value **/
declaredExports; /** TODO: add return value **/
}, path: string, data: string, sourceMap: string): any; /** TODO: add return value **/
arch: any; /** TODO: add return value **/
declaredExports: any; /** TODO: add return value **/
error(options: {
}, message: string, sourcePath?: string, line?: number, func?: string); /** TODO: add return value **/
fileOptions; /** TODO: add return value **/
fullInputPath; /** TODO: add return value **/
inputPath; /** TODO: add return value **/
inputSize; /** TODO: add return value **/
packageName; /** TODO: add return value **/
pathForSourceMap; /** TODO: add return value **/
}, message: string, sourcePath?: string, line?: number, func?: string): any; /** TODO: add return value **/
fileOptions: any; /** TODO: add return value **/
fullInputPath: any; /** TODO: add return value **/
inputPath: any; /** TODO: add return value **/
inputSize: any; /** TODO: add return value **/
packageName: any; /** TODO: add return value **/
pathForSourceMap: any; /** TODO: add return value **/
read(n?: number): any;
rootOutputPath; /** TODO: add return value **/
rootOutputPath: any; /** TODO: add return value **/
}
declare var PackageAPI: PackageAPIStatic;
@@ -777,5 +777,5 @@ interface Template {
}
declare function MethodInvocation(options: {
}); /** TODO: add return value **/
}): any; /** TODO: add return value **/
declare function check(value: any, pattern: any): void;
+28 -1
View File
@@ -24,6 +24,18 @@ function test_context() {
});
}
function test_suite() {
suite('some context', () => { });
suite.only('some context', () => { });
suite.skip('some context', () => { });
suite('some context', function() {
this.timeout(2000);
});
}
function test_it() {
it('does something', () => { });
@@ -39,6 +51,21 @@ function test_it() {
});
}
function test_test() {
test('does something', () => { });
test('does something', (done) => { done(); });
test.only('does something', () => { });
test.skip('does something', () => { });
test('does something', function () {
this.timeout(2000);
});
}
function test_before() {
before(() => { });
@@ -221,4 +248,4 @@ function test_run_withOnComplete() {
instance.run((failures: number): void => {
console.log(failures);
});
}
}
+22 -3
View File
@@ -52,7 +52,7 @@ interface MochaDone {
declare var mocha: Mocha;
declare var describe : {
declare var describe: {
(description: string, spec: () => void): void;
only(description: string, spec: () => void): void;
skip(description: string, spec: () => void): void;
@@ -60,12 +60,20 @@ declare var describe : {
}
// alias for `describe`
declare var context : {
declare var context: {
(contextTitle: string, spec: () => void): void;
only(contextTitle: string, spec: () => void): void;
skip(contextTitle: string, spec: () => void): void;
timeout(ms: number): void;
}
};
// alias for `describe`
declare var suite: {
(suiteTitle: string, spec: () => void): void;
only(suiteTitle: string, spec: () => void): void;
skip(suiteTitle: string, spec: () => void): void;
timeout(ms: number): void;
};
declare var it: {
(expectation: string, assertion?: () => void): void;
@@ -77,6 +85,17 @@ declare var it: {
timeout(ms: number): void;
};
// alias for `it`
declare var test: {
(expectation: string, assertion?: () => void): void;
(expectation: string, assertion?: (done: MochaDone) => void): void;
only(expectation: string, assertion?: () => void): void;
only(expectation: string, assertion?: (done: MochaDone) => void): void;
skip(expectation: string, assertion?: () => void): void;
skip(expectation: string, assertion?: (done: MochaDone) => void): void;
timeout(ms: number): void;
};
declare function before(action: () => void): void;
declare function before(action: (done: MochaDone) => void): void;
+30 -2
View File
@@ -12,14 +12,42 @@ var d = moment.tz("May 12th 2014 8PM", "MMM Do YYYY hA", true, "America/Toronto"
a.tz();
var arr = [2013, 5, 1],
var num = 1367337600000,
arr = [2013, 5, 1],
str = "2013-12-01",
obj = { year : 2013, month : 5, day : 1 };
date = new Date(2013, 4, 1),
mo = moment([2013, 4, 1]),
obj = { year : 2013, month : 5, day : 1 },
format = "YYYY-MM-DD",
formats = ["YYYY-MM-DD", "YYYY/MM/DD"],
formatsIncludingSpecial = ["YYYY-MM-DD", moment.ISO_8601],
language = "en";
moment.tz();
moment.tz("America/Los_Angeles");
moment.tz(num, "America/Los_Angeles");
moment.tz(arr, "America/Los_Angeles");
moment.tz(str, "America/Los_Angeles");
moment.tz(str, format, "America/Los_Angeles");
moment.tz(str, format, true, "America/Los_Angeles");
moment.tz(str, format, language, "America/Los_Angeles");
moment.tz(str, format, language, true, "America/Los_Angeles");
moment.tz(str, formats, "America/Los_Angeles");
moment.tz(str, formats, true, "America/Los_Angeles");
moment.tz(str, formats, language, "America/Los_Angeles");
moment.tz(str, formats, language, true, "America/Los_Angeles");
moment.tz(str, moment.ISO_8601, "America/Los_Angeles");
moment.tz(str, moment.ISO_8601, true, "America/Los_Angeles");
moment.tz(str, moment.ISO_8601, language, "America/Los_Angeles");
moment.tz(str, moment.ISO_8601, language, true, "America/Los_Angeles");
moment.tz(str, formatsIncludingSpecial, "America/Los_Angeles");
moment.tz(str, formatsIncludingSpecial, true, "America/Los_Angeles");
moment.tz(str, formatsIncludingSpecial, language, "America/Los_Angeles");
moment.tz(str, formatsIncludingSpecial, language, true, "America/Los_Angeles");
moment.tz(date, "America/Los_Angeles");
moment.tz(mo, "America/Los_Angeles");
moment.tz(obj, "America/Los_Angeles");
moment.tz.zone('America/Los_Angeles').abbr(1403465838805);
+17 -1
View File
@@ -28,11 +28,27 @@ interface MomentZone {
}
interface MomentTimezone {
(): moment.Moment;
(timezone: string): moment.Moment;
(date: number, timezone: string): moment.Moment;
(date: number[], timezone: string): moment.Moment;
(date: string, timezone: string): moment.Moment;
(date: string, format: string, timezone: string): moment.Moment;
(date: string, format: string, useStrict: boolean, timezone: string): moment.Moment;
(date: string, format: string, strict: boolean, timezone: string): moment.Moment;
(date: string, format: string, language: string, timezone: string): moment.Moment;
(date: string, format: string, language: string, strict: boolean, timezone: string): moment.Moment;
(date: string, formats: string[], timezone: string): moment.Moment;
(date: string, formats: string[], strict: boolean, timezone: string): moment.Moment;
(date: string, formats: string[], language: string, timezone: string): moment.Moment;
(date: string, formats: string[], language: string, strict: boolean, timezone: string): moment.Moment;
(date: string, specialFormat: () => void, timezone: string): moment.Moment;
(date: string, specialFormat: () => void, strict: boolean, timezone: string): moment.Moment;
(date: string, specialFormat: () => void, language: string, timezone: string): moment.Moment;
(date: string, specialFormat: () => void, language: string, strict: boolean, timezone: string): moment.Moment;
(date: string, formatsIncludingSpecial: any[], timezone: string): moment.Moment;
(date: string, formatsIncludingSpecial: any[], strict: boolean, timezone: string): moment.Moment;
(date: string, formatsIncludingSpecial: any[], language: string, timezone: string): moment.Moment;
(date: string, formatsIncludingSpecial: any[], language: string, strict: boolean, timezone: string): moment.Moment;
(date: Date, timezone: string): moment.Moment;
(date: moment.Moment, timezone: string): moment.Moment;
(date: Object, timezone: string): moment.Moment;
+1
View File
@@ -188,6 +188,7 @@ moment(1318874398806).valueOf();
moment(1318874398806).unix();
moment([2000]).isLeapYear();
moment().zone();
moment().utcOffset();
moment("2012-2", "YYYY-MM").daysInMonth();
moment([2011, 2, 12]).isDST();
+482
View File
@@ -0,0 +1,482 @@
// Type definitions for Moment.js 2.8.0
// Project: https://github.com/timrwood/moment
// Definitions by: Michael Lakerveld <https://github.com/Lakerfield>, Aaron King <https://github.com/kingdango>, Hiroki Horiuchi <https://github.com/horiuchi>, Dick van den Brink <https://github.com/DickvdBrink>, Adi Dahiya <https://github.com/adidahiya>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module moment {
interface MomentInput {
years?: number;
y?: number;
months?: number;
M?: number;
weeks?: number;
w?: number;
days?: number;
d?: number;
hours?: number;
h?: number;
minutes?: number;
m?: number;
seconds?: number;
s?: number;
milliseconds?: number;
ms?: number;
}
interface Duration {
humanize(withSuffix?: boolean): string;
as(units: string): number;
milliseconds(): number;
asMilliseconds(): number;
seconds(): number;
asSeconds(): number;
minutes(): number;
asMinutes(): number;
hours(): number;
asHours(): number;
days(): number;
asDays(): number;
months(): number;
asMonths(): number;
years(): number;
asYears(): number;
add(n: number, p: string): Duration;
add(n: number): Duration;
add(d: Duration): Duration;
subtract(n: number, p: string): Duration;
subtract(n: number): Duration;
subtract(d: Duration): Duration;
toISOString(): string;
}
interface Moment {
format(format: string): string;
format(): string;
fromNow(withoutSuffix?: boolean): string;
startOf(unitOfTime: string): Moment;
endOf(unitOfTime: string): Moment;
/**
* Mutates the original moment by adding time. (deprecated in 2.8.0)
*
* @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc)
* @param amount the amount you want to add
*/
add(unitOfTime: string, amount: number): Moment;
/**
* Mutates the original moment by adding time.
*
* @param amount the amount you want to add
* @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc)
*/
add(amount: number, unitOfTime: string): Moment;
/**
* Mutates the original moment by adding time. Note that the order of arguments can be flipped.
*
* @param amount the amount you want to add
* @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc)
*/
add(amount: string, unitOfTime: string): Moment;
/**
* Mutates the original moment by adding time.
*
* @param objectLiteral an object literal that describes multiple time units {days:7,months:1}
*/
add(objectLiteral: MomentInput): Moment;
/**
* Mutates the original moment by adding time.
*
* @param duration a length of time
*/
add(duration: Duration): Moment;
/**
* Mutates the original moment by subtracting time. (deprecated in 2.8.0)
*
* @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc)
* @param amount the amount you want to subtract
*/
subtract(unitOfTime: string, amount: number): Moment;
/**
* Mutates the original moment by subtracting time.
*
* @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc)
* @param amount the amount you want to subtract
*/
subtract(amount: number, unitOfTime: string): Moment;
/**
* Mutates the original moment by subtracting time. Note that the order of arguments can be flipped.
*
* @param amount the amount you want to add
* @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc)
*/
subtract(amount: string, unitOfTime: string): Moment;
/**
* Mutates the original moment by subtracting time.
*
* @param objectLiteral an object literal that describes multiple time units {days:7,months:1}
*/
subtract(objectLiteral: MomentInput): Moment;
/**
* Mutates the original moment by subtracting time.
*
* @param duration a length of time
*/
subtract(duration: Duration): Moment;
calendar(): string;
calendar(start: Moment): string;
clone(): Moment;
/**
* @return Unix timestamp, or milliseconds since the epoch.
*/
valueOf(): number;
local(): Moment; // current date/time in local mode
utc(): Moment; // current date/time in UTC mode
isValid(): boolean;
year(y: number): Moment;
year(): number;
quarter(): number;
quarter(q: number): Moment;
month(M: number): Moment;
month(M: string): Moment;
month(): number;
day(d: number): Moment;
day(d: string): Moment;
day(): number;
date(d: number): Moment;
date(): number;
hour(h: number): Moment;
hour(): number;
hours(h: number): Moment;
hours(): number;
minute(m: number): Moment;
minute(): number;
minutes(m: number): Moment;
minutes(): number;
second(s: number): Moment;
second(): number;
seconds(s: number): Moment;
seconds(): number;
millisecond(ms: number): Moment;
millisecond(): number;
milliseconds(ms: number): Moment;
milliseconds(): number;
weekday(): number;
weekday(d: number): Moment;
isoWeekday(): number;
isoWeekday(d: number): Moment;
weekYear(): number;
weekYear(d: number): Moment;
isoWeekYear(): number;
isoWeekYear(d: number): Moment;
week(): number;
week(d: number): Moment;
weeks(): number;
weeks(d: number): Moment;
isoWeek(): number;
isoWeek(d: number): Moment;
isoWeeks(): number;
isoWeeks(d: number): Moment;
weeksInYear(): number;
isoWeeksInYear(): number;
dayOfYear(): number;
dayOfYear(d: number): Moment;
from(f: Moment): string;
from(f: Moment, suffix: boolean): string;
from(d: Date): string;
from(s: string): string;
from(date: number[]): string;
diff(b: Moment): number;
diff(b: Moment, unitOfTime: string): number;
diff(b: Moment, unitOfTime: string, round: boolean): number;
toArray(): number[];
toDate(): Date;
toISOString(): string;
toJSON(): string;
unix(): number;
isLeapYear(): boolean;
zone(): number;
zone(b: number): Moment;
zone(b: string): Moment;
utcOffset(): number;
utcOffset(b: number): Moment;
utcOffset(b: string): Moment;
daysInMonth(): number;
isDST(): boolean;
isBefore(): boolean;
isBefore(b: Moment): boolean;
isBefore(b: string): boolean;
isBefore(b: Number): boolean;
isBefore(b: Date): boolean;
isBefore(b: number[]): boolean;
isBefore(b: Moment, granularity: string): boolean;
isBefore(b: String, granularity: string): boolean;
isBefore(b: Number, granularity: string): boolean;
isBefore(b: Date, granularity: string): boolean;
isBefore(b: number[], granularity: string): boolean;
isAfter(): boolean;
isAfter(b: Moment): boolean;
isAfter(b: string): boolean;
isAfter(b: Number): boolean;
isAfter(b: Date): boolean;
isAfter(b: number[]): boolean;
isAfter(b: Moment, granularity: string): boolean;
isAfter(b: String, granularity: string): boolean;
isAfter(b: Number, granularity: string): boolean;
isAfter(b: Date, granularity: string): boolean;
isAfter(b: number[], granularity: string): boolean;
isSame(b: Moment): boolean;
isSame(b: string): boolean;
isSame(b: Number): boolean;
isSame(b: Date): boolean;
isSame(b: number[]): boolean;
isSame(b: Moment, granularity: string): boolean;
isSame(b: String, granularity: string): boolean;
isSame(b: Number, granularity: string): boolean;
isSame(b: Date, granularity: string): boolean;
isSame(b: number[], granularity: string): boolean;
// Deprecated as of 2.8.0.
lang(language: string): Moment;
lang(reset: boolean): Moment;
lang(): MomentLanguage;
locale(language: string): Moment;
locale(reset: boolean): Moment;
locale(): string;
localeData(language: string): Moment;
localeData(reset: boolean): Moment;
localeData(): MomentLanguage;
// Deprecated as of 2.7.0.
max(date: Date): Moment;
max(date: number): Moment;
max(date: any[]): Moment;
max(date: string): Moment;
max(date: string, format: string): Moment;
max(clone: Moment): Moment;
// Deprecated as of 2.7.0.
min(date: Date): Moment;
min(date: number): Moment;
min(date: any[]): Moment;
min(date: string): Moment;
min(date: string, format: string): Moment;
min(clone: Moment): Moment;
get(unit: string): number;
set(unit: string, value: number): Moment;
}
interface MomentCalendar {
lastDay: any;
sameDay: any;
nextDay: any;
lastWeek: any;
nextWeek: any;
sameElse: any;
}
interface BaseMomentLanguage {
months ?: any;
monthsShort ?: any;
weekdays ?: any;
weekdaysShort ?: any;
weekdaysMin ?: any;
relativeTime ?: MomentRelativeTime;
meridiem ?: (hour: number, minute: number, isLowercase: boolean) => string;
calendar ?: MomentCalendar;
ordinal ?: (num: number) => string;
}
interface MomentLanguage extends BaseMomentLanguage {
longDateFormat?: MomentLongDateFormat;
}
interface MomentLanguageData extends BaseMomentLanguage {
/**
* @param formatType should be L, LL, LLL, LLLL.
*/
longDateFormat(formatType: string): string;
}
interface MomentLongDateFormat {
L: string;
LL: string;
LLL: string;
LLLL: string;
LT: string;
l?: string;
ll?: string;
lll?: string;
llll?: string;
lt?: string;
}
interface MomentRelativeTime {
future: any;
past: any;
s: any;
m: any;
mm: any;
h: any;
hh: any;
d: any;
dd: any;
M: any;
MM: any;
y: any;
yy: any;
}
interface MomentStatic {
version: string;
(): Moment;
(date: number): Moment;
(date: number[]): Moment;
(date: string, format?: string, strict?: boolean): Moment;
(date: string, format?: string, language?: string, strict?: boolean): Moment;
(date: string, formats: string[], strict?: boolean): Moment;
(date: string, formats: string[], language?: string, strict?: boolean): Moment;
(date: string, specialFormat: () => void, strict?: boolean): Moment;
(date: string, specialFormat: () => void, language?: string, strict?: boolean): Moment;
(date: string, formatsIncludingSpecial: any[], strict?: boolean): Moment;
(date: string, formatsIncludingSpecial: any[], language?: string, strict?: boolean): Moment;
(date: Date): Moment;
(date: Moment): Moment;
(date: Object): Moment;
utc(): Moment;
utc(date: number): Moment;
utc(date: number[]): Moment;
utc(date: string, format?: string, strict?: boolean): Moment;
utc(date: string, format?: string, language?: string, strict?: boolean): Moment;
utc(date: string, formats: string[], strict?: boolean): Moment;
utc(date: string, formats: string[], language?: string, strict?: boolean): Moment;
utc(date: Date): Moment;
utc(date: Moment): Moment;
utc(date: Object): Moment;
unix(timestamp: number): Moment;
invalid(parsingFlags?: Object): Moment;
isMoment(): boolean;
isMoment(m: any): boolean;
isDuration(): boolean;
isDuration(d: any): boolean;
// Deprecated in 2.8.0.
lang(language?: string): string;
lang(language?: string, definition?: MomentLanguage): string;
locale(language?: string): string;
locale(language?: string[]): string;
locale(language?: string, definition?: MomentLanguage): string;
localeData(language?: string): MomentLanguageData;
longDateFormat: any;
relativeTime: any;
meridiem: (hour: number, minute: number, isLowercase: boolean) => string;
calendar: any;
ordinal: (num: number) => string;
duration(milliseconds: Number): Duration;
duration(num: Number, unitOfTime: string): Duration;
duration(input: MomentInput): Duration;
duration(object: any): Duration;
duration(): Duration;
parseZone(date: string): Moment;
months(): string[];
months(index: number): string;
months(format: string): string[];
months(format: string, index: number): string;
monthsShort(): string[];
monthsShort(index: number): string;
monthsShort(format: string): string[];
monthsShort(format: string, index: number): string;
weekdays(): string[];
weekdays(index: number): string;
weekdays(format: string): string[];
weekdays(format: string, index: number): string;
weekdaysShort(): string[];
weekdaysShort(index: number): string;
weekdaysShort(format: string): string[];
weekdaysShort(format: string, index: number): string;
weekdaysMin(): string[];
weekdaysMin(index: number): string;
weekdaysMin(format: string): string[];
weekdaysMin(format: string, index: number): string;
min(moments: Moment[]): Moment;
max(moments: Moment[]): Moment;
normalizeUnits(unit: string): string;
relativeTimeThreshold(threshold: string, limit: number): void;
/**
* Constant used to enable explicit ISO_8601 format parsing.
*/
ISO_8601(): void;
}
}
declare module 'moment' {
var moment: moment.MomentStatic;
export = moment;
}
+1
View File
@@ -188,6 +188,7 @@ moment(1318874398806).valueOf();
moment(1318874398806).unix();
moment([2000]).isLeapYear();
moment().zone();
moment().utcOffset();
moment("2012-2", "YYYY-MM").daysInMonth();
moment([2011, 2, 12]).isDST();
+1 -473
View File
@@ -3,478 +3,6 @@
// Definitions by: Michael Lakerveld <https://github.com/Lakerfield>, Aaron King <https://github.com/kingdango>, Hiroki Horiuchi <https://github.com/horiuchi>, Dick van den Brink <https://github.com/DickvdBrink>, Adi Dahiya <https://github.com/adidahiya>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module moment {
interface MomentInput {
years?: number;
y?: number;
months?: number;
M?: number;
weeks?: number;
w?: number;
days?: number;
d?: number;
hours?: number;
h?: number;
minutes?: number;
m?: number;
seconds?: number;
s?: number;
milliseconds?: number;
ms?: number;
}
interface Duration {
humanize(withSuffix?: boolean): string;
as(units: string): number;
milliseconds(): number;
asMilliseconds(): number;
seconds(): number;
asSeconds(): number;
minutes(): number;
asMinutes(): number;
hours(): number;
asHours(): number;
days(): number;
asDays(): number;
months(): number;
asMonths(): number;
years(): number;
asYears(): number;
add(n: number, p: string): Duration;
add(n: number): Duration;
add(d: Duration): Duration;
subtract(n: number, p: string): Duration;
subtract(n: number): Duration;
subtract(d: Duration): Duration;
toISOString(): string;
}
interface Moment {
format(format: string): string;
format(): string;
fromNow(withoutSuffix?: boolean): string;
startOf(unitOfTime: string): Moment;
endOf(unitOfTime: string): Moment;
/**
* Mutates the original moment by adding time. (deprecated in 2.8.0)
*
* @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc)
* @param amount the amount you want to add
*/
add(unitOfTime: string, amount: number): Moment;
/**
* Mutates the original moment by adding time.
*
* @param amount the amount you want to add
* @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc)
*/
add(amount: number, unitOfTime: string): Moment;
/**
* Mutates the original moment by adding time. Note that the order of arguments can be flipped.
*
* @param amount the amount you want to add
* @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc)
*/
add(amount: string, unitOfTime: string): Moment;
/**
* Mutates the original moment by adding time.
*
* @param objectLiteral an object literal that describes multiple time units {days:7,months:1}
*/
add(objectLiteral: MomentInput): Moment;
/**
* Mutates the original moment by adding time.
*
* @param duration a length of time
*/
add(duration: Duration): Moment;
/**
* Mutates the original moment by subtracting time. (deprecated in 2.8.0)
*
* @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc)
* @param amount the amount you want to subtract
*/
subtract(unitOfTime: string, amount: number): Moment;
/**
* Mutates the original moment by subtracting time.
*
* @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc)
* @param amount the amount you want to subtract
*/
subtract(amount: number, unitOfTime: string): Moment;
/**
* Mutates the original moment by subtracting time. Note that the order of arguments can be flipped.
*
* @param amount the amount you want to add
* @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc)
*/
subtract(amount: string, unitOfTime: string): Moment;
/**
* Mutates the original moment by subtracting time.
*
* @param objectLiteral an object literal that describes multiple time units {days:7,months:1}
*/
subtract(objectLiteral: MomentInput): Moment;
/**
* Mutates the original moment by subtracting time.
*
* @param duration a length of time
*/
subtract(duration: Duration): Moment;
calendar(): string;
calendar(start: Moment): string;
clone(): Moment;
/**
* @return Unix timestamp, or milliseconds since the epoch.
*/
valueOf(): number;
local(): Moment; // current date/time in local mode
utc(): Moment; // current date/time in UTC mode
isValid(): boolean;
year(y: number): Moment;
year(): number;
quarter(): number;
quarter(q: number): Moment;
month(M: number): Moment;
month(M: string): Moment;
month(): number;
day(d: number): Moment;
day(d: string): Moment;
day(): number;
date(d: number): Moment;
date(): number;
hour(h: number): Moment;
hour(): number;
hours(h: number): Moment;
hours(): number;
minute(m: number): Moment;
minute(): number;
minutes(m: number): Moment;
minutes(): number;
second(s: number): Moment;
second(): number;
seconds(s: number): Moment;
seconds(): number;
millisecond(ms: number): Moment;
millisecond(): number;
milliseconds(ms: number): Moment;
milliseconds(): number;
weekday(): number;
weekday(d: number): Moment;
isoWeekday(): number;
isoWeekday(d: number): Moment;
weekYear(): number;
weekYear(d: number): Moment;
isoWeekYear(): number;
isoWeekYear(d: number): Moment;
week(): number;
week(d: number): Moment;
weeks(): number;
weeks(d: number): Moment;
isoWeek(): number;
isoWeek(d: number): Moment;
isoWeeks(): number;
isoWeeks(d: number): Moment;
weeksInYear(): number;
isoWeeksInYear(): number;
dayOfYear(): number;
dayOfYear(d: number): Moment;
from(f: Moment): string;
from(f: Moment, suffix: boolean): string;
from(d: Date): string;
from(s: string): string;
from(date: number[]): string;
diff(b: Moment): number;
diff(b: Moment, unitOfTime: string): number;
diff(b: Moment, unitOfTime: string, round: boolean): number;
toArray(): number[];
toDate(): Date;
toISOString(): string;
toJSON(): string;
unix(): number;
isLeapYear(): boolean;
zone(): number;
zone(b: number): Moment;
zone(b: string): Moment;
daysInMonth(): number;
isDST(): boolean;
isBefore(): boolean;
isBefore(b: Moment): boolean;
isBefore(b: string): boolean;
isBefore(b: Number): boolean;
isBefore(b: Date): boolean;
isBefore(b: number[]): boolean;
isBefore(b: Moment, granularity: string): boolean;
isBefore(b: String, granularity: string): boolean;
isBefore(b: Number, granularity: string): boolean;
isBefore(b: Date, granularity: string): boolean;
isBefore(b: number[], granularity: string): boolean;
isAfter(): boolean;
isAfter(b: Moment): boolean;
isAfter(b: string): boolean;
isAfter(b: Number): boolean;
isAfter(b: Date): boolean;
isAfter(b: number[]): boolean;
isAfter(b: Moment, granularity: string): boolean;
isAfter(b: String, granularity: string): boolean;
isAfter(b: Number, granularity: string): boolean;
isAfter(b: Date, granularity: string): boolean;
isAfter(b: number[], granularity: string): boolean;
isSame(b: Moment): boolean;
isSame(b: string): boolean;
isSame(b: Number): boolean;
isSame(b: Date): boolean;
isSame(b: number[]): boolean;
isSame(b: Moment, granularity: string): boolean;
isSame(b: String, granularity: string): boolean;
isSame(b: Number, granularity: string): boolean;
isSame(b: Date, granularity: string): boolean;
isSame(b: number[], granularity: string): boolean;
// Deprecated as of 2.8.0.
lang(language: string): Moment;
lang(reset: boolean): Moment;
lang(): MomentLanguage;
locale(language: string): Moment;
locale(reset: boolean): Moment;
locale(): string;
localeData(language: string): Moment;
localeData(reset: boolean): Moment;
localeData(): MomentLanguage;
// Deprecated as of 2.7.0.
max(date: Date): Moment;
max(date: number): Moment;
max(date: any[]): Moment;
max(date: string): Moment;
max(date: string, format: string): Moment;
max(clone: Moment): Moment;
// Deprecated as of 2.7.0.
min(date: Date): Moment;
min(date: number): Moment;
min(date: any[]): Moment;
min(date: string): Moment;
min(date: string, format: string): Moment;
min(clone: Moment): Moment;
get(unit: string): number;
set(unit: string, value: number): Moment;
}
interface MomentCalendar {
lastDay: any;
sameDay: any;
nextDay: any;
lastWeek: any;
nextWeek: any;
sameElse: any;
}
interface BaseMomentLanguage {
months ?: any;
monthsShort ?: any;
weekdays ?: any;
weekdaysShort ?: any;
weekdaysMin ?: any;
relativeTime ?: MomentRelativeTime;
meridiem ?: (hour: number, minute: number, isLowercase: boolean) => string;
calendar ?: MomentCalendar;
ordinal ?: (num: number) => string;
}
interface MomentLanguage extends BaseMomentLanguage {
longDateFormat?: MomentLongDateFormat;
}
interface MomentLanguageData extends BaseMomentLanguage {
/**
* @param formatType should be L, LL, LLL, LLLL.
*/
longDateFormat(formatType: string): string;
}
interface MomentLongDateFormat {
L: string;
LL: string;
LLL: string;
LLLL: string;
LT: string;
l?: string;
ll?: string;
lll?: string;
llll?: string;
lt?: string;
}
interface MomentRelativeTime {
future: any;
past: any;
s: any;
m: any;
mm: any;
h: any;
hh: any;
d: any;
dd: any;
M: any;
MM: any;
y: any;
yy: any;
}
interface MomentStatic {
version: string;
(): Moment;
(date: number): Moment;
(date: number[]): Moment;
(date: string, format?: string, strict?: boolean): Moment;
(date: string, format?: string, language?: string, strict?: boolean): Moment;
(date: string, formats: string[], strict?: boolean): Moment;
(date: string, formats: string[], language?: string, strict?: boolean): Moment;
(date: string, specialFormat: () => void, strict?: boolean): Moment;
(date: string, specialFormat: () => void, language?: string, strict?: boolean): Moment;
(date: string, formatsIncludingSpecial: any[], strict?: boolean): Moment;
(date: string, formatsIncludingSpecial: any[], language?: string, strict?: boolean): Moment;
(date: Date): Moment;
(date: Moment): Moment;
(date: Object): Moment;
utc(): Moment;
utc(date: number): Moment;
utc(date: number[]): Moment;
utc(date: string, format?: string, strict?: boolean): Moment;
utc(date: string, format?: string, language?: string, strict?: boolean): Moment;
utc(date: string, formats: string[], strict?: boolean): Moment;
utc(date: string, formats: string[], language?: string, strict?: boolean): Moment;
utc(date: Date): Moment;
utc(date: Moment): Moment;
utc(date: Object): Moment;
unix(timestamp: number): Moment;
invalid(parsingFlags?: Object): Moment;
isMoment(): boolean;
isMoment(m: any): boolean;
isDuration(): boolean;
isDuration(d: any): boolean;
// Deprecated in 2.8.0.
lang(language?: string): string;
lang(language?: string, definition?: MomentLanguage): string;
locale(language?: string): string;
locale(language?: string[]): string;
locale(language?: string, definition?: MomentLanguage): string;
localeData(language?: string): MomentLanguageData;
longDateFormat: any;
relativeTime: any;
meridiem: (hour: number, minute: number, isLowercase: boolean) => string;
calendar: any;
ordinal: (num: number) => string;
duration(milliseconds: Number): Duration;
duration(num: Number, unitOfTime: string): Duration;
duration(input: MomentInput): Duration;
duration(object: any): Duration;
duration(): Duration;
parseZone(date: string): Moment;
months(): string[];
months(index: number): string;
months(format: string): string[];
months(format: string, index: number): string;
monthsShort(): string[];
monthsShort(index: number): string;
monthsShort(format: string): string[];
monthsShort(format: string, index: number): string;
weekdays(): string[];
weekdays(index: number): string;
weekdays(format: string): string[];
weekdays(format: string, index: number): string;
weekdaysShort(): string[];
weekdaysShort(index: number): string;
weekdaysShort(format: string): string[];
weekdaysShort(format: string, index: number): string;
weekdaysMin(): string[];
weekdaysMin(index: number): string;
weekdaysMin(format: string): string[];
weekdaysMin(format: string, index: number): string;
min(moments: Moment[]): Moment;
max(moments: Moment[]): Moment;
normalizeUnits(unit: string): string;
relativeTimeThreshold(threshold: string, limit: number): void;
/**
* Constant used to enable explicit ISO_8601 format parsing.
*/
ISO_8601(): void;
}
}
/// <reference path="moment-node.d.ts" />
declare var moment: moment.MomentStatic;
declare module 'moment' {
export = moment;
}
+13 -1
View File
@@ -146,6 +146,9 @@ Model.remove((err: any, res: IActor[]) => {});
Model.save((err: any, res: IActor, numberAffected: number) => {});
Model.create({ type: 'jelly bean' }, { type: 'snickers' }, (err: any, res1: IActor, res2: IActor) => {});
Model.create({ type: 'jawbreaker' });
Model.create({ type: 'muffin' }).then(function (res) {
res.name;
});
Model.distinct('url', { clicks: {$gt: 100}}, (err: any, result: IActor[]) => {});
Model.distinct('url');
@@ -364,5 +367,14 @@ schema.virtual('display_name')
.get(function(): string { return this.name; })
.set((value: string): void => {});
var id : mongoose.Types.ObjectId;
var id: mongoose.Types.ObjectId = new mongoose.Types.ObjectId('foo');
var id2: mongoose.Types.ObjectId = new mongoose.Types.ObjectId(123);
var id2: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromTime(123);
var id2: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromHexString('foo');
var s = id.toHexString();
var valid = id.isValid();
var eq = id.equals(id2);
var kitty1 = new Kitty({});
var kitty2 = new Kitty({});
var kittyEq = kitty1._id.equals(kitty2._id);
+9 -3
View File
@@ -79,7 +79,13 @@ declare module "mongoose" {
}
export module Types {
export class ObjectId {
toHexString(): string;
constructor(id: string|number);
toHexString(): string;
equals(other: ObjectId): boolean;
getTimestamp(): Date;
isValid(): boolean;
static createFromTime(time: number): ObjectId;
static createFromHexString(hexString: string): ObjectId;
}
}
@@ -137,7 +143,7 @@ declare module "mongoose" {
aggregate(aggregation1: Object, aggregation2: Object, aggregation3: Object, callback: (err: any, res: T[]) => void): Promise<T[]>;
count(conditions: Object, callback?: (err: any, count: number) => void): Query<number>;
create(doc: Object, fn?: (err: any, res: T) => void): Promise<T[]>;
create(doc: Object, fn?: (err: any, res: T) => void): Promise<T>;
create(doc1: Object, doc2: Object, fn?: (err: any, res1: T, res2: T) => void): Promise<T[]>;
create(doc1: Object, doc2: Object, doc3: Object, fn?: (err: any, res1: T, res2: T, res3: T) => void): Promise<T[]>;
discriminator<U extends Document>(name: string, schema: Schema): Model<U>;
@@ -374,7 +380,7 @@ declare module "mongoose" {
export interface Document {
id?: string;
_id: string;
_id: Types.ObjectId;
equals(doc: Document): boolean;
get(path: string, type?: new(...args: any[]) => any): any;
+134
View File
@@ -0,0 +1,134 @@
/// <reference path="mpromise.d.ts" />
/// <reference path="../node/node.d.ts" />
var assert = require('assert');
import Promise = require('mpromise');
function ex1() {
var promise = new Promise;
}
function ex2() {
var promise = new Promise<number, string> (function(reason: string, ...args: number[]) {
return;
});
}
function ex3() {
var promise = new Promise<number, string>();
promise.onResolve(function(reason: string, ...args: number[]) {
return;
});
}
function fulfill() {
var promise = new Promise<number, Error>();
promise.fulfill(1, 2, 3);
}
function reject() {
var promise = new Promise<number, string>();
promise.reject('reason');
}
function onFulfill1<R>() {
var promise = new Promise<number, R>();
promise.onFulfill(function (...args: number[]) {
assert.equal(3, args[0] + args[1]);
});
promise.fulfill(1, 2);
}
function onFulfill2() {
var promise = new Promise<string, Error>();
promise.fulfill(" :D ");
promise.onFulfill(function (arg: string) {
console.log(arg); // logs " :D "
});
}
function onReject1<F>() {
var promise = new Promise<F, string>();
promise.onReject(function (reason: string) {
assert.equal('sad', reason);
});
promise.reject('sad');
}
function onReject2() {
var promise = new Promise<string, string>();
promise.reject(" :( ");
promise.onReject(function (reason: string) {
console.log(reason); // logs " :( "
});
}
function onResolve1<R>() {
var promise = new Promise<number, R>();
promise.onResolve(function (err: R, ...args: number[]) {
console.log(args[0] + args[1]); // logs 3
});
promise.fulfill(1, 2);
}
function onResolve2<F>() {
// rejection
var promise = new Promise<F, Error>();
promise.onResolve(function (err: Error) {
if (err) {
console.log(err.message); // logs "failed"
}
});
promise.reject(new Error('failed'));
}
function then() {
var promise = new Promise<number, Error>();
promise.then(function (arg: number) {
return arg + 1;
}).then(function (arg: number) {
throw new Error(arg + ' is an error!');
}).then(null, function (err: Error) {
assert.ok(err instanceof Error);
assert.equal('2 is an error', err.message);
});
promise.fulfill(1);
}
function end1() {
var promise = new Promise<number, Error>();
promise.then(function(){ throw new Error('shucks') });
setTimeout(function () {
promise.fulfill();
// error was caught and swallowed by the promise returned from
// p.then(). we either have to always register handlers on
// the returned promises or we can do the following...
}, 10);
}
function end2() {
// this time we use .end() which prevents catching thrown errors
var promise = new Promise<any, Error>();
setTimeout(function () {
promise.fulfill(); // throws "shucks"
}, 10);
return promise.then(function(){ throw new Error('shucks') }).end(); // <--
}
function chain() {
function makeMeAPromise(i: number) {
var p = new Promise<number, Error>();
p.fulfill(i);
return p;
}
var initialPromise = new Promise<number, Error>();
var returnPromise = initialPromise;
for (var i=0; i<10; ++i) {
returnPromise = returnPromise.chain(makeMeAPromise(i));
}
initialPromise.fulfill();
return returnPromise;
}
+42
View File
@@ -0,0 +1,42 @@
// Type definitions for mpromise 0.5.4
// Project: https://github.com/aheckmann/mpromise
// Definitions by: Seulgi Kim <https://github.com/sgkim126/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "mpromise" {
interface IFulfillFunction<F> {
(...args: F[]): void;
(arg: F): void;
}
interface IRejectFunction<R> {
(err: R): void;
}
interface IResolveFunction<F, R> {
(err: R, ...args: F[]): void;
(err: R, arg: F): void;
}
class Promise<F, R> {
constructor(fn?: IResolveFunction<F, R>);
static FAILURE: string;
static SUCCESS: string;
fulfill(...args: F[]): Promise<F, R>;
fulfill(arg: F): Promise<F, R>;
reject(reason: R): Promise<F, R>;
resolve(reason: R, ...args: F[]): Promise<F, R>;
resolve(reason: R, arg: F): Promise<F, R>;
onFulfill(callback: IFulfillFunction<F>): Promise<F, R>;
onReject(callback: IRejectFunction<R>): Promise<F, R>;
onResolve(callback: IResolveFunction<F, R>): Promise<F, R>;
then<F, R>(onFulfilled: IFulfillFunction<F>, onRejected?: IRejectFunction<R>): Promise<F, R>;
end(): void;
chain(promise: Promise<F, R>): Promise<F, R>;
}
export = Promise;
}
File diff suppressed because it is too large Load Diff
+2551
View File
File diff suppressed because it is too large Load Diff
+72
View File
@@ -0,0 +1,72 @@
/// <reference path="node-gcm.d.ts" />
import gcm = require('node-gcm');
// Create a message
// ... with default values
var message = new gcm.Message();
// ... or some given values
var message = new gcm.Message({
collapseKey: 'demo',
delayWhileIdle: true,
timeToLive: 3,
data: {
key1: 'message1',
key2: 'message2'
}
});
// Change the message data
// ... as key-value
message.addData('key1','message1');
message.addData('key2','message2');
// ... or as a data object (overwrites previous data object)
message.addData({
key1: 'message1',
key2: 'message2'
});
// Change the message variables
message.collapseKey = 'demo';
message.delayWhileIdle = true;
message.timeToLive = 3;
message.dryRun = true;
// Set up the sender with you API key
var sender = new gcm.Sender('insert Google Server API Key here');
// Add the registration IDs of the devices you want to send to
var registrationIds: string[] = [];
registrationIds.push('regId1');
registrationIds.push('regId2');
// Send the message
// ... trying only once
sender.sendNoRetry(message, registrationIds, (err, result) => {
if (err) {
console.error(err);
} else {
console.log(result);
}
});
// ... or retrying
sender.send(message, registrationIds, (err, result) => {
if (err) {
console.error(err);
} else {
console.log(result);
}
});
// ... or retrying a specific number of times (10)
sender.send(message, registrationIds, 10, (err, result) => {
if (err) {
console.error(err);
} else {
console.log(result);
}
});
+62
View File
@@ -0,0 +1,62 @@
// Type definitions for node-gcm 0.9.15
// Project: https://www.npmjs.org/package/node-gcm
// Definitions by: Hiroki Horiuchi <https://github.com/horiuchi>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "node-gcm" {
export interface IMessageOptions {
collapseKey?: string;
delayWhileIdle?: boolean;
timeToLive?: number;
dryRun?: boolean;
}
export class Message {
constructor(options?: IMessageOptions);
collapseKey: string;
delayWhileIdle: boolean;
timeToLive: number;
dryRun: boolean;
addData(key: string, value: string): void;
addData(data: any): void;
}
export interface ISenderOptions {
proxy?: any;
maxSockets?: number;
timeout?: number;
}
export interface ISenderSendOptions {
retries?: number;
backoff?: number;
}
export class Sender {
constructor(key: string, options?: ISenderOptions);
key: string;
options: ISenderOptions;
send(message: Message, registrationIds: string|string[], callback: (err: any, resJson: IResponseBody) => void): void;
send(message: Message, registrationIds: string|string[], retries: number, callback: (err: any, resJson: IResponseBody) => void): void;
send(message: Message, registrationIds: string|string[], options: ISenderSendOptions, callback: (err: any, resJson: IResponseBody) => void): void;
sendNoRetry(message: Message, registrationIds: string|string[], callback: (err: any, resJson: IResponseBody) => void): void;
}
export interface IResponseBody {
success: number;
failure: number;
canonical_ids: number;
multicast_id?: number;
results?: {
message_id?: string;
registration_id?: string;
error?: string;
}[];
}
}
+71
View File
@@ -0,0 +1,71 @@
/// <reference path="node-sass.d.ts" />
import sass = require('node-sass');
sass.render({
file: '/path/to/myFile.scss',
data: 'body{background:blue; a{color:black;}}',
importer: function(url, prev, done) {
// url is the path in import as is, which libsass encountered.
// prev is the previously resolved path.
// done is an optional callback, either consume it or return value synchronously.
// this.options contains this options hash, this.callback contains the node-style callback
someAsyncFunction(url, prev, function(result) {
done({
file: result.path, // only one of them is required, see section Sepcial Behaviours.
contents: result.data
});
});
// OR
var result = someSyncFunction(url, prev);
return { file: result.path, contents: result.data };
},
includePaths: ['lib/', 'mod/'],
outputStyle: 'compressed'
}, function(error, result) { // node-style callback from v3.0.0 onwards
if (error) {
console.log(error.status); // used to be "code" in v2x and below
console.log(error.column);
console.log(error.message);
console.log(error.line);
}
else {
console.log(result.css.toString());
console.log(result.stats);
console.log(result.map.toString());
// or better
console.log(JSON.stringify(result.map)); // note, JSON.stringify accepts Buffer too
}
});
// OR
var result = sass.renderSync({
file: '/path/to/file.scss',
data: 'body{background:blue; a{color:black;}}',
outputStyle: 'compressed',
outFile: '/to/my/output.css',
sourceMap: true, // or an absolute or relative (to outFile) path
importer: function(url, prev, done) {
// url is the path in import as is, which libsass encountered.
// prev is the previously resolved path.
// done is an optional callback, either consume it or return value synchronously.
// this.options contains this options hash
someAsyncFunction(url, prev, function(result) {
done({
file: result.path, // only one of them is required, see section Sepcial Behaviours.
contents: result.data
});
});
// OR
var result = someSyncFunction(url, prev);
return { file: result.path, contents: result.data };
},
});
console.log(result.css);
console.log(result.map);
console.log(result.stats);
function someAsyncFunction(url: string, prev: string, callback: (result: { path: string; data: string }) => void): void {}
function someSyncFunction(url: string, prev: string): { path: string; data: string} {
return null;
}
+56
View File
@@ -0,0 +1,56 @@
// Type definitions for Node Sass
// Project: https://github.com/sass/node-sass
// Definitions by: Asana <https://asana.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "node-sass" {
interface Importer {
(url: string, prev: string, done: (data: { file: string; contents: string; }) => void): void;
}
interface Options {
file?: string;
data?: string;
importer?: Importer | Importer[];
functions?: { [key: string]: Function };
includePaths?: string[];
indentedSyntax?: boolean;
indentType?: string;
indentWidth?: number;
linefeed?: string;
omitSourceMapUrl?: boolean;
outFile?: string;
outputStyle?: string;
precision?: number;
sourceComments?: boolean;
sourceMap?: boolean | string;
sourceMapContents?: boolean;
sourceMapEmbed?: boolean;
sourceMapRoot?: boolean;
}
interface SassError extends Error {
message: string;
line: number;
column: number;
status: number;
file: string;
}
interface Result {
css: Buffer;
map: Buffer;
stats: {
entry: string;
start: number;
end: number;
duration: number;
includedFiles: string[];
}
}
export function render(options: Options, callback: (err: SassError, result: Result) => any): void;
export function renderSync(options: Options): Result;
}
+55
View File
@@ -0,0 +1,55 @@
/// <reference path="papaparse.d.ts" />
import Papa = require("papaparse");
/**
* Parsing
*/
var res = Papa.parse("3,3,3");
res.errors[0].code;
Papa.parse("3,3,3", {
delimiter: ';',
comments: false,
step: function(results, p) {
p.abort();
results.data.length;
}
});
var file = new File();
Papa.parse(file, {
complete: function(a, b) {
a.meta.fields;
b.name;
}
});
/**
* Unparsing
*/
Papa.unparse([{a: 1, b: 1, c: 1}]);
Papa.unparse([[1, 2, 3], [4, 5, 6]]);
Papa.unparse({
fields: ["3"],
data: []
});
/**
* Properties
*/
Papa.SCRIPT_PATH;
Papa.LocalChunkSize;
/**
* Parser
*/
var parser = new Papa.Parser({})
parser.getCharIndex();
parser.abort();
parser.parse("", 0, false);
+144
View File
@@ -0,0 +1,144 @@
// Type definitions for PapaParse v4.1
// Project: https://github.com/mholt/PapaParse
// Definitions by: Pedro Flemming <https://github.com/torpedro>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module PapaParse {
interface Static {
/**
* Parse a csv string or a csv file
*/
parse(csvString: string, config?: ParseConfig): ParseResult;
parse(file: File, config?: ParseConfig): ParseResult;
/**
* Unparses javascript data objects and returns a csv string
*/
unparse(data: Array<Object>, config?: UnparseConfig): string;
unparse(data: Array<Array<any>>, config?: UnparseConfig): string;
unparse(data: UnparseObject, config?: UnparseConfig): string;
/**
* Read-Only Properties
*/
// An array of characters that are not allowed as delimiters.
BAD_DELIMETERS: Array<string>;
// The true delimiter. Invisible. ASCII code 30. Should be doing the job we strangely rely upon commas and tabs for.
RECORD_SEP: string;
// Also sometimes used as a delimiting character. ASCII code 31.
UNIT_SEP: string;
// Whether or not the browser supports HTML5 Web Workers. If false, worker: true will have no effect.
WORKERS_SUPPORTED: boolean;
// The relative path to Papa Parse. This is automatically detected when Papa Parse is loaded synchronously.
SCRIPT_PATH: string;
/**
* Configurable Properties
*/
// The size in bytes of each file chunk. Used when streaming files obtained from the DOM that exist on the local computer. Default 10 MB.
LocalChunkSize: string;
// Same as LocalChunkSize, but for downloading files from remote locations. Default 5 MB.
RemoteChunkSize: string;
// The delimiter used when it is left unspecified and cannot be detected automatically. Default is comma.
DefaultDelimiter: string;
/**
* On Papa there are actually more classes exposed
* but none of them are officially documented
* Since we can interact with the Parser from one of the callbacks
* I have included the API for this class.
*/
Parser: ParserConstructor;
}
interface ParseConfig {
delimiter?: string; // default: ""
newline?: string; // default: ""
header?: boolean; // default: false
dynamicTyping?: boolean; // default: false
preview?: number; // default: 0
encoding?: string; // default: ""
worker?: boolean; // default: false
comments?: boolean; // default: false
download?: boolean; // default: false
skipEmptyLines?: boolean; // default: false
fastMode?: boolean; // default: undefined
// Callbacks
step?(results: ParseResult, parser: Parser): void; // default: undefined
complete?(results: ParseResult, file?: File): void; // default: undefined
error?(error: ParseError, file?: File): void; // default: undefined
chunk?(results: ParseResult, parser: Parser): void; // default: undefined
beforeFirstChunk?(chunk: string): string|void; // default: undefined
}
interface UnparseConfig {
quotes: boolean; // default: false
delimiter: string; // default: ","
newline: string; // default: "\r\n"
}
interface UnparseObject {
fields: Array<any>;
data: string | Array<any>;
}
interface ParseError {
type: string; // A generalization of the error
code: string; // Standardized error code
message: string; // Human-readable details
row: number; // Row index of parsed data where error is
}
interface ParseMeta {
delimiter: string; // Delimiter used
linebreak: string; // Line break sequence used
aborted: boolean; // Whether process was aborted
fields: Array<string>; // Array of field names
truncated: boolean; // Whether preview consumed all input
}
/**
* @interface ParseResult
*
* data: is an array of rows. If header is false, rows are arrays; otherwise they are objects of data keyed by the field name.
* errors: is an array of errors
* meta: contains extra information about the parse, such as delimiter used, the newline sequence, whether the process was aborted, etc. Properties in this object are not guaranteed to exist in all situations
*/
interface ParseResult {
data: Array<any>;
errors: Array<ParseError>;
meta: ParseMeta;
}
/**
* Parser
*/
interface ParserConstructor { new(config: ParseConfig): Parser; }
interface Parser {
// Parses the input
parse(input: string, baseIndex: number, ignoreLastRow: boolean): any;
// Sets the abort flag
abort(): void;
// Gets the cursor position
getCharIndex(): number;
}
}
declare var Papa: PapaParse.Static;
declare module "papaparse" {
var Papa: PapaParse.Static;
export = Papa;
}
+4 -1
View File
@@ -842,7 +842,6 @@ declare module Parse {
INVALID_CONTENT_LENGTH = 128,
FILE_TOO_LARGE = 129,
FILE_SAVE_ERROR = 130,
FILE_DELETE_ERROR = 153,
DUPLICATE_VALUE = 137,
INVALID_ROLE_NAME = 139,
EXCEEDED_QUOTA = 140,
@@ -851,6 +850,9 @@ declare module Parse {
INVALID_IMAGE_DATA = 150,
UNSAVED_FILE_ERROR = 151,
INVALID_PUSH_TIME_ERROR = 152,
FILE_DELETE_ERROR = 153,
REQUEST_LIMIT_EXCEEDED = 155,
INVALID_EVENT_NAME = 160,
USERNAME_MISSING = 200,
PASSWORD_MISSING = 201,
USERNAME_TAKEN = 202,
@@ -860,6 +862,7 @@ declare module Parse {
SESSION_MISSING = 206,
MUST_CREATE_USER_THROUGH_SIGNUP = 207,
ACCOUNT_ALREADY_LINKED = 208,
INVALID_SESSION_TOKEN = 209,
LINKED_ID_MISSING = 250,
INVALID_LINKED_SESSION = 251,
UNSUPPORTED_SERVICE = 252,

Some files were not shown because too many files have changed in this diff Show More