Merge remote-tracking branch 'original/master'

This commit is contained in:
psnider
2015-07-31 22:18:33 +00:00
1466 changed files with 495347 additions and 924970 deletions
+9
View File
@@ -0,0 +1,9 @@
root = true
[*]
trim_trailing_whitespace = true
insert_final_newline = true
[{*.json,*.yml}]
indent_style = space
indent_size = 2
+2 -3
View File
@@ -28,10 +28,9 @@ _infrastructure/tests/build
.idea
*.iml
*.js.map
#rx.js
!rx.js
!*.js/
node_modules
.sublimets
.settings/launch.json
+1 -1
View File
@@ -1,6 +1,6 @@
language: node_js
node_js:
- "0.10"
- "iojs-v2"
sudo: false
+496 -59
View File
File diff suppressed because it is too large Load Diff
+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
View File
@@ -0,0 +1,11 @@
/// <reference path="FileSaver.d.ts" />
/**
* @summary Test for "saveAs" function.
*/
function testSaveAs() {
var data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
var filename: string = 'hello world.txt';
saveAs(data, filename);
}
+27
View File
@@ -0,0 +1,27 @@
// Type definitions for FileSaver.js
// Project: https://github.com/eligrey/FileSaver.js/
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* @summary Interface for "saveAs" function.
* @author Cyril Schumacher
* @version 1.0
*/
interface FileSaver {
(
/**
* @summary Data.
* @type {Blob}
*/
data: Blob,
/**
* @summary File name.
* @type {DOMString}
*/
filename: string
): void
}
declare var saveAs: FileSaver;
+4 -2
View File
@@ -1,5 +1,7 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/borisyankov/DefinitelyTyped.png?branch=master)](https://travis-ci.org/borisyankov/DefinitelyTyped)
[![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
> The repository for *high quality* TypeScript type definitions.
For more information see the [definitelytyped.org](http://definitelytyped.org) website.
@@ -30,7 +32,7 @@ Please see the [contribution guide](http://definitelytyped.org/guides/contributi
## Requested definitions
Here is an updated list of [definitions people have requested](https://github.com/borisyankov/DefinitelyTyped/issues?labels=Definition%3ARequest).
Here is are the [currently requested definitions](https://github.com/borisyankov/DefinitelyTyped/labels/Definition%3ARequest).
## Licence
@@ -38,4 +40,4 @@ This project is licensed under the MIT license.
Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file.
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)
+10
View File
@@ -0,0 +1,10 @@
/// <reference path="_debugger.d.ts"/>
import _debugger = require("_debugger");
var {Client} = _debugger;
var client = new Client();
client.connect(8888, 'localhost');
client.listbreakpoints((err, res) => {
});
+135
View File
@@ -0,0 +1,135 @@
// Type definitions for Node.js debugger API
// Project: http://nodejs.org/
// Definitions by: Basarat Ali Syed <https://github.com/basarat>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts"/>
declare module NodeJS {
export module _debugger {
export interface Packet {
raw: string;
headers: string[];
body: Message;
}
export interface Message {
seq: number;
type: string;
}
export interface RequestInfo {
command: string;
arguments: any;
}
export interface Request extends Message, RequestInfo {
}
export interface Event extends Message {
event: string;
body?: any;
}
export interface Response extends Message {
request_seq: number;
success: boolean;
/** Contains error message if success === false. */
message?: string;
/** Contains message body if success === true. */
body?: any;
}
export interface BreakpointMessageBody {
type: string;
target: number;
line: number;
}
export class Protocol {
res: Packet;
state: string;
execute(data: string): void;
serialize(rq: Request): string;
onResponse: (pkt: Packet) => void;
}
export var NO_FRAME: number;
export var port: number;
export interface ScriptDesc {
name: string;
id: number;
isNative?: boolean;
handle?: number;
type: string;
lineOffset?: number;
columnOffset?: number;
lineCount?: number;
}
export interface Breakpoint {
id: number;
scriptId: number;
script: ScriptDesc;
line: number;
condition?: string;
scriptReq?: string;
}
export interface RequestHandler {
(err: boolean, body: Message, res: Packet): void;
request_seq?: number;
}
export interface ResponseBodyHandler {
(err: boolean, body?: any): void;
request_seq?: number;
}
export interface ExceptionInfo {
text: string;
}
export interface BreakResponse {
script?: ScriptDesc;
exception?: ExceptionInfo;
sourceLine: number;
sourceLineText: string;
sourceColumn: number;
}
export function SourceInfo(body: BreakResponse): string;
export interface ClientInstance extends EventEmitter {
protocol: Protocol;
scripts: ScriptDesc[];
handles: ScriptDesc[];
breakpoints: Breakpoint[];
currentSourceLine: number;
currentSourceColumn: number;
currentSourceLineText: string;
currentFrame: number;
currentScript: string;
connect(port: number, host: string): void;
req(req: any, cb: RequestHandler): void;
reqFrameEval(code: string, frame: number, cb: RequestHandler): void;
mirrorObject(obj: any, depth: number, cb: ResponseBodyHandler): void;
setBreakpoint(rq: BreakpointMessageBody, cb: RequestHandler): void;
clearBreakpoint(rq: Request, cb: RequestHandler): void;
listbreakpoints(cb: RequestHandler): void;
reqSource(from: number, to: number, cb: RequestHandler): void;
reqScripts(cb: any): void;
reqContinue(cb: RequestHandler): void;
}
export var Client : {
new (): ClientInstance
}
}
}
declare module "_debugger"{
export = NodeJS._debugger;
}
-23
View File
@@ -1,23 +0,0 @@
var path = require('path');
var fs = require('fs');
function readJSON(target) {
return JSON.parse(fs.readFileSync(target, 'utf8'));
}
function getSemFloat(str) {
var m = /^[^\d]*(\d+)\.(\d+)/.exec(str);
return parseFloat(m[1] + '.' + m[2]);
}
var repo = readJSON(path.resolve(__dirname, '..', 'package.json'));
var testerPath = path.resolve(__dirname, '..', 'node_modules', 'definition-tester', 'package.json');
// ultra lame semver major/minor check
if (!fs.existsSync(testerPath) || getSemFloat(repo.dependencies['definition-tester']) > getSemFloat(readJSON(testerPath).version)) {
console.log('DefinitelyTyped tester needs an update!\n\n please run \'npm install\'\n');
process.exit(1);
}
require('definition-tester');
File diff suppressed because it is too large Load Diff
@@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')
File diff suppressed because one or more lines are too long
+36
View File
@@ -0,0 +1,36 @@
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="acc-wizard.d.ts" />
/**
* @summary Test for "accwizard" without options.
*/
function testBasic() {
$('#test').accwizard();
}
/**
* @summary Test for "accwizard" with options.
*/
function testWithOptions() {
var options: AccWizardOptions = {
addButtons: true,
sidebar: '.acc-wizard-sidebar',
activeClass: 'acc-wizard-active',
completedClass: 'acc-wizard-completed',
todoClass: 'acc-wizard-todo',
stepClass: 'acc-wizard-step',
nextText: 'Next Step',
backText: 'Go Back',
nextType: 'submit',
backType: 'reset',
nextClasses: 'btn btn-primary',
backClasses: 'btn',
autoScrolling: true,
onNext: function() {},
onBack: function() {},
onInit: function() {},
onDestroy: function() {}
};
$('#test').accwizard(options);
}
+101
View File
@@ -0,0 +1,101 @@
// Type definitions for acc-wizard
// Project: https://github.com/sathomas/acc-wizard
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface AccWizardOptions {
/**
* @summary Add next/prev buttons to panels.
* @type {boolean}
*/
addButtons: boolean;
/**
* @summary Selector for task sidebar.
* @type {string}
*/
sidebar: string;
/**
* @summary Class to indicate the active task in sidebar.
* @type {string}
*/
activeClass: string;
/**
* @summary Class to indicate task is complete.
* @type {string}
*/
completedClass: string;
/**
* @summary Class to indicate task is still pending.
* @type {string}
*/
todoClass: string;
/**
* @summary Class for step buttons within panels.
* @type {string}
*/
stepClass: string;
/**
* @summary Text for next button.
* @type {string}
*/
nextText: string;
/**
* @summary Text for back button
* @type {string}
*/
backType: string;
/**
* @summary Class(es) for next button.
* @type {string}
*/
nextClasses: string;
/**
* @summary Class(es) for back button.
* @type {string}
*/
backClasses: string;
/**
* @summary Auto-scrolling.
* @type {boolean}
*/
autoScrolling: boolean;
/**
* @summary Function to call on next step.
*/
onNext: Function;
/**
* @summary Function to call on back up.
*/
onBack: Function;
/**
* @summary A chance to hook initialization.
*/
onInit: Function;
/**
* @summary A chance to hook destruction.
*/
onDestroy: Function;
}
/**
* @summary Interface for "acc-wizard" JQuery plugin.
* @author Cyril Schumacher
* @version 1.0
*/
interface JQuery {
accwizard(options?: AccWizardOptions): void;
}
+1
View File
@@ -0,0 +1 @@
--noImplicitAny
+46 -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;
@@ -1060,6 +1063,31 @@ declare module AceAjax {
onChangeMode(e?);
execCommand(command:string, args?: any);
/**
* Sets a Configuration Option
**/
setOption(optionName: any, optionValue: any);
/**
* Sets Configuration Options
**/
setOptions(keyValueTuples: any);
/**
* Get a Configuration Option
**/
getOption(name: any):any;
/**
* Get Configuration Options
**/
getOptions():any;
/**
* Get rid of console warning by setting this to Infinity
**/
$blockScrolling:number;
/**
* Sets a new key handler, such as "vim" or "windows".
@@ -1710,6 +1738,13 @@ declare module AceAjax {
**/
new(renderer: VirtualRenderer, session?: IEditSession): Editor;
}
interface EditorChangeEvent {
start: Position;
end: Position;
action: string; // insert, remove
lines: any[];
}
////////////////////////////////
/// PlaceHolder
@@ -2574,6 +2609,16 @@ declare module AceAjax {
* Returns `true` if there are redo operations left to perform.
**/
hasRedo(): boolean;
/**
* Returns `true` if the dirty counter is 0
**/
isClean(): boolean;
/**
* Sets dirty counter to 0
**/
markClean(): void;
}
var UndoManager: {
+16
View File
@@ -0,0 +1,16 @@
/// <reference path='acl.d.ts'/>
// https://github.com/OptimalBits/node_acl/blob/master/Readme.md
import Acl = require('acl');
import mongodb = require('mongodb');
var db: mongodb.Db;
// Using the mongo db backend
var acl = new Acl(new Acl.mongodbBackend(db, 'acl_', true));
// guest is allowed to view blogs
acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
acl.allow('member', 'blogs', ['edit','view', 'delete']);
+16
View File
@@ -0,0 +1,16 @@
/// <reference path='acl.d.ts'/>
// https://github.com/OptimalBits/node_acl/blob/master/Readme.md
import Acl = require('acl');
import redis = require('redis');
var client: redis.RedisClient;
// Using the redis backend
var acl = new Acl(new Acl.redisBackend(client, 'acl_'));
// guest is allowed to view blogs
acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
acl.allow('member', 'blogs', ['edit','view', 'delete']);
+65
View File
@@ -0,0 +1,65 @@
/// <reference path='acl.d.ts'/>
// Sample code from
// https://github.com/OptimalBits/node_acl/blob/master/Readme.md
import Acl = require('acl');
var report = <T>(err: Error, value: T) => {
if (err) {
console.error(err);
}
console.info(value);
};
// Using the memory backend
var acl = new Acl(new Acl.memoryBackend());
// guest is allowed to view blogs
acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
acl.allow('member', 'blogs', ['edit','view', 'delete']);
acl.addUserRoles('joed', 'guest');
acl.addRoleParents('baz', ['foo','bar']);
acl.allow('foo', ['blogs','forums','news'], ['view', 'delete']);
acl.allow('admin', ['blogs','forums'], '*');
acl.allow([
{
roles:['guest','special-member'],
allows:[
{resources:'blogs', permissions:'get'},
{resources:['forums','news'], permissions:['get','put','delete']}
]
},
{
roles:['gold','silver'],
allows:[
{resources:'cash', permissions:['sell','exchange']},
{resources:['account','deposit'], permissions:['put','delete']}
]
}
]);
acl.isAllowed('joed', 'blogs', 'view', (err, res) => {
if (res) {
console.log("User joed is allowed to view blogs");
}
});
acl.isAllowed('jsmith', 'blogs', ['edit','view','delete'])
.then((result) => {
console.dir('jsmith is allowed blogs ' + result);
acl.addUserRoles('jsmith', 'member');
}).then(() =>
acl.isAllowed('jsmith', 'blogs', ['edit','view','delete'])
).then((result) =>
console.dir('jsmith is allowed blogs ' + result)
).then(() => {
acl.allowedPermissions('james', ['blogs','forums'], report);
acl.allowedPermissions('jsmith', ['blogs','forums'], report);
});
+150
View File
@@ -0,0 +1,150 @@
// Type definitions for node_acl 0.4.7
// Project: https://github.com/optimalbits/node_acl
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../bluebird/bluebird.d.ts" />
/// <reference path='../node/node.d.ts'/>
/// <reference path='../redis/redis.d.ts'/>
/// <reference path="../mongodb/mongodb.d.ts" />
declare module "acl" {
import http = require('http');
import Promise = require("bluebird");
type strings = string|string[];
type Value = string|number;
type Values = Value|Value[];
type Action = () => any;
type Callback = (err: Error) => any;
type AnyCallback = (err: Error, obj: any) => any;
type AllowedCallback = (err: Error, allowed: boolean) => any;
type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value;
interface AclStatic {
new (backend: Backend<any>, logger: Logger, options: Option): Acl;
new (backend: Backend<any>, logger: Logger): Acl;
new (backend: Backend<any>): Acl;
memoryBackend: MemoryBackendStatic;
}
interface Logger {
debug: (msg: string)=>any;
}
interface Acl {
addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>;
removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>;
userRoles: (userId: Value, cb?: (err: Error, roles: string[])=>any) => Promise<string[]>;
roleUsers: (role: Value, cb?: (err: Error, users: Values)=>any) => Promise<any>;
hasRole: (userId: Value, role: string, cb?: (err: Error, isInRole: boolean)=>any) => Promise<boolean>;
addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise<void>;
removeRole: (role: string, cb?: Callback) => Promise<void>;
removeResource: (resource: string, cb?: Callback) => Promise<void>;
allow: {
(roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise<void>;
(aclSets: AclSet|AclSet[]): Promise<void>;
}
removeAllow: (role: string, resources: strings, permissions: strings, cb?: Callback) => Promise<void>;
removePermissions: (role: string, resources: strings, permissions: strings, cb?: Function) => Promise<void>;
allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise<void>;
isAllowed: (userId: Value, resources: strings, permissions: strings, cb?: AllowedCallback) => Promise<boolean>;
areAnyRolesAllowed: (roles: strings, resource: strings, permissions: strings, cb?: AllowedCallback) => Promise<any>;
whatResources: (roles: strings, permissions: strings, cb?: AnyCallback) => Promise<any>;
permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise<void>;
middleware: (numPathComponents: number, userId: Value|GetUserId, actions: strings) => Promise<any>;
}
interface Option {
buckets?: BucketsOption;
}
interface BucketsOption {
meta?: string;
parents?: string;
permissions?: string;
resources?: string;
roles?: string;
users?: string;
}
interface AclSet {
roles: strings;
allows: AclAllow[];
}
interface AclAllow {
resources: strings;
permissions: strings;
}
interface MemoryBackend extends Backend<Action[]> { }
interface MemoryBackendStatic {
new(): MemoryBackend;
}
//
// For internal use
//
interface Backend<T> {
begin: () => T;
end: (transaction: T, cb?: Action) => void;
clean: (cb?: Action) => void;
get: (bucket: string, key: Value, cb?: Action) => void;
union: (bucket: string, keys: Value[], cb?: Action) => void;
add: (transaction: T, bucket: string, key: Value, values: Values) => void;
del: (transaction: T, bucket: string, keys: Value[]) => void;
remove: (transaction: T, bucket: string, key: Value, values: Values) => void;
endAsync: Function; //TODO: Give more specific function signature
getAsync: Function;
cleanAsync: Function;
unionAsync: Function;
}
interface Contract {
(args: IArguments): Contract|NoOp;
debug: boolean;
fulfilled: boolean;
args: any[];
checkedParams: string[];
params: (...types: string[]) => Contract|NoOp;
end: () => void;
}
interface NoOp {
params: (...types: string[]) => NoOp;
end: () => void;
}
// for redis backend
import redis = require('redis');
interface AclStatic {
redisBackend: RedisBackendStatic;
}
interface RedisBackend extends Backend<redis.RedisClient> { }
interface RedisBackendStatic {
new(redis: redis.RedisClient, prefix: string): RedisBackend;
new(redis: redis.RedisClient): RedisBackend;
}
// for mongodb backend
import mongo = require('mongodb');
interface AclStatic {
mongodbBackend: MongodbBackendStatic;
}
interface MongodbBackend extends Backend<Callback> { }
interface MongodbBackendStatic {
new(db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend;
new(db: mongo.Db, prefix: string): MongodbBackend;
new(db: mongo.Db): MongodbBackend;
}
var _: AclStatic;
export = _;
}
+30
View File
@@ -0,0 +1,30 @@
/// <reference path="../estree/estree.d.ts" />
/// <reference path="acorn.d.ts" />
import acorn = require('acorn');
var token: acorn.Token;
var tokens: acorn.Token[];
var comment: acorn.Comment;
var comments: acorn.Comment[];
var program: ESTree.Program;
var any: any;
var string: string;
// acorn
string = acorn.version;
program = acorn.parse('code');
program = acorn.parse('code', {range: true, onToken: tokens, onComment: comments});
program = acorn.parse('code', {
ranges: true,
onToken: (token) => tokens.push(token),
onComment: (isBlock, text, start, end) => { }
});
// Token
token = tokens[0];
string = token.type.label;
any = token.value;
// Comment
string = comment.value;
+67
View File
@@ -0,0 +1,67 @@
// Type definitions for Acorn v1.0.1
// Project: https://github.com/marijnh/acorn
// Definitions by: RReverser <https://github.com/RReverser>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../estree/estree.d.ts" />
declare module acorn {
var version: string;
function parse(input: string, options?: Options): ESTree.Program;
function parseExpressionAt(input: string, pos: number, options?: Options): ESTree.Expression;
var defaultOptions: Options;
interface TokenType {
label: string;
keyword: string;
beforeExpr: boolean;
startsExpr: boolean;
isLoop: boolean;
isAssign: boolean;
prefix: boolean;
postfix: boolean;
binop: number;
updateContext: (prevType: TokenType) => any;
}
interface AbstractToken {
start: number;
end: number;
loc: ESTree.SourceLocation;
range: [number, number];
}
interface Token extends AbstractToken {
type: TokenType;
value: any;
}
interface Comment extends AbstractToken {
type: string;
value: string;
}
interface Options {
ecmaVersion?: number;
sourceType?: string;
onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any;
onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any;
allowReserved?: boolean;
allowReturnOutsideFunction?: boolean;
allowImportExportEverywhere?: boolean;
allowHashBang?: boolean;
locations?: boolean;
onToken?: ((token: Token) => any) | Token[];
onComment?: ((isBlock: boolean, text: string, start: number, end: number, startLoc?: ESTree.Position, endLoc?: ESTree.Position) => any) | Comment[];
ranges?: boolean;
program?: ESTree.Program;
sourceFile?: string;
directSourceFile?: string;
preserveParens?: boolean;
plugins?: { [name: string]: Function; };
}
}
declare module "acorn" {
export = acorn
}
+143
View File
@@ -0,0 +1,143 @@
/**
* Created by shearerbeard on 6/28/15.
*/
///<reference path="alt.d.ts"/>
///<reference path="../es6-promise/es6-promise.d.ts" />
import Alt = require("alt");
import Promise = require("es6-promise");
//New alt instance
var alt = new Alt();
//Interfaces for our Action Types
interface TestActionsGenerate {
notifyTest(str:string):void;
}
interface TestActionsExplicit {
doTest(str:string):void;
success():void;
error():void;
loading():void;
}
//Create abstracts to inherit ghost methods
class AbstractActions implements AltJS.ActionsClass {
constructor( alt:AltJS.Alt){}
actions:any;
dispatch: ( ...payload:Array<any>) => void;
generateActions:( ...actions:Array<string>) => void;
}
class AbstractStoreModel<S> implements AltJS.StoreModel<S> {
bindActions:( ...actions:Array<Object>) => void;
bindAction:( ...args:Array<any>) => void;
bindListeners:(obj:any)=> void;
exportPublicMethods:(config:{[key:string]:(...args:Array<any>) => any}) => any;
exportAsync:( source:any) => void;
waitFor:any;
exportConfig:any;
getState:() => S;
}
class GenerateActionsClass extends AbstractActions {
constructor(config:AltJS.Alt) {
this.generateActions("notifyTest");
super(config);
}
}
class ExplicitActionsClass extends AbstractActions {
doTest(str:string) {
this.dispatch(str);
}
success() {
this.dispatch();
}
error() {
this.dispatch();
}
loading() {
this.dispatch();
}
}
var generatedActions = alt.createActions<TestActionsGenerate>(GenerateActionsClass);
var explicitActions = alt.createActions<ExplicitActionsClass>(ExplicitActionsClass);
interface AltTestState {
hello:string;
}
var testSource:AltJS.Source = {
fakeLoad():AltJS.SourceModel<string> {
return {
remote() {
return new Promise.Promise<string>((res:any, rej:any) => {
setTimeout(() => {
if(true) {
res("stuff");
} else {
rej("Things have broken");
}
}, 250)
});
},
local() {
return "local";
},
success: explicitActions.success,
error: explicitActions.error,
loading:explicitActions.loading
};
}
};
class TestStore extends AbstractStoreModel<AltTestState> implements AltTestState {
hello:string = "world";
constructor() {
super();
this.bindAction(generatedActions.notifyTest, this.onTest);
this.bindActions(explicitActions);
this.exportAsync(testSource);
this.exportPublicMethods({
split: this.split
});
}
onTest(str:string) {
this.hello = str;
}
onDoTest(str:string) {
this.hello = str;
}
split():string[] {
return this.hello.split("");
}
}
interface ExtendedTestStore extends AltJS.AltStore<AltTestState> {
fakeLoad():string;
split():Array<string>;
}
var testStore = <ExtendedTestStore>alt.createStore<AltTestState>(TestStore);
function testCallback(state:AltTestState) {
console.log(state);
}
//Listen allows a typed state callback
testStore.listen(testCallback);
testStore.unlisten(testCallback);
//State generic passes to derived store
var name:string = testStore.getState().hello;
var nameChars:Array<string> = testStore.split();
generatedActions.notifyTest("types");
explicitActions.doTest("more types");
export var result = testStore.getState();
+167
View File
@@ -0,0 +1,167 @@
// Type definitions for Alt 0.16.10
// Project: https://github.com/goatslacker/alt
// Definitions by: Michael Shearer <https://github.com/Shearerbeard>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../react/react.d.ts"/>
///<reference path="../es6-promise/es6-promise.d.ts" />
declare module AltJS {
interface StoreReduce {
action:any;
data: any;
}
export interface StoreModel<S> {
//Actions
bindAction?( action:Action<any>, handler:ActionHandler):void;
bindActions?(actions:ActionsClass):void;
//Methods/Listeners
exportPublicMethods?(exportConfig:any):void;
bindListeners?(config:{[methodName:string]:Action<any> | Actions}):void;
exportAsync?(source:Source):void;
registerAsync?(datasource:Source):void;
//state
setState?(state:S):void;
setState?(stateFn:(currentState:S, nextState:S) => S):void;
getState?():S;
waitFor?(store:AltStore<any>):void;
//events
onSerialize?(fn:(data:any) => any):void;
onDeserialize?(fn:(data:any) => any):void;
on?(event:AltJS.lifeCycleEvents, callback:() => any):void;
emitChange?():void;
waitFor?(storeOrStores:AltStore<any> | Array<AltStore<any>>):void;
otherwise?(data:any, action:AltJS.Action<any>):void;
observe?(alt:Alt):any;
reduce?(state:any, config:StoreReduce):Object;
preventDefault?():void;
afterEach?(payload:Object, state:Object):void;
beforeEach?(payload:Object, state:Object):void;
// TODO: Embed dispatcher interface in def
dispatcher?:any;
//instance
getInstance?():AltJS.AltStore<S>;
alt?:Alt;
displayName?:string;
}
export type Source = {[name:string]: () => SourceModel<any>};
export interface SourceModel<S> {
local(state:any):any;
remote(state:any):Promise<S>;
shouldFetch?(fetchFn:(...args:Array<any>) => boolean):void;
loading?:(args:any) => void;
success?:(state:S) => void;
error?:(args:any) => void;
interceptResponse?(response:any, action:Action<any>, ...args:Array<any>):any;
}
export interface AltStore<S> {
getState():S;
listen(handler:(state:S) => any):() => void;
unlisten(handler:(state:S) => any):void;
emitChange():void;
}
export enum lifeCycleEvents {
bootstrap,
snapshot,
init,
rollback,
error
}
export type Actions = {[action:string]:Action<any>};
export interface Action<T> {
( args:T):void;
defer(data:any):void;
}
export interface ActionsClass {
generateActions?( ...action:Array<string>):void;
dispatch( ...payload:Array<any>):void;
actions?:Actions;
}
type StateTransform = (store:StoreModel<any>) => AltJS.AltStore<any>;
interface AltConfig {
dispatcher?:any;
serialize?:(serializeFn:(data:Object) => string) => void;
deserialize?:(deserializeFn:(serialData:string) => Object) => void;
storeTransforms?:Array<StateTransform>;
batchingFunction?:(callback:( ...data:Array<any>) => any) => void;
}
class Alt {
constructor(config?:AltConfig);
actions:Actions;
bootstrap(jsonData:string):void;
takeSnapshot( ...storeNames:Array<string>):string;
flush():Object;
recycle( ...stores:Array<AltJS.AltStore<any>>):void;
rollback():void;
dispatch(action?:AltJS.Action<any>, data?:Object, details?:any):void;
//Actions methods
addActions(actionsName:string, ActionsClass: ActionsClassConstructor):void;
createActions<T>(ActionsClass: ActionsClassConstructor, exportObj?: Object):T;
createActions<T>(ActionsClass: ActionsClassConstructor, exportObj?: Object, ...constructorArgs:Array<any>):T;
generateActions<T>( ...actions:Array<string>):T;
getActions(actionsName:string):AltJS.Actions;
//Stores methods
addStore(name:string, store:StoreModel<any>, saveStore?:boolean):void;
createStore<S>(store:StoreModel<S>, name?:string):AltJS.AltStore<S>;
getStore(name:string):AltJS.AltStore<any>;
}
export interface AltFactory {
new(config?:AltConfig):Alt;
}
type ActionsClassConstructor = new (alt:Alt) => AltJS.ActionsClass;
type ActionHandler = ( ...data:Array<any>) => any;
type ExportConfig = {[key:string]:(...args:Array<any>) => any};
}
declare module "alt/utils/chromeDebug" {
function chromeDebug(alt:AltJS.Alt):void;
export = chromeDebug;
}
declare module "alt/AltContainer" {
import React = require("react");
interface ContainerProps {
store?:AltJS.AltStore<any>;
stores?:Array<AltJS.AltStore<any>>;
inject?:{[key:string]:any};
actions?:{[key:string]:Object};
render?:(...props:Array<any>) => React.ReactElement<any>;
flux?:AltJS.Alt;
transform?:(store:AltJS.AltStore<any>, actions:any) => any;
shouldComponentUpdate?:(props:any) => boolean;
component?:React.Component<any, any>;
}
type AltContainer = React.ReactElement<ContainerProps>;
var AltContainer:React.ComponentClass<ContainerProps>;
export = AltContainer;
}
declare module "alt" {
var alt:AltJS.AltFactory;
export = alt;
}
+1 -1
View File
@@ -50,7 +50,7 @@ interface amplifyRequest {
* success (optional): Function to invoke on success.
* error (optional): Function to invoke on error.
*/
(settings: amplifyRequestSettings);
(settings: amplifyRequestSettings): any;
/***
* Define a resource.
@@ -0,0 +1,23 @@
/// <reference path='../angularjs/angular.d.ts' />
/// <reference path='angular-dynamic-locale.d.ts' />
var app = angular.module('testModule', ['tmh.dynamicLocale']);
app.config((localStorageServiceProvider: angular.dynamicLocale.tmhDynamicLocaleProvider) => {
localStorageServiceProvider
.localeLocationPattern("app/config/locales/")
.useCookieStorage();
});
class LocaleTestController {
constructor(tmhDynamicLocaleService: angular.dynamicLocale.tmhDynamicLocaleService) {
var locale = tmhDynamicLocaleService.get();
var newLocale = "mt"
tmhDynamicLocaleService.set(newLocale);
}
}
app.controller('TestController', LocaleTestController);
+21
View File
@@ -0,0 +1,21 @@
// Type definitions for angular-dynamic-locale v0.1.27
// Project: https://github.com/lgalfaso/angular-dynamic-locale
// Definitions by: Stephen Lautier <https://github.com/stephenlautier>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.dynamicLocale {
interface tmhDynamicLocaleService {
set(locale: string): void;
get(): string;
}
interface tmhDynamicLocaleProvider extends angular.IServiceProvider {
localeLocationPattern(location: string): tmhDynamicLocaleProvider;
localeLocationPattern(): string;
useStorage(storageName: string): void;
useCookieStorage(): void;
}
}
@@ -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);
});
}
}
}
+12 -6
View File
@@ -1,26 +1,32 @@
// 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
/// <reference path="../angularjs/angular.d.ts" />
declare module ng.angularFileUpload {
declare module angular.angularFileUpload {
interface IUploadService {
http<T>(config: IFileUploadConfig): IUploadPromise<T>;
http<T>(config: IRequestConfig): IUploadPromise<T>;
upload<T>(config: IFileUploadConfig): IUploadPromise<T>;
}
interface IUploadPromise<T> extends IHttpPromise<T> {
abort(): IUploadPromise<T>;
progress(callback: IHttpPromiseCallback<T>): IUploadPromise<T>;
xhr(callback: IHttpPromiseCallback<T>): IUploadPromise<T>;
}
interface IFileUploadConfig extends ng.IRequestConfig {
interface IFileUploadConfig extends IRequestConfig {
file: File;
fileName?: string;
}
interface IFileProgressEvent extends ProgressEvent {
config: IFileUploadConfig;
}
}
+108
View File
@@ -0,0 +1,108 @@
/// <reference path="angular-formly.d.ts" />
var app = angular.module('app', ['formly']);
interface IScope extends ng.IScope {
to: { label: string; }
}
class FormConfig {
constructor(formlyConfig: AngularFormly.IFormlyConfig, formlyValidationMessages: AngularFormly.IValidationMessages) {
formlyConfig.setWrapper({
name: 'validation',
types: ['input', 'customInput'],
templateUrl: 'my-messages.html'
});
formlyValidationMessages.addStringMessage('required', 'This field is required');
formlyConfig.setType({
name: 'customInput',
extends: 'input'
});
}
}
class AppController {
fields: AngularFormly.IFieldConfigurationObject[];
constructor() {
var vm = this;
vm.fields = [
{
key: 'firstName',
type: 'customInput',
templateOptions: {
required: true,
label: 'First Name',
foo: 'hi'
}
},
{
key: 'email',
type: 'input',
templateOptions: {
label: 'Email',
required: true,
type: 'email',
maxlength: 10,
minlength: 6,
placeholder: 'example@example.com'
}
},
{
key: 'ip',
type: 'input',
validators: {
ipAddress: {
expression: function(viewValue, modelValue) {
var value = modelValue || viewValue;
return /(\d{1,3}\.){3}\d{1,3}/.test(value);
},
message: '$viewValue + " is not a valid IP Address"'
}
},
templateOptions: {
label: 'IP Address',
required: true,
type: 'text',
placeholder: '127.0.0.1',
},
validation: {
messages: {
required: function($viewValue: any, $modelValue: any, scope: AngularFormly.ITemplateScope) {
return scope.to.label + ' is required'
}
}
}
},
{
key: 'mac',
type: 'input',
templateOptions: {
label: 'MAC Address',
required: true,
placeholder: '49-8A-BD-4E-00-1D',
pattern: '([0-9A-F]{2}[:-]){5}([0-9A-F]{2})'
}
},
{
type: 'checkbox',
key: 'checked',
templateOptions: {
label: 'Check this'
}
},
{
key: 'checked2',
type: 'checkbox',
wrapper: null,
templateOptions: {
label: 'no wrapper here...'
}
}
]
}
}
app.controller("AppController", AppController);
+574
View File
@@ -0,0 +1,574 @@
// Type definitions for angular-formly 6.18.0
// Project: https://github.com/formly-js/angular-formly
// Definitions by: Scott Hatcher <https://github.com/scatcher>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module 'AngularFormly' {
export = AngularFormly;
}
declare module AngularFormly {
interface IFieldGroup {
data?: Object;
className?: string;
elementAttributes?: { [key: string]: string };
fieldGroup: IFieldConfigurationObject[];
form?: Object;
hide?: boolean;
hideExpression?: string | IExpresssionFunction;
key?: string | number;
model?: string | Object;
options?: IFormOptionsAPI
}
interface IFormOptionsAPI {
data?: Object;
fieldTransform?: Function;
formState?: Object;
removeChromeAutoComplete?: boolean;
resetModel?: Function;
templateManipulators?: ITemplateManipulators;
updateInitialValue?: Function;
wrapper?: string | string[];
}
/**
* see http://docs.angular-formly.com/docs/formly-expressions#expressionproperties-validators--messages
*/
interface IExpresssionFunction {
($viewValue: any, $modelValue: any, scope: ITemplateScope): any;
}
interface IModelOptions {
updateOn?: string;
debounce?: number;
allowInvalid?: boolean;
getterSetter?: string;
timezone?: string;
}
interface ITemplateManipulator {
(template: string | HTMLElement, options: Object, scope: ITemplateScope): string | HTMLElement;
}
interface ITemplateManipulators {
preWrapper?: ITemplateManipulator[];
postWrapper?: ITemplateManipulator[];
}
/**
* see http://docs.angular-formly.com/docs/ngmodelattrstemplatemanipulator
*/
interface ITemplateOptions {
// both attribute or regular attribute
disabled?: boolean;
maxlength?: number;
minlength?: number;
pattern?: string;
required?: boolean;
//attribute only
max?: number;
min?: number;
placeholder?: number | string;
tabindex?: number;
type?: string;
//expression types
onBlur?: string;
onChange?: string;
onClick?: string;
onFocus?: string;
onKeydown?: string;
onKeypress?: string;
onKeyup?: string;
//Bootstrap types
label?: string;
description?: string;
[key: string]: any;
}
/**
* see http://docs.angular-formly.com/docs/field-configuration-object#validators-object
*/
interface IValidator {
expression: string | IExpresssionFunction;
message?: string | IExpresssionFunction;
}
/**
* An object which has at least two properties called expression and listener. The watch.expression
* is added to the formly-form directive's scope (to allow it to run even when hide is true). You
* can specify a type ($watchCollection or $watchGroup) via the watcher.type property (defaults to
* $watch) and whether you want it to be a deep watch via the watcher.deep property (defaults to false).
*
* see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches
*/
interface IWatcher {
deep?: boolean; //Defaults to false
expression?: string | { (field: string, scope: ITemplateScope): boolean };
listener: (field: string, newValue: any, oldValue: any, scope: ITemplateScope, stopWatching: Function) => void;
type?: string; //Defaults to $watch but can be set to $watchCollection or $watchGroup
}
// see http://docs.angular-formly.com/docs/field-configuration-object
interface IFieldConfigurationObject {
/**
* Added in 6.18.0
*
* Demo
* see http://angular-formly.com/#/example/other/unique-value-async-validation
*/
asyncValidators?: {
[key: string]: string | IExpresssionFunction | IValidator;
}
/**
* This is a great way to add custom behavior to a specific field. It is injectable with the $scope of the
* field, and anything else you have in your injector.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#controller-controller-name-as-string--controller-f
*/
controller?: string | Function;
/**
* This is reserved for the developer. You have our guarantee to be able to use this and not worry about
* future versions of formly overriding your usage and preventing you from upgrading :-)
*
* see http://docs.angular-formly.com/docs/field-configuration-object#data-object
*/
data?: Object;
/**
* Use defaultValue to initialize it the model. If this is provided and the value of the
* model at compile-time is undefined, then the value of the model will be assigned to defaultValue.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#defaultvalue-any
*/
defaultValue?: any;
/**
* You can specify your own class that will be applied to the formly-field directive (or ng-form of
* a fieldGroup).
*
* see http://docs.angular-formly.com/docs/field-configuration-object#classname-string
*/
className?: string;
elementAttributes?: string;
/**
* An object where the key is a property to be set on the main field config and the value is an
* expression used to assign that property. The value is a formly expressions. The returned value is
* wrapped in $q.when so you can return a promise from your function :-)
*
* see http://docs.angular-formly.com/docs/field-configuration-object#expressionproperties-object
*/
expressionProperties?: {
[key: string]: string | IExpresssionFunction | IValidator;
}
/**
* Uses ng-if. Whether to hide the field. Defaults to false. If you wish this to be conditional, use
* hideExpression. See below.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#hide-boolean
*/
hide?: boolean
/**
* This is similar to expressionProperties with a slight difference. You should (hopefully) never
* notice the difference with the most common use case. This is available due to limitations with
* expressionProperties and ng-if not working together very nicely.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#hideexpression-string--function
*/
hideExpression?: string | IExpresssionFunction;
/**
* This allows you to specify the id of your field (which will be used for its name as well unless
* a name is provided). Note, you can also override the id generation code using the formlyConfig
* extra called getFieldId.
*
* AVOID THIS
* If you don't have to do this, don't. Specifying IDs makes it harder to re-use things and it's
* just extra work. Part of the beauty that angular-formly provides is the fact that you don't need
* to concern yourself with making sure that this is unique.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#id-string
*/
id?: string;
initialValue?: any;
/**
* Can be set instead of type or template to use a custom html template form field. Works
* just like a directive templateUrl and uses the $templateCache
*
* see http://docs.angular-formly.com/docs/field-configuration-object#key-string
*/
key?: string | number;
/**
* This allows you to specify a link function. It is invoked after your template has finished compiling.
* You are passed the normal arguments for a normal link function.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#link-link-function
*/
link?: ng.IDirectiveLinkFn;
/**
* By default, the model passed to the formly-field directive is the same as the model passed to the
* formly-form. However, if the field has a model specified, then it is used for that field (and that
* field only). In addition, a deep watch is added to the formly-field directive's scope to run the
* expressionProperties when the specified model changes.
*
* Note, the formly-form directive will allow you to specify a string which is an (almost) formly
* expression which allows you to define the model as relative to the scope of the form.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#model-object--string
*/
model?: Object | string;
/**
* Allows you to take advantage of ng-model-options directive. Formly's built-in templateManipulator (see
* below) will add this attribute to your ng-model element automatically if this property exists. Note,
* if you use the getter/setter option, formly's templateManipulator will change the value of ng-model
* to options.value which is a getterSetter that formly adds to field options.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#modeloptions
*/
modelOptions?: IModelOptions;
/**
* If you wish to, you can specify a specific name for your ng-model. This is useful if you're posting
* the form to a server using techniques of yester-year.
*
* AVOID THIS
* If you don't have to do this, don't. It's just extra work. Part of the beauty that angular-formly
* provides is the fact that you don't need to concern yourself with stuff like this.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#name-string
*/
name?: string;
/**
* This is used by ngModelAttrsTemplateManipulator to automatically add attributes to the ng-model element
* of field templates. You will likely not use this often. This object is a little complex, but extremely
* powerful. It's best to explain this api via an example. For more information, see the guide on ngModelAttrs.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#ngmodelattrs-object
*/
ngModelAttrs?: {
attribute?: any;
bound?: any;
expression?: any;
value?: any;
};
/**
* Used to tell angular-formly to not attempt to add the formControl property to your object. This is useful
* for things like validation, but not necessary if your "field" doesn't use ng-model (if it's just a horizontal
* line for example). Defaults to undefined.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#noformcontrol-boolean
*/
noFormControl?: boolean;
/**
* Allows you to specify extra types to get options from. Duplicate options are overridden in later priority
* (index 1 will override index 0 properties). Also, these are applied after the type's defaultOptions and
* hence will override any duplicates of those properties as well.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#optionstypes-string--array-of-strings
*/
optionsTypes?: string | string[];
/**
* Can be set instead of type or templateUrl to use a custom html
* template form field. Recommended to be used with one-liners mostly
* (like a directive), or if you're using webpack with the ability to require templates :-)
*
* If a function is passed, it is invoked with the field configuration object and can return
* either a string for the template or a promise that resolves to a string.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#template-string--function
*/
template?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise<string> };
/**
* Allows you to specify custom template manipulators for this specific field. (use defaultOptions in a
* type configuration if you want it to apply to all fields of a certain type).
*
* see http://docs.angular-formly.com/docs/field-configuration-object#templatemanipulator-object-of-arrays-of-functions
*/
templateManipulators?: ITemplateManipulators;
/**
* This is reserved for the templates. Any template-specific options go in here. Look at your specific
* template implementation to know the options required for this.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#templateoptions-object
*/
templateOptions?: ITemplateOptions;
/**
* Can be set instead of type or template to use a custom html template form field. Works
* just like a directive templateUrl and uses the $templateCache
*
* see http://docs.angular-formly.com/docs/field-configuration-object#templateurl-string--function
*/
templateUrl?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise<string> };
/**
* The type of field to be rendered. This is the recommended method
* for defining fields. Types must be pre-defined using formlyConfig.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#type-string
*/
type?: string;
/**
* An object with a few useful properties mostly handy when used in combination with ng-messages
*/
validation?: {
/**
* This is set by angular-formly. This is a boolean indicating whether an error message should be shown. Because
* you generally only want to show error messages when the user has interacted with a specific field, this value
* is set to true based on this rule: field invalid && (field touched || validation.show) (with slight difference
* for pre-angular 1.3 because it doesn't have touched support).
*/
errorExistsAndShouldBeVisible?: boolean;
/**
* A map of Formly Expressions mapped to message names. This is really useful when you're using ng-messages
* like in this example.
*/
messages?: {
[key: string]: IExpresssionFunction | string;
}
/**
* A boolean you as the developer can set to specify to force options.validation.errorExistsAndShouldBeVisible
* to be set to true when there are $errors. This is useful when you're trying to call the user's attention to
* some fields for some reason.
*/
show?: boolean;
}
/**
* An object where the keys are the name of the validator and the values are Formly Expressions;
*
* Async Validation
* All function validators can return true/false/Promise. A validator passes if it returns true or a promise
* that is resolved. A validator fails if it returns false or a promise that is rejected.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#validators-object
*/
validators?: {
[key: string]: string | IExpresssionFunction | IValidator;
}
/**
* This is a getter/setter function for the value that your field is representing. Useful when using getterSetter: true
* in the modelOptions (in fact, if you don't disable the ngModelAttrsTemplateManipulator that comes built-in with formly,
* it will automagically change your field's ng-model attribute to use options.value.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#value-gettersetter-function
*/
value?(): any; //Getter
value?(val: any): void; //Setter
/**
* An object which has at least two properties called expression and listener. The watch.expression is added
* to the formly-form directive's scope (to allow it to run even when hide is true). You can specify a type
* ($watchCollection or $watchGroup) via the watcher.type property (defaults to $watch) and whether you want
* it to be a deep watch via the watcher.deep property (defaults to false).
*
* see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches
*/
watcher?: IWatcher | IWatcher[];
/**
* This makes reference to setWrapper in formlyConfig. It is expected to be the name of the wrapper. If
* given an array, the formly field template will be wrapped by the first wrapper, then the second, then
* the third, etc. You can also specify these as part of a type (which is the recommended approach).
* Specifying this property will override the wrappers for the type for this field.
*
* http://docs.angular-formly.com/docs/field-configuration-object#wrapper-string--array-of-strings
*/
wrapper?: string | string[];
//ALL PROPERTIES BELOW ARE ADDED (So you should not be setting them yourself.)
/**
* This is the NgModelController for the field. It provides you with awesome stuff like $errors :-)
*
* see http://docs.angular-formly.com/docs/field-configuration-object#formcontrol-ngmodelcontroller
*/
formControl?: ng.IFormController | ng.IFormController[];
/**
* Will reset the field's model and the field control to the last initialValue. This is used by the
* formly-form's options.resetModel function.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#resetmodel-function
*/
resetModel?: () => void;
/**
* It is not likely that you'll ever want to invoke this function. It simply runs the expressionProperties expressions.
* It is used internally and you shouldn't have to use it, but you can if you want to, and any breaking changes to the
* way it works will result in a major version change, so you can rely on its api.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#runexpressions-function
*/
runExpressions?: () => void;
/**
* Will reset the field's initialValue to the current state of the model. Useful if you load the model asynchronously.
* Invoke this when the model gets set. This is used by the formly-form's options.updateInitialValue function.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#updateinitialvalue-function
*/
updateInitialValue?: () => void;
}
/**
*
*
* see http://docs.angular-formly.com/docs/custom-templates#section-formlyconfig-settype-options
*/
interface ITypeOptions {
apiCheck?: { [key: string]: Function };
apiCheckFunction?: string; //'throw' or 'warn
apiCheckInstance?: any;
apiCheckOptions?: Object;
defaultOptions?: IFieldConfigurationObject | Function;
controller?: Function | string | any[];
data?: Object;
extends?: string;
link?: ng.IDirectiveLinkFn;
overwriteOk?: boolean;
name: string;
template?: Function | string;
templateUrl?: Function | string;
validateOptions?: Function;
wrapper?: string | string[];
}
interface IWrapperOptions {
apiCheck?: { [key: string]: Function };
apiCheckFunction?: string; //'throw' or 'warn
apiCheckInstance?: any;
apiCheckOptions?: Object;
overwriteOk?: boolean;
name?: string;
template?: string;
templateUrl?: string;
types?: string[];
validateOptions?: Function;
}
interface IFormlyConfig {
setType(typeOptions: ITypeOptions): void;
setWrapper(wrapperOptions: IWrapperOptions): void;
}
interface ITemplateScopeOptions {
formControl: ng.IFormController | ng.IFormController[];
templateOptions: ITemplateOptions;
validation: Object;
}
/**
* see http://docs.angular-formly.com/docs/custom-templates#templates-scope
*/
interface ITemplateScope {
options: ITemplateScopeOptions;
//Shortcut to options.formControl
fc: ng.IFormController | ng.IFormController[];
//all the fields for the form
fields: IFieldConfigurationObject[];
//the form controller the field is in
form: any;
//The object passed as options.formState to the formly-form directive. Use this to share state between fields.
formState: Object;
//The id of the field. You shouldn't have to use this.
id: string;
//The index of the field the form is on (in ng-repeat)
index: number;
//the model of the form (or the model specified by the field if it was specified).
model: Object | string;
//Shortcut to options.validation.errorExistsAndShouldBeVisible
showError: boolean;
//Shortcut to options.templateOptions
to: ITemplateOptions;
}
/**
* see http://docs.angular-formly.com/docs/formlyvalidationmessages#addtemplateoptionvaluemessage
*/
interface IValidationMessages {
addTemplateOptionValueMessage(name: string, prop: string, prefix: string, suffix: string, alternate: string): void;
addStringMessage(name: string, string: string): void;
messages: { [key: string]: ($viewValue: any, $modelValue: any, scope: ITemplateScope) => string };
}
}
+53
View File
@@ -0,0 +1,53 @@
/// <reference path="angular-growl-v2.d.ts" />
var app = angular.module("ag", ["pascalprecht.translate", "$httpProvider"]);
app.config((growlProvider:angular.growl.IGrowlProvider, $httpProvider:angular.IHttpProvider) => {
var ttl:angular.growl.IGrowlTTLConfig = {
success: 5000,
error: 4000
};
growlProvider.globalTimeToLive(ttl);
growlProvider.globalTimeToLive(5000);
growlProvider.globalDisableCloseButton(true);
growlProvider.globalDisableIcons(true);
growlProvider.globalReversedOrder(false);
growlProvider.globalDisableCountDown(true);
growlProvider.messageVariableKey("someKey");
growlProvider.globalInlineMessages(false);
growlProvider.globalPosition("top-center");
growlProvider.messagesKey("someKey");
growlProvider.messageTextKey("someKey");
growlProvider.messageTitleKey("someKey");
growlProvider.messageSeverityKey("someKey");
growlProvider.onlyUniqueMessages(false);
$httpProvider.interceptors.push(growlProvider.serverMessagesInterceptor);
});
app.controller("Ctrl", ($scope:angular.IScope, growl:angular.growl.IGrowlService) => {
var config:angular.growl.IGrowlMessageConfig = {
ttl: 5000,
disableCountDown: true,
disableCloseButton: true
};
var message = "Some message";
growl.warning(message);
growl.warning(message, config);
growl.error(message);
growl.error(message, config);
growl.info(message);
growl.info(message, config);
growl.success(message);
growl.success(message, config);
growl.general(message);
growl.general(message, config);
growl.general(message, config, "error");
growl.onlyUnique();
growl.reverseOrder();
growl.inlineMessages();
growl.position();
});
+211
View File
@@ -0,0 +1,211 @@
// Type definitions for Angular Growl 2 v.0.7.3
// Project: http://janstevens.github.io/angular-growl-2
// Definitions by: Tadeusz Hucal <https://github.com/mkp05>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.growl {
/**
* Global Time-To-Leave configuration.
*/
interface IGrowlTTLConfig {
success?: number;
error?: number;
warning?: number;
info?: number;
}
/**
* Custom configuration used in single message call.
*/
interface IGrowlMessageConfig {
title?: string;
ttl?: number;
disableCountDown?: boolean;
disableIcons?: boolean;
disableCloseButton?: boolean;
referenceId?: number;
onclose?: Function;
onopen?: Function;
}
/**
* Growl message with configuration.
*/
interface IGrowlMessage extends IGrowlMessageConfig {
text: string;
}
/**
* Growl service provider.
*/
interface IGrowlProvider extends angular.IServiceProvider {
/**
* Pre-defined server error interceptor.
*/
serverMessagesInterceptor: (string|Function)[];
/**
* Set default TTL settings.
* @param ttl configuration of TTL for different type of message
*/
globalTimeToLive(ttl: IGrowlTTLConfig): void;
/**
* Set default TTL settings.
* @param ttl ttl in milliseconds
*/
globalTimeToLive(ttl: number): void;
/**
* Set default setting for disabling close button.
* @param disableCloseButton
*/
globalDisableCloseButton(disableCloseButton: boolean): void;
/**
* Set default setting for disabling icons.
* @param disableIcons
*/
globalDisableIcons(disableIcons: boolean): void;
/**
* Set reversing order of displaying new messages.
* @param reverseOrder
*/
globalReversedOrder(reverseOrder: boolean): void
/**
* Set default setting for displaying message disappear countdown.
* @param disableCountDown
*/
globalDisableCountDown(disableCountDown: boolean): void;
/**
* Set default allowance for inline messages.
* @param inline
*/
globalInlineMessages(inline: boolean): void;
/**
* Set default message position.
* @param position
*/
globalPosition(position: string): void;
/**
* Enable/disable displaying only unique messages.
* @param onlyUniqueMessages
*/
onlyUniqueMessages(onlyUniqueMessages: boolean): void;
/**
* Set key where messages are stored (for http interceptor).
* @param messageVariableKey
*/
messagesKey(messageKey: string): void;
/**
* Set key where message text is stored (for http interceptor).
* @param messageVariableKey
*/
messageTextKey(messageTextKey: string): void;
/**
* Set key where title of message is stored (for http interceptor).
* @param messageVariableKey
*/
messageTitleKey(messageTitleKey: string): void;
/**
* Set key where severity of message is stored (for http interceptor).
* @param messageVariableKey
*/
messageSeverityKey(messageSeverityKey: string): void;
/**
* Set key where variables for message are stored (for http interceptor).
* @param messageVariableKey
*/
messageVariableKey(messageVariableKey: string): void;
}
/**
* Growl service.
*/
interface IGrowlService {
/**
* Show warning message.
* @param message text to display (or code for angular-translate)
*/
warning(message: string): IGrowlMessage;
/**
* Show warning message.
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
warning(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show error message.
* @param message text to display (or code for angular-translate)
*/
error(message: string): IGrowlMessage;
/**
* Show error message.
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
error(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show information message.
* @param message text to display (or code for angular-translate)
*/
info(message: string): IGrowlMessage;
/**
* Show information message.
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
info(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show success message.
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
success(message: string): IGrowlMessage;
/**
* Show success message.
* @param message text to display (or code for angular-translate)
*/
success(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show message (generic).
* @param message text to display (or code for angular-translate)
*/
general(message: string): IGrowlMessage;
/**
* Show message (generic).
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
general(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show message (generic).
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
* @param severity message severity (error, warning, success, info).
*/
general(message: string, config: IGrowlMessageConfig, severity: string): IGrowlMessage;
/**
* Get current setting for displaying only unique messages.
*/
onlyUnique(): boolean;
/**
* Get current setting for reversing messages order.
*/
reverseOrder(): boolean;
/**
* Get current allowance for inline messages.
*/
inlineMessages(): boolean;
/**
* Get current messages position.
*/
position(): string;
}
}
+8
View File
@@ -6,10 +6,13 @@ var hotkeyProvider: ng.hotkeys.HotkeysProvider;
var hotkeyObj: ng.hotkeys.Hotkey;
hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} );
hotkeyProvider.add(["mod+s"], "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} );
hotkeyProvider.add(hotkeyObj);
hotkeyProvider.bindTo(scope);
hotkeyProvider.del("mod+s");
hotkeyProvider.del(["mod+s"]);
hotkeyProvider.get("mod+s");
hotkeyProvider.get(["mod+s"]);
hotkeyProvider.toggleCheatSheet();
hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description ,hotkeyObj.callback);
@@ -21,5 +24,10 @@ hotkeyProvider.bindTo(scope)
combo: 'w',
description: 'blah blah',
callback: function() {}
})
.add({
combo: ['w', 'mod+w'],
description: 'blah blah',
callback: function() {}
});
+18 -8
View File
@@ -1,40 +1,50 @@
// Type definitions for angular-hotkeys
// Project: https://github.com/chieffancypants/angular-hotkeys
// Definitions by: Jason Zhao <https://github.com/jlz27>
// Definitions by: Jason Zhao <https://github.com/jlz27>, Stefan Steinhart <https://github.com/reppners>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module ng.hotkeys {
declare module angular.hotkeys {
interface HotkeysProvider {
template: string;
templateTitle:string;
includeCheatSheet: boolean;
cheatSheetHotkey: string;
cheatSheetDescription: string;
add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): void;
add(combo: string|string[], callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array<string>, persistent?: boolean): ng.hotkeys.Hotkey;
add(hotkeyObj: ng.hotkeys.Hotkey): void;
add(combo: string|string[], description: string, callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array<string>, persistent?: boolean): ng.hotkeys.Hotkey;
add(hotkeyObj: ng.hotkeys.Hotkey): ng.hotkeys.Hotkey;
bindTo(scope : ng.IScope): ng.hotkeys.HotkeysProviderChained;
del(combo: string): void;
del(combo: string|string[]): void;
get(combo: string): ng.hotkeys.Hotkey;
del(hotkeyObj: ng.hotkeys.Hotkey): void;
get(combo: string|string[]): ng.hotkeys.Hotkey;
toggleCheatSheet(): void;
purgeHotkeys(): void;
}
interface HotkeysProviderChained {
add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained;
add(combo: string|string[], description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained;
add(hotkeyObj: ng.hotkeys.Hotkey): HotkeysProviderChained;
}
interface Hotkey {
combo: string;
combo: string|string[];
description?: string;
callback: (event: Event, hotkey: ng.hotkeys.Hotkey) => void;
action?: string;
allowIn?: Array<string>;
persistent?: boolean;
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
/// <reference path="../angularjs/angular.d.ts" />
declare module ng.httpAuth {
declare module angular.httpAuth {
interface IAuthService {
loginConfirmed(data?:any, configUpdater?:Function):void;
loginCancelled(data?:any, reason?:any):void;
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="./angular-idle.d.ts" />
angular.module('app', ['ngIdle'])
.config(['$keepaliveProvider', '$idleProvider',
($keepaliveProvider: ng.idle.IKeepAliveProvider, $idleProvider: ng.idle.IIdleProvider) => {
$idleProvider.activeOn('mousemove keydown DOMMouseScroll mousewheel mousedown');
$idleProvider.idleDuration(5);
$idleProvider.warningDuration(5);
$idleProvider.keepalive(true)
$idleProvider.autoResume(true);
$keepaliveProvider.interval(10);
}])
.run(['$keepalive', '$idle', ($keepalive: ng.idle.IKeepAliveService, $idle: ng.idle.IIdleService) => {
$idle.watch();
if ($idle.running() || $idle.idling()) {
$idle.unwatch();
}
$keepalive.start();
$keepalive.ping();
$keepalive.stop();
}]);
+134
View File
@@ -0,0 +1,134 @@
// Type definitions for ng-idle v0.3.5
// Project: http://hackedbychinese.github.io/ng-idle/
// Definitions by: mthamil <https://github.com/mthamil>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.idle {
/**
* Used to configure the $keepalive service.
*/
interface IKeepAliveProvider extends IServiceProvider {
/**
* If configured, options will be used to issue a request using $http.
* If the value is null, no HTTP request will be issued.
* You can specify a string, which it will assume to be a URL to a simple GET request.
* Otherwise, you can use the same options $http takes. However, cache will always be false.
*
* @param value May be string or object, default is null.
*/
http(value: any): void;
/**
* This specifies how often the keepalive event is triggered and the
* HTTP request is issued.
*
* @param seconds Integer, default is 5 minutes. Must be greater than 0.
*/
interval(seconds: number): void;
}
/**
* $keepalive will use a timeout to periodically wake, broadcast a $keepalive event on the root scope,
* and optionally make an $http request. By default, the $idle service will stop and start $keepalive
* when a user becomes idle or returns from idle, respectively. It is also started automatically when
* $idle.watch() is called. This can be disabled by configuring the $idleProvider.
*/
interface IKeepAliveService {
/**
* Starts pinging periodically until stop() is called.
*/
start(): void;
/**
* Stops pinging.
*/
stop(): void;
/**
* Performs one ping only.
*/
ping(): void;
}
/**
* Used to configure the $idle service.
*/
interface IIdleProvider extends IServiceProvider {
/**
* Specifies the DOM events the service will watch to reset the idle timeout.
* Multiple events should be separated by a space.
*
* @param events string, default 'mousemove keydown DOMMouseScroll mousewheel mousedown'
*/
activeOn(events: string): void;
/**
* The idle timeout duration in seconds. After this amount of time passes without the user
* performing an action that triggers one of the watched DOM events, the user is considered
* idle.
*
* @param seconds integer, default is 20min
*/
idleDuration(seconds: number): void;
/**
* The amount of time the user has to respond (in seconds) before they have been considered
* timed out.
*
* @param seconds integer, default is 30s
*/
warningDuration(seconds: number): void;
/**
* When true, user activity will automatically interrupt the warning countdown and reset the
* idle state. If false, you will need to manually call watch() when you want to start
* watching for idleness again.
*
* @param enabled boolean, default is true
*/
autoResume(enabled: boolean): void;
/**
* When true, the $keepalive service is automatically stopped and started as needed.
*
* @param enabled boolean, default is true
*/
keepalive(enabled: boolean): void;
}
/**
* $idle, once watch() is called, will start a timeout which if expires, will enter a warning state
* countdown. Once the countdown reaches zero, idle will broadcast a timeout event indicating the
* user has timed out (where your app should log them out or whatever you like). If the user performs
* an action that triggers a watched DOM event that bubbles up to document.body, this will reset the
* idle/warning state and start the process over again.
*/
interface IIdleService {
/**
* Whether or not the watch() has been called and it is watching for idleness.
*/
running(): boolean;
/**
* Whether or not the user appears to be idle.
*/
idling(): boolean;
/**
* Starts watching for idleness, or resets the idle/warning state and continues watching.
*/
watch(): void;
/**
* Stops watching for idleness, and resets the idle/warning state.
*/
unwatch(): void;
}
}
+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;
}
}
@@ -12,55 +12,53 @@ interface TestScope extends ng.IScope {
property: string;
}
module ng.local.storage.tests {
export class TestController {
constructor($scope: TestScope, localStorageService: ng.local.storage.ILocalStorageService) {
// isSupported
if (localStorageService.isSupported) {
// do something
}
// getStorageType
var storageType: string = localStorageService.getStorageType();
// set
$scope.submit = (key, value) => {
return localStorageService.set(key, value);
};
// get
$scope.getItem = (key) => {
return localStorageService.get(key);
};
// remove
$scope.removeItem = (key) => {
return localStorageService.remove(key);
};
// clearAll(regexp)
$scope.clearNumbers = () => {
return localStorageService.clearAll(/^\d+$/);
};
// clearAll
$scope.clearAll = () => {
return localStorageService.clearAll();
};
// keys
var lsKeys = localStorageService.keys();
// bind
localStorageService.set('property', 'oldValue');
$scope.unbind = localStorageService.bind($scope, 'property');
// deriveKey
console.log(localStorageService.deriveKey('property')); // ls.property
// length
var lsLength: number = localStorageService.length();
export class TestController {
constructor($scope: TestScope, localStorageService: ng.local.storage.ILocalStorageService) {
// isSupported
if (localStorageService.isSupported) {
// do something
}
// getStorageType
var storageType: string = localStorageService.getStorageType();
// set
$scope.submit = (key, value) => {
return localStorageService.set(key, value);
};
// get
$scope.getItem = (key) => {
return localStorageService.get<string>(key);
};
// remove
$scope.removeItem = (key) => {
return localStorageService.remove(key);
};
// clearAll(regexp)
$scope.clearNumbers = () => {
return localStorageService.clearAll(/^\d+$/);
};
// clearAll
$scope.clearAll = () => {
return localStorageService.clearAll();
};
// keys
var lsKeys = localStorageService.keys();
// bind
localStorageService.set('property', 'oldValue');
$scope.unbind = localStorageService.bind($scope, 'property');
// deriveKey
console.log(localStorageService.deriveKey('property')); // ls.property
// length
var lsLength: number = localStorageService.length();
}
}
@@ -72,4 +70,4 @@ app.config(function (localStorageServiceProvider: ng.local.storage.ILocalStorage
.setNotify(true, true);
});
app.controller('TestController', ng.local.storage.tests.TestController);
app.controller('TestController', TestController);
+6 -6
View File
@@ -5,8 +5,8 @@
/// <reference path='../angularjs/angular.d.ts' />
declare module ng.local.storage {
interface ILocalStorageServiceProvider extends IServiceProvider {
declare module angular.local.storage {
interface ILocalStorageServiceProvider extends angular.IServiceProvider {
/**
* Setter for the prefix
* You should set a prefix to avoid overwriting any local storage variables from the rest of your app
@@ -92,14 +92,14 @@ declare module ng.local.storage {
* @param key
* @param value
*/
set(key: string, value: string): boolean;
set<T>(key: string, value: T): boolean;
/**
* Directly get a value from local storage.
* If local storage is not supported, use cookies instead.
* Returns: value from local storage
* @param key
*/
get(key: string): string;
get<T>(key: string): T;
/**
* Return array of keys for local storage, ignore keys that not owned.
* Returns: value from local storage
@@ -129,7 +129,7 @@ declare module ng.local.storage {
* @param value optional
* @param key The corresponding key used in local storage
*/
bind(scope:ng.IScope, property: string, value?: any, key?: string): Function;
bind(scope: angular.IScope, property: string, value?: any, key?: string): Function;
/**
* Return the derive key
* Returns String
@@ -146,4 +146,4 @@ declare module ng.local.storage {
*/
cookie:ICookie;
}
}
}
@@ -0,0 +1,126 @@
/// <reference path='../angularjs/angular.d.ts' />
/// <reference path='angular-localForage.d.ts' />
var app = angular.module('angular-localForage-tests', ['LocalForageModule']);
app.config(function (localStorageServiceProvider:angular.localForage.ILocalForageProvider) {
//TODO
});
var $rootScope:angular.IRootScopeService,
$localForage:angular.localForage.ILocalForageService,
instanceVersion = 0;
// create a fresh instance
$localForage.clear().then(function () {
$localForage = $localForage.createInstance({
name: ++instanceVersion
});
});
$localForage.getItem('this key is unknown').then(function (value) {
});
$localForage.setItem('myName', 'Olivier Combe').then(function (data) {
$localForage.getItem('myName').then(function (data) {
});
});
var values = ['Olivier Combe', 'AngularJs', 'Open Source'];
$localForage.setItem(['myName', 'myPassion', 'myHobbie'], values).then(function (data) {
$localForage.getItem(['myHobbie', 'myName']).then(function (data) {
});
});
$localForage.removeItem('myName').then(function () {
$localForage.getItem('myName').then(function (data) {
});
});
$localForage.removeItem(['myName', 'myPassion']).then(function () {
$localForage.getItem(['myName', 'myPassion', 'myHobbie']).then(function (data) {
});
});
$localForage.pull('myName').then(function (data) {
$localForage.getItem('myName').then(function (data) {
});
});
$localForage.pull(['myName', 'myPassion']).then(function (data) {
$localForage.getItem(['myName', 'myPassion', 'myHobbie']).then(function (data) {
});
});
$localForage.setItem('myName', 'Olivier Combe').then(function (d) {
$localForage.getItem('myName').then(function (data) {
});
});
$localForage.setDriver('localStorageWrapper').then(function () {
$localForage.setItem('myName', 'Olivier Combe').then(function (d) {
$localForage.getItem('myName').then(function (data) {
});
});
});
$localForage.setItem('myArray', [{
$$hashKey: '00A',
name: 'Olivier Combe'
}]).then(function (d) {
$localForage.getItem('myArray').then(function (data) {
});
});
$localForage.setDriver('localStorageWrapper').then(function () {
$localForage.setItem('myArray', [{
$$hashKey: '00A',
name: 'Olivier Combe'
}]).then(function (d) {
$localForage.getItem('myArray').then(function (data) {
});
});
});
var aFileParts = ["<a id=\"a\"><b id=\"b\">hey!<\/b><\/a>"];
var oMyBlob = new Blob(aFileParts, {"type": "text\/xml"}); // the blob
$localForage.setItem('myBlob', oMyBlob).then(function (data) {
});
// $localForage.setItem(['myName', 'myPassion', 'myHobbie'], 'value');
// $localForage.setItem();
$localForage.iterate(function (value, key) {
}).then(function (data) {
});
$localForage.iterate(function (value, key) {
if (key == 'myPassion') {
return value;
}
}).then(function (data) {
});
+63
View File
@@ -0,0 +1,63 @@
// Type definitions for angular-localForage 1.2.2
// Project: https://github.com/ocombe/angular-localForage
// Definitions by: Stefan Steinhart <https://github.com/reppners>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../localForage/localForage.d.ts" />
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.localForage {
interface LocalForageConfig {
driver?:string;
name?:string | number;
version?:number;
storeName?:string;
description?:string;
}
interface ILocalForageProvider {
config(config:LocalForageConfig):void;
setNotify(onItemSet:boolean, onItemRemove:boolean):void;
}
interface ILocalForageService {
setDriver(driver:string):angular.IPromise<void>;
driver<T>():lf.ILocalForage<T>;
setItem(key:string, value:any):angular.IPromise<void>;
setItem(keys:Array<string>, values:Array<any>):angular.IPromise<void>;
getItem(key:string):angular.IPromise<any>;
getItem(keys:Array<string>):angular.IPromise<Array<any>>;
removeItem(key:string | Array<string>):angular.IPromise<void>;
pull(key:string):angular.IPromise<any>;
pull(keys:Array<string>):angular.IPromise<Array<any>>;
clear():angular.IPromise<void>;
key(n:number):angular.IPromise<string>;
keys():angular.IPromise<string>;
length():angular.IPromise<number>;
iterate<T>(iteratorCallback:(value:string | number, key:string)=>T):angular.IPromise<T>;
bind($scope:ng.IScope, key:string):void;
bind($scope:ng.IScope, config:{
key:string;
defaultValue:any;
scopeKey:string;
name:string;
}):void;
unbind($scope:ng.IScope, key:string, scopeKey?:string):void;
createInstance(config:LocalForageConfig):ILocalForageService;
instance(name:string):ILocalForageService;
}
}
+195
View File
@@ -0,0 +1,195 @@
// Type definitions for Angular Material 0.8.3+ (angular.material module)
// Project: https://github.com/angular/material
// Definitions by: Matt Traynham <https://github.com/mtraynham>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.material {
interface MDBottomSheetOptions {
templateUrl?: string;
template?: string;
controller?: any;
locals?: {[index: string]: any};
targetEvent?: any;
resolve?: {[index: string]: angular.IPromise<any>}
controllerAs?: string;
parent?: Element;
disableParentScroll?: boolean;
}
interface MDBottomSheetService {
show(options: MDBottomSheetOptions): angular.IPromise<any>;
hide(response?: any): void;
cancel(response?: any): void;
}
interface MDPresetDialog<T> {
title(title: string): T;
content(content: string): T;
ok(content: string): T;
theme(theme: string): T;
}
interface MDAlertDialog extends MDPresetDialog<MDAlertDialog> {
}
interface MDConfirmDialog extends MDPresetDialog<MDConfirmDialog> {
cancel(reason?: string): MDConfirmDialog;
}
interface MDDialogOptions {
templateUrl?: string;
template?: string;
domClickEvent?: any;
disableParentScroll?: boolean;
clickOutsideToClose?: boolean;
hasBackdrop?: boolean;
escapeToClose?: boolean;
controller?: any;
locals?: {[index: string]: any};
bindToController?: boolean;
resolve?: {[index: string]: angular.IPromise<any>}
controllerAs?: string;
parent?: Element;
onComplete?: Function;
}
interface MDDialogService {
show(dialog: MDDialogOptions|MDPresetDialog<any>): angular.IPromise<any>;
confirm(): MDConfirmDialog;
alert(): MDAlertDialog;
hide(response?: any): void;
cancel(response?: any): void;
}
interface MDIcon {
(path: string): angular.IPromise<Element>;
}
interface MDIconProvider {
icon(id: string, url: string, iconSize?: string): MDIconProvider;
iconSet(id: string, url: string, iconSize?: string): MDIconProvider;
defaultIconSet(url: string, iconSize?: string): MDIconProvider;
defaultIconSize(iconSize: string): MDIconProvider;
}
interface MDMedia {
(media: string): boolean;
}
interface MDSidenavObject {
toggle(): void;
open(): void;
close(): void;
isOpen(): boolean;
isLockedOpen(): boolean;
}
interface MDSidenavService {
(component: string): MDSidenavObject;
}
interface MDToastPreset<T> {
content(content: string): T;
action(action: string): T;
highlightAction(highlightAction: boolean): T;
capsule(capsule: boolean): T;
theme(theme: string): T;
hideDelay(delay: number): T;
}
interface MDSimpleToastPreset extends MDToastPreset<MDSimpleToastPreset> {
}
interface MDToastOptions {
templateUrl?: string;
template?: string;
hideDelay?: number;
position?: string;
controller?: any;
locals?: {[index: string]: any};
bindToController?: boolean;
resolve?: {[index: string]: angular.IPromise<any>}
controllerAs?: string;
parent?: Element;
}
interface MDToastService {
show(optionsOrPreset: MDToastOptions|MDToastPreset<any>): angular.IPromise<any>;
showSimple(): angular.IPromise<any>;
simple(): MDSimpleToastPreset;
build(): MDToastPreset<any>;
updateContent(): void;
hide(response?: any): void;
cancel(response?: any): void;
}
interface MDPalette {
0?: string;
50?: string;
100?: string;
200?: string;
300?: string;
400?: string;
500?: string;
600?: string;
700?: string;
800?: string;
900?: string;
A100?: string;
A200?: string;
A400?: string;
A700?: string;
contrastDefaultColor?: string;
contrastDarkColors?: string;
contrastStrongLightColors?: string;
}
interface MDThemeHues {
default?: string;
'hue-1'?: string;
'hue-2'?: string;
'hue-3'?: string;
}
interface MDThemePalette {
name: string;
hues: MDThemeHues;
}
interface MDThemeColors {
accent: MDThemePalette;
background: MDThemePalette;
primary: MDThemePalette;
warn: MDThemePalette;
}
interface MDThemeGrayScalePalette {
1: string;
2: string;
3: string;
4: string;
name: string;
}
interface MDTheme {
name: string;
colors: MDThemeColors;
foregroundPalette: MDThemeGrayScalePalette;
foregroundShadow: string;
accentPalette(name: string, hues?: MDThemeHues): MDTheme;
primaryPalette(name: string, hues?: MDThemeHues): MDTheme;
warnPalette(name: string, hues?: MDThemeHues): MDTheme;
backgroundPalette(name: string, hues?: MDThemeHues): MDTheme;
dark(isDark?: boolean): MDTheme;
}
interface MDThemingProvider {
theme(name: string, inheritFrom?: string): MDTheme;
definePalette(name: string, palette: MDPalette): MDThemingProvider;
extendPalette(name: string, palette: MDPalette): MDPalette;
setDefaultTheme(theme: string): void;
alwaysWatchTheme(alwaysWatch: boolean): void;
}
}
+204
View File
@@ -0,0 +1,204 @@
// Type definitions for Angular Material 0.9.0-rc1+ (angular.material module)
// Project: https://github.com/angular/material
// Definitions by: Matt Traynham <https://github.com/mtraynham>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.material {
interface MDBottomSheetOptions {
templateUrl?: string;
template?: string;
scope?: angular.IScope; // default: new child scope
preserveScope?: boolean; // default: false
controller?: string|Function;
locals?: {[index: string]: any};
targetEvent?: MouseEvent;
resolve?: {[index: string]: angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
disableParentScroll?: boolean; // default: true
}
interface MDBottomSheetService {
show(options: MDBottomSheetOptions): angular.IPromise<any>;
hide(response?: any): void;
cancel(response?: any): void;
}
interface MDPresetDialog<T> {
title(title: string): T;
content(content: string): T;
ok(ok: string): T;
theme(theme: string): T;
}
interface MDAlertDialog extends MDPresetDialog<MDAlertDialog> {
}
interface MDConfirmDialog extends MDPresetDialog<MDConfirmDialog> {
cancel(cancel: string): MDConfirmDialog;
}
interface MDDialogOptions {
templateUrl?: string;
template?: string;
targetEvent?: MouseEvent;
scope?: angular.IScope; // default: new child scope
preserveScope?: boolean; // default: false
disableParentScroll?: boolean; // default: true
hasBackdrop?: boolean // default: true
clickOutsideToClose?: boolean; // default: false
escapeToClose?: boolean; // default: true
focusOnOpen?: boolean; // default: true
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
resolve?: {[index: string]: angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
onComplete?: Function;
}
interface MDDialogService {
show(dialog: MDDialogOptions|MDAlertDialog|MDConfirmDialog): angular.IPromise<any>;
confirm(): MDConfirmDialog;
alert(): MDAlertDialog;
hide(response?: any): void;
cancel(response?: any): void;
}
interface MDIcon {
(id: string): angular.IPromise<Element>; // id is a unique ID or URL
}
interface MDIconProvider {
icon(id: string, url: string, iconSize?: string): MDIconProvider; // iconSize default: '24px'
iconSet(id: string, url: string, iconSize?: string): MDIconProvider; // iconSize default: '24px'
defaultIconSet(url: string, iconSize?: string): MDIconProvider; // iconSize default: '24px'
defaultIconSize(iconSize: string): MDIconProvider; // default: '24px'
}
interface MDMedia {
(media: string): boolean;
}
interface MDSidenavObject {
toggle(): angular.IPromise<void>;
open(): angular.IPromise<void>;
close(): angular.IPromise<void>;
isOpen(): boolean;
isLockedOpen(): boolean;
}
interface MDSidenavService {
(component: string): MDSidenavObject;
}
interface MDToastPreset<T> {
content(content: string): T;
action(action: string): T;
highlightAction(highlightAction: boolean): T;
capsule(capsule: boolean): T;
theme(theme: string): T;
hideDelay(delay: number): T;
position(position: string): T;
}
interface MDSimpleToastPreset extends MDToastPreset<MDSimpleToastPreset> {
}
interface MDToastOptions {
templateUrl?: string;
template?: string;
scope?: angular.IScope; // default: new child scope
preserveScope?: boolean; // default: false
hideDelay?: number; // default (ms): 3000
position?: string; // any combination of 'bottom'/'left'/'top'/'right'/'fit'; default: 'bottom left'
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
resolve?: {[index: string]: angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
}
interface MDToastService {
show(optionsOrPreset: MDToastOptions|MDToastPreset<any>): angular.IPromise<any>;
showSimple(): angular.IPromise<any>;
simple(): MDSimpleToastPreset;
build(): MDToastPreset<any>;
updateContent(): void;
hide(response?: any): void;
cancel(response?: any): void;
}
interface MDPalette {
0?: string;
50?: string;
100?: string;
200?: string;
300?: string;
400?: string;
500?: string;
600?: string;
700?: string;
800?: string;
900?: string;
A100?: string;
A200?: string;
A400?: string;
A700?: string;
contrastDefaultColor?: string;
contrastDarkColors?: string|string[];
contrastLightColors?: string|string[];
}
interface MDThemeHues {
default?: string;
'hue-1'?: string;
'hue-2'?: string;
'hue-3'?: string;
}
interface MDThemePalette {
name: string;
hues: MDThemeHues;
}
interface MDThemeColors {
accent: MDThemePalette;
background: MDThemePalette;
primary: MDThemePalette;
warn: MDThemePalette;
}
interface MDThemeGrayScalePalette {
1: string;
2: string;
3: string;
4: string;
name: string;
}
interface MDTheme {
name: string;
isDark: boolean;
colors: MDThemeColors;
foregroundPalette: MDThemeGrayScalePalette;
foregroundShadow: string;
accentPalette(name: string, hues?: MDThemeHues): MDTheme;
primaryPalette(name: string, hues?: MDThemeHues): MDTheme;
warnPalette(name: string, hues?: MDThemeHues): MDTheme;
backgroundPalette(name: string, hues?: MDThemeHues): MDTheme;
dark(isDark?: boolean): MDTheme;
}
interface MDThemingProvider {
theme(name: string, inheritFrom?: string): MDTheme;
definePalette(name: string, palette: MDPalette): MDThemingProvider;
extendPalette(name: string, palette: MDPalette): MDPalette;
setDefaultTheme(theme: string): void;
alwaysWatchTheme(alwaysWatch: boolean): void;
}
}
@@ -0,0 +1,94 @@
/// <reference path="angular-material.d.ts" />
var myApp = angular.module('testModule', ['ngMaterial']);
myApp.config((
$mdThemingProvider: ng.material.IThemingProvider,
$mdIconProvider: ng.material.IIconProvider) => {
$mdThemingProvider.alwaysWatchTheme(true);
var neonRedMap: ng.material.IPalette = $mdThemingProvider.extendPalette('red', {
'500': 'ff0000'
});
// Register the new color palette map with the name <code>neonRed</code>
$mdThemingProvider.definePalette('neonRed', neonRedMap);
// Use that theme for the primary intentions
$mdThemingProvider.theme('default')
.primaryPalette('neonRed')
.accentPalette('blue')
.backgroundPalette('grey')
.warnPalette('red')
.dark(true);
$mdIconProvider
.defaultIconSet('my/app/icons.svg') // Register a default set of SVG icons
.iconSet('social', 'my/app/social.svg') // Register a named icon set of SVGs
.icon('android', 'my/app/android.svg') // Register a specific icon (by name)
.icon('work:chair', 'my/app/chair.svg'); // Register icon in a specific set
});
myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng.material.IBottomSheetService) => {
$scope['openBottomSheet'] = () => {
$mdBottomSheet.show({
template: '<md-bottom-sheet>Hello!</md-bottom-sheet>'
});
};
$scope['hideBottomSheet'] = $mdBottomSheet.hide.bind($mdBottomSheet, 'hide');
$scope['cancelBottomSheet'] = $mdBottomSheet.cancel.bind($mdBottomSheet, 'cancel');
});
myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material.IDialogService) => {
$scope['openDialog'] = () => {
$mdDialog.show({
template: '<md-dialog>Hello!</md-dialog>'
});
};
$scope['alertDialog'] = () => {
$mdDialog.show($mdDialog.alert().content('Alert!'));
};
$scope['confirmDialog'] = () => {
$mdDialog.show($mdDialog.confirm().content('Confirm!'));
};
$scope['hideDialog'] = $mdDialog.hide.bind($mdDialog, 'hide');
$scope['cancelDialog'] = $mdDialog.cancel.bind($mdDialog, 'cancel');
});
class IconDirective implements ng.IDirective {
private $mdIcon: ng.material.IIcon;
constructor($mdIcon: ng.material.IIcon) {
this.$mdIcon = $mdIcon;
}
public link($scope: ng.IScope, $elm: ng.IAugmentedJQuery) {
this.$mdIcon('android').then((iconEl: Element) => $elm.append(iconEl));
this.$mdIcon('work:chair').then((iconEl: Element) => $elm.append(iconEl));
// Load and cache the external SVG using a URL
this.$mdIcon('img/icons/android.svg').then((iconEl: Element) => {
$elm.append(iconEl);
});
}
}
myApp.directive('icon-directive', ($mdIcon: ng.material.IIcon) => new IconDirective($mdIcon));
myApp.controller('MediaController', ($scope: ng.IScope, $mdMedia: ng.material.IMedia) => {
$scope.$watch(() => $mdMedia('lg'), (big: boolean) => {
$scope['bigScreen'] = big;
});
$scope['screenIsSmall'] = $mdMedia('sm');
$scope['customQuery'] = $mdMedia('(min-width: 1234px)');
$scope['anotherCustom'] = $mdMedia('max-width: 300px');
});
myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.material.ISidenavService) => {
var componentId = 'left';
$scope['toggle'] = () => $mdSidenav(componentId).toggle();
$scope['open'] = () => $mdSidenav(componentId).open();
$scope['close'] = () => $mdSidenav(componentId).close();
$scope['isOpen'] = $mdSidenav(componentId).isOpen();
$scope['isLockedOpen'] = $mdSidenav(componentId).isLockedOpen();
});
myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => {
$scope['openToast'] = () => $mdToast.show($mdToast.simple().content('Hello!'));
});
+223
View File
@@ -0,0 +1,223 @@
// Type definitions for Angular Material 0.10.1-rc1+ (angular.material module)
// Project: https://github.com/angular/material
// Definitions by: Matt Traynham <https://github.com/mtraynham>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.material {
interface IBottomSheetOptions {
templateUrl?: string;
template?: string;
scope?: angular.IScope; // default: new child scope
preserveScope?: boolean; // default: false
controller?: string|Function;
locals?: {[index: string]: any};
targetEvent?: MouseEvent;
resolve?: {[index: string]: angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
disableParentScroll?: boolean; // default: true
}
interface IBottomSheetService {
show(options: IBottomSheetOptions): angular.IPromise<any>;
hide(response?: any): void;
cancel(response?: any): void;
}
interface IPresetDialog<T> {
title(title: string): T;
content(content: string): T;
ok(ok: string): T;
theme(theme: string): T;
templateUrl(templateUrl?: string): T;
template(template?: string): T;
targetEvent(targetEvent?: MouseEvent): T;
scope(scope?: angular.IScope): T; // default: new child scope
preserveScope(preserveScope?: boolean): T; // default: false
disableParentScroll(disableParentScroll?: boolean): T; // default: true
hasBackdrop(hasBackdrop?: boolean): T; // default: true
clickOutsideToClose(clickOutsideToClose?: boolean): T; // default: false
escapeToClose(escapeToClose?: boolean): T; // default: true
focusOnOpen(focusOnOpen?: boolean): T; // default: true
controller(controller?: string|Function): T;
locals(locals?: {[index: string]: any}): T;
bindToController(bindToController?: boolean): T; // default: false
resolve(resolve?: {[index: string]: angular.IPromise<any>}): T;
controllerAs(controllerAs?: string): T;
parent(parent?: string|Element|JQuery): T; // default: root node
onComplete(onComplete?: Function): T;
ariaLabel(ariaLabel: string): T;
}
interface IAlertDialog extends IPresetDialog<IAlertDialog> {
}
interface IConfirmDialog extends IPresetDialog<IConfirmDialog> {
cancel(cancel: string): IConfirmDialog;
}
interface IDialogOptions {
templateUrl?: string;
template?: string;
targetEvent?: MouseEvent;
scope?: angular.IScope; // default: new child scope
preserveScope?: boolean; // default: false
disableParentScroll?: boolean; // default: true
hasBackdrop?: boolean // default: true
clickOutsideToClose?: boolean; // default: false
escapeToClose?: boolean; // default: true
focusOnOpen?: boolean; // default: true
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
resolve?: {[index: string]: angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
onComplete?: Function;
}
interface IDialogService {
show(dialog: IDialogOptions|IAlertDialog|IConfirmDialog): angular.IPromise<any>;
confirm(): IConfirmDialog;
alert(): IAlertDialog;
hide(response?: any): void;
cancel(response?: any): void;
}
interface IIcon {
(id: string): angular.IPromise<Element>; // id is a unique ID or URL
}
interface IIconProvider {
icon(id: string, url: string, viewBoxSize?: number): IIconProvider; // viewBoxSize default: 24
iconSet(id: string, url: string, viewBoxSize?: number): IIconProvider; // viewBoxSize default: 24
defaultIconSet(url: string, viewBoxSize?: number): IIconProvider; // viewBoxSize default: 24
defaultViewBoxSize(viewBoxSize: number): IIconProvider; // default: 24
defaultFontSet(name: string): IIconProvider;
}
interface IMedia {
(media: string): boolean;
}
interface ISidenavObject {
toggle(): angular.IPromise<void>;
open(): angular.IPromise<void>;
close(): angular.IPromise<void>;
isOpen(): boolean;
isLockedOpen(): boolean;
}
interface ISidenavService {
(component: string): ISidenavObject;
}
interface IToastPreset<T> {
content(content: string): T;
action(action: string): T;
highlightAction(highlightAction: boolean): T;
capsule(capsule: boolean): T;
theme(theme: string): T;
hideDelay(delay: number): T;
position(position: string): T;
}
interface ISimpleToastPreset extends IToastPreset<ISimpleToastPreset> {
}
interface IToastOptions {
templateUrl?: string;
template?: string;
scope?: angular.IScope; // default: new child scope
preserveScope?: boolean; // default: false
hideDelay?: number; // default (ms): 3000
position?: string; // any combination of 'bottom'/'left'/'top'/'right'/'fit'; default: 'bottom left'
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
resolve?: {[index: string]: angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
}
interface IToastService {
show(optionsOrPreset: IToastOptions|IToastPreset<any>): angular.IPromise<any>;
showSimple(content: string): angular.IPromise<any>;
simple(): ISimpleToastPreset;
build(): IToastPreset<any>;
updateContent(): void;
hide(response?: any): void;
cancel(response?: any): void;
}
interface IPalette {
0?: string;
50?: string;
100?: string;
200?: string;
300?: string;
400?: string;
500?: string;
600?: string;
700?: string;
800?: string;
900?: string;
A100?: string;
A200?: string;
A400?: string;
A700?: string;
contrastDefaultColor?: string;
contrastDarkColors?: string|string[];
contrastLightColors?: string|string[];
}
interface IThemeHues {
default?: string;
'hue-1'?: string;
'hue-2'?: string;
'hue-3'?: string;
}
interface IThemePalette {
name: string;
hues: IThemeHues;
}
interface IThemeColors {
accent: IThemePalette;
background: IThemePalette;
primary: IThemePalette;
warn: IThemePalette;
}
interface IThemeGrayScalePalette {
1: string;
2: string;
3: string;
4: string;
name: string;
}
interface ITheme {
name: string;
isDark: boolean;
colors: IThemeColors;
foregroundPalette: IThemeGrayScalePalette;
foregroundShadow: string;
accentPalette(name: string, hues?: IThemeHues): ITheme;
primaryPalette(name: string, hues?: IThemeHues): ITheme;
warnPalette(name: string, hues?: IThemeHues): ITheme;
backgroundPalette(name: string, hues?: IThemeHues): ITheme;
dark(isDark?: boolean): ITheme;
}
interface IThemingProvider {
theme(name: string, inheritFrom?: string): ITheme;
definePalette(name: string, palette: IPalette): IThemingProvider;
extendPalette(name: string, palette: IPalette): IPalette;
setDefaultTheme(theme: string): void;
alwaysWatchTheme(alwaysWatch: boolean): void;
}
}
+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 { }
}
+2 -2
View File
@@ -5,7 +5,7 @@
///<reference path="../angularjs/angular.d.ts" />
declare module ng.cgNotify {
declare module angular.cgNotify {
interface INotifyService {
@@ -113,4 +113,4 @@ declare module ng.cgNotify {
*/
close():void;
}
}
}
@@ -0,0 +1,199 @@
/// <reference path="angular-odata-resources.d.ts" />
interface IMyResource extends OData.IResource<IMyResource> { };
interface IMyResourceClass extends OData.IResourceClass<IMyResource> { };
///////////////////////////////////////
// IActionDescriptor
///////////////////////////////////////
var actionDescriptor: OData.IActionDescriptor;
actionDescriptor.url = '/api/test-url/'
actionDescriptor.headers = { header: 'value' };
actionDescriptor.isArray = true;
actionDescriptor.method = 'method action';
actionDescriptor.params = { key: 'value' };
///////////////////////////////////////
// IResourceClass
///////////////////////////////////////
var resourceClass: IMyResourceClass;
var resource: IMyResource;
var resourceArray: OData.IResourceArray<IMyResource>;
resource = resourceClass.delete();
resource = resourceClass.delete({ key: 'value' });
resource = resourceClass.delete({ key: 'value' }, function() { });
resource = resourceClass.delete(function() { });
resource = resourceClass.delete(function() { }, function() { });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' }, function() { });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' }, function() { }, function() { });
resource.$promise.then(function(data: IMyResource) { });
resource = resourceClass.get();
resource = resourceClass.get({ key: 'value' });
resource = resourceClass.get({ key: 'value' }, function() { });
resource = resourceClass.get(function() { });
resource = resourceClass.get(function() { }, function() { });
resource = resourceClass.get({ key: 'value' }, { key: 'value' });
resource = resourceClass.get({ key: 'value' }, { key: 'value' }, function() { });
resource = resourceClass.get({ key: 'value' }, { key: 'value' }, function() { }, function() { });
resourceArray = resourceClass.query();
resourceArray = resourceClass.query({ key: 'value' });
resourceArray = resourceClass.query({ key: 'value' }, function() { });
resourceArray = resourceClass.query(function() { });
resourceArray = resourceClass.query(function() { }, function() { });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function() { });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function() { }, function() { });
resourceArray.push(resource);
resourceArray.$promise.then(function(data: OData.IResourceArray<IMyResource>) { });
resource = resourceClass.remove();
resource = resourceClass.remove({ key: 'value' });
resource = resourceClass.remove({ key: 'value' }, function() { });
resource = resourceClass.remove(function() { });
resource = resourceClass.remove(function() { }, function() { });
resource = resourceClass.remove({ key: 'value' }, { key: 'value' });
resource = resourceClass.remove({ key: 'value' }, { key: 'value' }, function() { });
resource = resourceClass.remove({ key: 'value' }, { key: 'value' }, function() { }, function() { });
resource = resourceClass.save();
resource = resourceClass.save({ key: 'value' });
resource = resourceClass.save({ key: 'value' }, function() { });
resource = resourceClass.save(function() { });
resource = resourceClass.save(function() { }, function() { });
resource = resourceClass.save({ key: 'value' }, { key: 'value' });
resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function() { });
resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function() { }, function() { });
///////////////////////////////////////
// IResource
///////////////////////////////////////
var promise: angular.IPromise<IMyResource>;
var arrayPromise: angular.IPromise<IMyResource[]>;
promise = resource.$delete();
promise = resource.$delete({ key: 'value' });
promise = resource.$delete({ key: 'value' }, function() { });
promise = resource.$delete(function() { });
promise = resource.$delete(function() { }, function() { });
promise = resource.$delete({ key: 'value' }, function() { }, function() { });
promise.then(function(data: IMyResource) { });
promise = resource.$get();
promise = resource.$get({ key: 'value' });
promise = resource.$get({ key: 'value' }, function() { });
promise = resource.$get(function() { });
promise = resource.$get(function() { }, function() { });
promise = resource.$get({ key: 'value' }, function() { }, function() { });
arrayPromise = resourceArray[0].$query();
arrayPromise = resourceArray[0].$query({ key: 'value' });
arrayPromise = resourceArray[0].$query({ key: 'value' }, function() { });
arrayPromise = resourceArray[0].$query(function() { });
arrayPromise = resourceArray[0].$query(function() { }, function() { });
arrayPromise = resourceArray[0].$query({ key: 'value' }, function() { }, function() { });
arrayPromise.then(function(data: OData.IResourceArray<IMyResource>) { });
promise = resource.$remove();
promise = resource.$remove({ key: 'value' });
promise = resource.$remove({ key: 'value' }, function() { });
promise = resource.$remove(function() { });
promise = resource.$remove(function() { }, function() { });
promise = resource.$remove({ key: 'value' }, function() { }, function() { });
promise = resource.$save();
promise = resource.$save({ key: 'value' });
promise = resource.$save({ key: 'value' }, function() { });
promise = resource.$save(function() { });
promise = resource.$save(function() { }, function() { });
promise = resource.$save({ key: 'value' }, function() { }, function() { });
///////////////////////////////////////
// IResourceService
///////////////////////////////////////
var resourceService: OData.IResourceService;
resourceClass = resourceService<IMyResource, IMyResourceClass>('test');
resourceClass = resourceService<IMyResource>('test');
resourceClass = resourceService('test');
///////////////////////////////////////
// IModule
///////////////////////////////////////
var mod: ng.IModule;
var resourceServiceFactoryFunction: OData.IResourceServiceFactoryFunction<IMyResource>;
var resourceService: OData.IResourceService;
resourceClass = resourceServiceFactoryFunction<IMyResourceClass>(resourceService);
resourceServiceFactoryFunction = function(resourceService: OData.IResourceService) { return <any>resourceClass; };
mod = mod.factory('factory name', resourceServiceFactoryFunction);
///////////////////////////////////////
// IResource
///////////////////////////////////////
///////////////////////////////////////
// IResourceServiceProvider
///////////////////////////////////////
var resourceServiceProvider: OData.IResourceServiceProvider;
resourceServiceProvider.defaults.stripTrailingSlashes = false;
///////////////////////////////////////
// OData
///////////////////////////////////////
interface User extends OData.IResource<User> {
name: string;
}
var resourceService: OData.IResourceService;
var odataResourceClass = resourceService<User>("my/url", {}, {}, { odata: { method: 'POST' } });
var Value: OData.ValueFactory;
var Property: OData.PropertyFactory;
var Predicate: OData.PredicateFactory;
var users = odataResourceClass.odata().query();
users[0].name;
users[0].$save;
users[0].$update;
var user = odataResourceClass.odata()
.filter(new Value("1", OData.ValueTypes.Int32), new Property("abc"))
.filter("Name", "John")
.filter("Age", ">", 20)
.skip(10)
.take(20)
.orderBy("Name", "desc")
.single();
user.$save();
var predicate1 = new Predicate("a", "b");
var predicate2 = new Predicate("c", "d");
var predicate3 = new Predicate("Age", '>', 10);
var combination1 = Predicate.or([predicate1, predicate2]);
var combination2 = Predicate.and([combination1, predicate2]);
var predicate = new Predicate("FirstName", "John")
.or(new Predicate("LastName", '!=', "Doe"))
.and(new Predicate("Age", '>', 10));
users = odataResourceClass.odata()
.withInlineCount()
.query();
var countResult = odataResourceClass.odata().count();
var total = countResult.result;
+321
View File
@@ -0,0 +1,321 @@
// Type definitions for OData Angular Resources
// Project: https://github.com/devnixs/ODataAngularResources
// Definitions by: Raphael ATALLAH <http://raphael.atallah.me>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module OData {
/**
* Currently supported options for the $resource factory options argument.
*/
interface IResourceOptions {
/**
* If true then the trailing slashes from any calculated URL will be stripped (defaults to true)
*/
stripTrailingSlashes?: boolean;
odata?: {
url?: string;
method?: string;
};
}
///////////////////////////////////////////////////////////////////////////
// ResourceService
// see http://docs.angularjs.org/api/ngResource.$resource
// Most part of the following definitions were achieved by analyzing the
// actual implementation, since the documentation doesn't seem to cover
// that deeply.
///////////////////////////////////////////////////////////////////////////
interface IResourceService {
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): IResourceClass<IResource<any>>;
<T, U>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): U;
<T>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): IResourceClass<T>;
}
// Just a reference to facilitate describing new actions
interface IActionDescriptor {
url?: string;
method: string;
isArray?: boolean;
params?: any;
headers?: any;
}
// Baseclass for everyresource with default actions.
// If you define your new actions for the resource, you will need
// to extend this interface and typecast the ResourceClass to it.
//
// In case of passing the first argument as anything but a function,
// it's gonna be considered data if the action method is POST, PUT or
// PATCH (in other words, methods with body). Otherwise, it's going
// to be considered as parameters to the request.
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L461-L465
//
// Only those methods with an HTTP body do have 'data' as first parameter:
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L463
// More specifically, those methods are POST, PUT and PATCH:
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L432
//
// Also, static calls always return the IResource (or IResourceArray) retrieved
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L549
interface IResourceClass<T> {
new(dataOrParams? : any) : IResource<T>;
get(): IResource<T>;
get(params: Object): IResource<T>;
get(success: Function, error?: Function): IResource<T>;
get(params: Object, success: Function, error?: Function): IResource<T>;
get(params: Object, data: Object, success?: Function, error?: Function): IResource<T>;
query(): IResourceArray<T>;
query(params: Object): IResourceArray<T>;
query(success: Function, error?: Function): IResourceArray<T>;
query(params: Object, success: Function, error?: Function): IResourceArray<T>;
query(params: Object, data: Object, success?: Function, error?: Function): IResourceArray<T>;
save(): IResource<T>;
save(data: Object): IResource<T>;
save(success: Function, error?: Function): IResource<T>;
save(data: Object, success: Function, error?: Function): IResource<T>;
save(params: Object, data: Object, success?: Function, error?: Function): IResource<T>;
update(): IResource<T>;
update(data: Object): IResource<T>;
update(success: Function, error?: Function): IResource<T>;
update(data: Object, success: Function, error?: Function): IResource<T>;
update(params: Object, data: Object, success?: Function, error?: Function): IResource<T>;
remove(): IResource<T>;
remove(params: Object): IResource<T>;
remove(success: Function, error?: Function): IResource<T>;
remove(params: Object, success: Function, error?: Function): IResource<T>;
remove(params: Object, data: Object, success?: Function, error?: Function): IResource<T>;
delete(): IResource<T>;
delete(params: Object): IResource<T>;
delete(success: Function, error?: Function): IResource<T>;
delete(params: Object, success: Function, error?: Function): IResource<T>;
delete(params: Object, data: Object, success?: Function, error?: Function): IResource<T>;
odata(): OData.Provider<T>;
}
// Instance calls always return the the promise of the request which retrieved the object
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L546
interface IResource<T> {
$get(): angular.IPromise<T>;
$get(params?: Object, success?: Function, error?: Function): angular.IPromise<T>;
$get(success: Function, error?: Function): angular.IPromise<T>;
$query(): angular.IPromise<IResourceArray<T>>;
$query(params?: Object, success?: Function, error?: Function): angular.IPromise<IResourceArray<T>>;
$query(success: Function, error?: Function): angular.IPromise<IResourceArray<T>>;
$save(): angular.IPromise<T>;
$save(params?: Object, success?: Function, error?: Function): angular.IPromise<T>;
$save(success: Function, error?: Function): angular.IPromise<T>;
$update(): angular.IPromise<T>;
$update(params?: Object, success?: Function, error?: Function): angular.IPromise<T>;
$update(success: Function, error?: Function): angular.IPromise<T>;
$remove(): angular.IPromise<T>;
$remove(params?: Object, success?: Function, error?: Function): angular.IPromise<T>;
$remove(success: Function, error?: Function): angular.IPromise<T>;
$delete(): angular.IPromise<T>;
$delete(params?: Object, success?: Function, error?: Function): angular.IPromise<T>;
$delete(success: Function, error?: Function): angular.IPromise<T>;
/** the promise of the original server interaction that created this instance. **/
$promise: angular.IPromise<T>;
$resolved: boolean;
}
/**
* Really just a regular Array object with $promise and $resolve attached to it
*/
interface IResourceArray<T> extends Array<T> {
/** the promise of the original server interaction that created this collection. **/
$promise: angular.IPromise<IResourceArray<T>>;
$resolved: boolean;
}
/** when creating a resource factory via IModule.factory */
interface IResourceServiceFactoryFunction<T> {
($resource: OData.IResourceService): IResourceClass<T>;
<U extends IResourceClass<T>>($resource: OData.IResourceService): U;
}
// IResourceServiceProvider used to configure global settings
interface IResourceServiceProvider extends angular.IServiceProvider {
defaults: IResourceOptions;
}
interface IExecutable {
execute(noParenthesis?: any): string;
}
class Global {
static $inject: string[];
constructor(ODataBinaryOperation: any, ODataProvider: any, ODataValue: any, ODataProperty: any, ODataMethodCall: any, ODataPredicate: any, ODataOrderByStatement: any);
Provider: Provider<any>;
BinaryOperation: typeof BinaryOperation;
Value: typeof Value;
Property: typeof Property;
Func: typeof MethodCall;
Predicate: typeof Predicate;
OrderBy: typeof OrderByStatement;
}
interface BinaryOperationFactory {
new (propertyOrPredicate: any, valueOrOperator?: any, value?: any): BinaryOperation;
}
class BinaryOperation implements IExecutable {
private operandA;
private operandB;
private filterOperator;
constructor(propertyOrPredicate: any, valueOrOperator?: any, value?: any);
execute(noParenthesis?: any): string;
or(propertyOrPredicate: any, operatorOrValue?: any, value?: any): BinaryOperation;
and(propertyOrPredicate: any, operatorOrValue?: any, value?: any): BinaryOperation;
}
interface MethodCallFactory {
new (methodName: string, ...args: any[]): MethodCall;
}
class MethodCall implements IExecutable {
private methodName;
private params;
execute(): string;
constructor(methodName: string, ...args: any[]);
}
class Operators {
operators: {
'eq': string[];
'ne': string[];
'gt': string[];
'ge': string[];
'lt': string[];
'le': string[];
'and': string[];
'or': string[];
'not': string[];
'add': string[];
'sub': string[];
'mul': string[];
'div': string[];
'mod': string[];
};
private rtrim;
private trim(value);
convert(from: string): any;
}
interface OrderByStatementFactory {
new (propertyName: string, sortOrder?: string): OrderByStatement;
}
class OrderByStatement implements IExecutable {
private propertyName;
private direction;
execute(): string;
constructor(propertyName: string, sortOrder?: string);
}
interface PredicateFactory {
new (propertyOrValueOrPredicate: any, valueOrOperator?: any, value?: any): Predicate;
or(orStatements: any[]): IExecutable;
create(propertyOrPredicate: any, operatorOrValue?: any, value?: any): IExecutable;
and(andStatements: any): IExecutable;
}
class Predicate extends BinaryOperation {
constructor(propertyOrValueOrPredicate: any, valueOrOperator?: any, value?: any);
static or(orStatements: any[]): IExecutable;
static create(propertyOrPredicate: any, operatorOrValue?: any, value?: any): IExecutable;
static and(andStatements: any): IExecutable;
}
interface PropertyFactory {
new (value: string): Property;
}
class Property implements IExecutable {
private value;
constructor(value: string);
execute(): string;
}
interface ProviderFactory {
new <T>(callback: ProviderCallback<T>): Provider<T>;
}
interface ProviderCallback<T> {
(queryString: string, success: () => any, error: () => any): T[];
(queryString: string, success: () => any, error: () => any, isSingleElement?: boolean, forceSingleElement?: boolean): T;
}
interface ICountResult{
result: number;
}
class Provider<T> {
private callback;
private filters;
private sortOrders;
private takeAmount;
private skipAmount;
private expandables;
constructor(callback: ProviderCallback<T>);
filter(operand1: any, operand2?: any, operand3?: any): Provider<T>;
orderBy(arg1: any, arg2?: any): Provider<T>;
take(amount: number): Provider<T>;
skip(amount: number): Provider<T>;
private execute();
query(success?: any, error?: any): T[];
single(success?: any, error?: any): T;
get(data: any, success?: any, error?: any): T;
expand(params: any, otherParam1?: any, otherParam2?: any, otherParam3?: any, otherParam4?: any, otherParam5?: any, otherParam6?: any, otherParam7?: any): Provider<T>;
count(success?: (result: ICountResult) => any, error?: () => any):ICountResult;
withInlineCount(): Provider<T>;
}
interface ValueFactory {
new (value: any, type?: string): Value;
}
class ValueTypes {
static Boolean: string;
static Byte: string;
static DateTime: string;
static Decimal: string;
static Double: string;
static Single: string;
static Guid: string;
static Int32: string;
static String: string;
}
class Value {
private value;
private type;
private illegalChars;
private escapeIllegalChars(haystack);
private generateDate(date);
executeWithUndefinedType(): any;
executeWithType(): any;
execute(): string;
constructor(value: any, type?: string);
}
}
@@ -374,7 +374,7 @@ function TestElementArrayFinder() {
var b: boolean = elementArrayFinder.isPending();
var locator: webdriver.Locator = elementArrayFinder.locator();
var findersArray: protractor.ElementFinder[] = elementArrayFinder.asElementFinders_();
var findersArrayPromise: protractor.promise.Promise<protractor.ElementFinder[]> = elementArrayFinder.asElementFinders_();
var driverElementArray: webdriver.WebElement[] = elementArrayFinder.getWebElements();
var elementFinder: protractor.ElementFinder = elementArrayFinder.get(42);
+16 -111
View File
@@ -534,7 +534,7 @@ declare module protractor {
all(locator: webdriver.Locator): ElementArrayFinder;
}
interface ElementFinder extends webdriver.IWebElement, webdriver.promise.IThenable<ElementFinder> {
interface ElementFinder extends webdriver.IWebElement, webdriver.promise.IThenable<any> {
/**
* Calls to element may be chained to find elements within a parent.
*
@@ -564,7 +564,7 @@ declare module protractor {
*/
element(subLocator: webdriver.Locator): ElementFinder;
/**
/**
* Calls to element may be chained to find an array of elements within a parent.
*
* @alias element(locator).all(locator)
@@ -652,7 +652,7 @@ declare module protractor {
/**
* Override for WebElement.prototype.isElementPresent so that protractor waits
* for Angular to settle before making the check.
*
*
* @see ElementFinder.isPresent
*
* @param {webdriver.Locator} subLocator Locator for element to look for.
@@ -701,103 +701,6 @@ declare module protractor {
*/
allowAnimations(value: string): ElementFinder;
/**
* Cancels the computation of this promise's value, rejecting the promise in the
* process. This method is a no-op if the promise has alreayd been resolved.
*
* @param {string=} opt_reason The reason this promise is being cancelled.
*/
cancel(opt_reason?: string): void;
/** @return {boolean} Whether this promise's value is still being computed. */
isPending(): boolean;
/**
* Registers listeners for when this instance is resolved.
*
* @param {?(function(T): (R|webdriver.promise.Promise.<R>))=} opt_callback The
* function to call if this promise is successfully resolved. The function
* should expect a single argument: the promise's resolved value.
* @param {?(function(*): (R|webdriver.promise.Promise.<R>))=} opt_errback The
* function to call if this promise is rejected. The function should expect
* a single argument: the rejection reason.
* @return {!webdriver.promise.Promise.<R>} A new promise which will be
* resolved with the result of the invoked callback.
* @template R
*/
then<R>(opt_callback?: (value: ElementFinder) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise<R>;
/**
* Registers a listener for when this promise is rejected. This is synonymous
* with the {@code catch} clause in a synchronous API:
* <pre><code>
* // Synchronous API:
* try {
* doSynchronousWork();
* } catch (ex) {
* console.error(ex);
* }
*
* // Asynchronous promise API:
* doAsynchronousWork().thenCatch(function(ex) {
* console.error(ex);
* });
* </code></pre>
*
* @param {function(*): (R|webdriver.promise.Promise.<R>)} errback The function
* to call if this promise is rejected. The function should expect a single
* argument: the rejection reason.
* @return {!webdriver.promise.Promise.<R>} A new promise which will be
* resolved with the result of the invoked callback.
* @template R
*/
thenCatch<R>(errback: (error: any) => any): webdriver.promise.Promise<R>;
/**
* Registers a listener to invoke when this promise is resolved, regardless
* of whether the promise's value was successfully computed. This function
* is synonymous with the {@code finally} clause in a synchronous API:
* <pre><code>
* // Synchronous API:
* try {
* doSynchronousWork();
* } finally {
* cleanUp();
* }
*
* // Asynchronous promise API:
* doAsynchronousWork().thenFinally(cleanUp);
* </code></pre>
*
* <b>Note:</b> similar to the {@code finally} clause, if the registered
* callback returns a rejected promise or throws an error, it will silently
* replace the rejection error (if any) from this promise:
* <pre><code>
* try {
* throw Error('one');
* } finally {
* throw Error('two'); // Hides Error: one
* }
*
* webdriver.promise.rejected(Error('one'))
* .thenFinally(function() {
* throw Error('two'); // Hides Error: one
* });
* </code></pre>
*
*
* @param {function(): (R|webdriver.promise.Promise.<R>)} callback The function
* to call when this promise is resolved.
* @return {!webdriver.promise.Promise.<R>} A promise that will be fulfilled
* with the callback result.
* @template R
*/
thenFinally<R>(callback: () => any): webdriver.promise.Promise<R>;
/**
* Create a shallow copy of ElementFinder.
*
@@ -976,7 +879,7 @@ declare module protractor {
* filteredElements[0].click();
* });
*
* @param {function(ElementFinder, number): webdriver.WebElement.Promise} filterFn
* @param {function(ElementFinder, number): webdriver.WebElement.Promise} filterFn
* Filter function that will test if an element should be returned.
* filterFn can either return a boolean or a promise that resolves to a boolean.
* @return {!ElementArrayFinder} A ElementArrayFinder that represents an array
@@ -985,11 +888,11 @@ declare module protractor {
filter(filterFn: (element: ElementFinder, index: number) => any): ElementArrayFinder;
/**
* Apply a reduce function against an accumulator and every element found
* Apply a reduce function against an accumulator and every element found
* using the locator (from left-to-right). The reduce function has to reduce
* every element into a single value (the accumulator). Returns promise of
* the accumulator. The reduce function receives the accumulator, current
* ElementFinder, the index, and the entire array of ElementFinders,
* every element into a single value (the accumulator). Returns promise of
* the accumulator. The reduce function receives the accumulator, current
* ElementFinder, the index, and the entire array of ElementFinders,
* respectively.
*
* @alias element.all(locator).reduce(reduceFn)
@@ -1009,21 +912,22 @@ declare module protractor {
*
* expect(value).toEqual('First Second Third ');
*
* @param {function(number, ElementFinder, number, Array.<ElementFinder>)}
* @param {function(number, ElementFinder, number, Array.<ElementFinder>)}
* reduceFn Reduce function that reduces every element into a single value.
* @param {*} initialValue Initial value of the accumulator.
* @param {*} initialValue Initial value of the accumulator.
* @return {!webdriver.promise.Promise} A promise that resolves to the final
* value of the accumulator.
* value of the accumulator.
*/
reduce<T>(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => webdriver.promise.Promise<T>, initialValue: T): webdriver.promise.Promise<T>;
reduce<T>(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => T, initialValue: T): webdriver.promise.Promise<T>;
/**
* Represents the ElementArrayFinder as an array of ElementFinders.
*
* @return {Array.<ElementFinder>} Return a promise, which resolves to a list
* @return {Array.<ElementFinder>} Return a promise, which resolves to a list
* of ElementFinders specified by the locator.
*/
asElementFinders_(): ElementFinder[];
asElementFinders_(): webdriver.promise.Promise<ElementFinder[]>;
/**
* Create a shallow copy of ElementArrayFinder.
@@ -1317,6 +1221,7 @@ declare module protractor {
interface LocatorWithColumn extends webdriver.Locator {
column(index: number): webdriver.Locator;
column(name: string): webdriver.Locator;
}
interface RepeaterLocator extends LocatorWithColumn {
@@ -1395,7 +1300,7 @@ declare module protractor {
* expect(element(by.exactBinding('person_phone')).isPresent()).toBe(true);
* expect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true);
* expect(element(by.exactBinding('phone')).isPresent()).toBe(false);
*
*
* @param {string} bindingDescriptor
* @return {{findElementsOverride: findElementsOverride, toString: Function|string}}
*/
+64
View File
@@ -0,0 +1,64 @@
/// <reference path="angular-scroll.d.ts" />
module TestApp {
class TestController {
constructor($scope: ng.IScope, $document: duScroll.IDocumentService) {
var positionFromTop = 400;
var positionFromLeft = 200;
var offsetInPixels = 100;
var durationInMillis = 2000;
var someElement: ng.IAugmentedJQuery;
$document.duScrollTo(positionFromLeft, positionFromTop);
$document.duScrollTo(positionFromLeft, positionFromTop, durationInMillis).then(this.onScrollCompleted);
$document.duScrollTo(positionFromLeft, positionFromTop, durationInMillis, this.invertedEasingFn).then(this.onScrollCompleted);
$document.duScrollTo(someElement);
$document.duScrollTo(someElement, offsetInPixels);
$document.duScrollTo(someElement, offsetInPixels, durationInMillis).then(this.onScrollCompleted);
$document.duScrollTo(someElement, offsetInPixels, durationInMillis, this.invertedEasingFn).then(this.onScrollCompleted);
$document.duScrollToElement(someElement);
$document.duScrollToElement(someElement, offsetInPixels);
$document.duScrollToElement(someElement, offsetInPixels, durationInMillis).then(this.onScrollCompleted);
$document.duScrollToElement(someElement, offsetInPixels, durationInMillis, this.invertedEasingFn).then(this.onScrollCompleted);
$document.duScrollToElementAnimated(someElement).then(this.onScrollCompleted);
$document.duScrollToElementAnimated(someElement, offsetInPixels).then(this.onScrollCompleted);
$document.duScrollToElementAnimated(someElement, offsetInPixels, durationInMillis).then(this.onScrollCompleted);
$document.duScrollToElementAnimated(someElement, offsetInPixels, durationInMillis, this.invertedEasingFn).then(this.onScrollCompleted);
$document.duScrollTop(positionFromTop);
$document.duScrollTop(positionFromTop, durationInMillis).then(this.onScrollCompleted);
$document.duScrollTop(positionFromTop, durationInMillis, this.invertedEasingFn).then(this.onScrollCompleted);
$document.duScrollTopAnimated(positionFromTop).then(this.onScrollCompleted);
$document.duScrollTopAnimated(positionFromTop, durationInMillis).then(this.onScrollCompleted);
$document.duScrollTopAnimated(positionFromTop, durationInMillis, this.invertedEasingFn).then(this.onScrollCompleted);
$document.duScrollLeft(positionFromLeft);
$document.duScrollLeft(positionFromLeft, durationInMillis).then(this.onScrollCompleted);
$document.duScrollLeft(positionFromLeft, durationInMillis, this.invertedEasingFn).then(this.onScrollCompleted);
$document.duScrollLeftAnimated(positionFromLeft).then(this.onScrollCompleted);
$document.duScrollLeftAnimated(positionFromLeft, durationInMillis).then(this.onScrollCompleted);
$document.duScrollLeftAnimated(positionFromLeft, durationInMillis, this.invertedEasingFn).then(this.onScrollCompleted);
var verticalPosition: number = $document.duScrollTop();
var horixontalPosition: number = $document.duScrollLeft();
}
private invertedEasingFn = (x: number): number => {
return 1 - x;
}
private onScrollCompleted = (): void => {
console.log('Done scrolling');
}
}
angular.module('testApp', ['duScroll'])
.controller('testController', TestController);
}
+44
View File
@@ -0,0 +1,44 @@
// Type definitions for angular-scroll
// Project: https://github.com/oblador/angular-scroll
// Definitions by: Sam Herrmann <https://github.com/samherrmann>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module duScroll {
/**
* Extends the angular.element object returned by the $document sercive with a few jQuery like functions.
* see https://github.com/oblador/angular-scroll#angularelement-scroll-api
*/
interface IDocumentService extends ng.IDocumentService {
duScrollTo(left: number, top: number): void;
duScrollTo(left: number, top: number, duration: number, easing?: Function): ng.IPromise<void>;
duScrollTo(element: ng.IAugmentedJQuery, offset?: number): void;
duScrollTo(element: ng.IAugmentedJQuery, offset: number, duration: number, easing?: Function): ng.IPromise<void>;
duScrollToElement(element: ng.IAugmentedJQuery, offset?: number): void;
duScrollToElement(element: ng.IAugmentedJQuery, offset: number, duration: number, easing?: Function): ng.IPromise<void>;
duScrollToElementAnimated(element: ng.IAugmentedJQuery, offset?: number): ng.IPromise<void>;
duScrollToElementAnimated(element: ng.IAugmentedJQuery, offset: number, duration: number, easing?: Function): ng.IPromise<void>;
duScrollTop(top: number): void;
duScrollTop(top: number, duration: number, easing?: Function): ng.IPromise<void>;
duScrollTopAnimated(top: number): ng.IPromise<void>;
duScrollTopAnimated(top: number, duration: number, easing?: Function): ng.IPromise<void>;
duScrollLeft(left: number): void;
duScrollLeft(left: number, duration: number, easing?: Function): ng.IPromise<void>;
duScrollLeftAnimated(left: number): ng.IPromise<void>;
duScrollLeftAnimated(left: number, duration: number, easing?: Function): ng.IPromise<void>;
duScrollTop(): number;
duScrollLeft(): number;
}
}
+43
View File
@@ -0,0 +1,43 @@
/// <reference path='../angularjs/angular.d.ts' />
/// <reference path='angular-storage.d.ts' />
// Samples taken from the a0-angular-storage Readme.md
var app = angular.module('angular-storage-tests', ['angular-storage']);
angular.module('angular-storage-tests')
.controller('StoreController', function(store: angular.a0.storage.IStoreService) {
var myObj = {
name: 'mgonto'
};
store.set('obj', myObj);
var myNewObject = store.get('obj');
console.log('Should be true: ', angular.equals(myNewObject, myObj));
store.remove('obj');
store.set('number', 2);
console.log('Should be true: ', typeof(store.get('number')) === 'number');
})
.factory('Auth0Store', function(store: angular.a0.storage.IStoreService) {
return store.getNamespacedStore('auth0');
})
.controller('NamespacedStoreController', function(Auth0Store: angular.a0.storage.INamespacedStoreService) {
var myObj = {
name: 'mgonto'
};
// This will be saved in localStorage as auth0.obj
Auth0Store.set('obj', myObj);
// This will look for auth0.obj
var myNewObject = Auth0Store.get('obj');
console.log('Should be true: ', angular.equals(myNewObject, myObj));
});;
+53
View File
@@ -0,0 +1,53 @@
// Type definitions for angular-storage v0.0.11
// Project: https://github.com/auth0/angular-storage
// Definitions by: Matthew DeKrey <https://github.com/mdekrey>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module angular.a0.storage {
interface IStoreService extends INamespacedStoreService {
/**
* Returns a namespaced store
*
* @param {String} namespace - The namespace
* @param {String} storage - The name of the storage service. Defaults to local storage.
* @param {String} delimiter - The delimiter to use to separate the namespace and the keys.
* @returns {INamespacedStoreService}
*/
getNamespacedStore(namespace: string, storage?: string, delimiter?: string): INamespacedStoreService;
}
interface INamespacedStoreService {
/**
* Sets a new value to the storage with the key name. It can be any object.
*
* @param {String} name - The key name for the location of the value
* @param value - The value to store
*/
set(name: string, value: any): void;
/**
* Returns the saved value with they key name.
*
* @param {String} name - The key name for the location of the value
* @returns The saved value; if you saved an object, you get an object
*/
get(name: string): any;
/**
* Deletes the saved value with the key name
*
* @param {String} name - The key name for the location of the value to remove
*/
remove(name: string): void;
}
interface IStoreProvider {
/**
* Sets the storage.
*
* @param {String} storage - The storage name
*/
setStore(storage: string): void;
}
}
+2 -2
View File
@@ -2,7 +2,7 @@
var app = angular.module('at', ['pascalprecht.translate']);
app.config(($translateProvider: ng.translate.ITranslateProvider) => {
app.config(($translateProvider: angular.translate.ITranslateProvider) => {
$translateProvider.translations('en', {
TITLE: 'Hello',
FOO: 'This is a paragraph.',
@@ -22,7 +22,7 @@ interface Scope extends ng.IScope {
changeLanguage(key: any): void;
}
app.controller('Ctrl', ($scope: Scope, $translate: ng.translate.ITranslateService) => {
app.controller('Ctrl', ($scope: Scope, $translate: angular.translate.ITranslateService) => {
$scope['changeLanguage'] = function (key: any) {
$translate.use(key);
};
+29 -15
View File
@@ -5,14 +5,13 @@
/// <reference path="../angularjs/angular.d.ts" />
declare module ng.translate {
interface ITranslatePartialLoaderService {
addPart(name: string): ITranslatePartialLoaderService;
deletePart(name: string, removeData?: boolean): ITranslatePartialLoaderService;
isPartAvailable(name: string): boolean;
}
declare module "angular-translate" {
var _: string;
export = _;
}
declare module angular.translate {
interface ITranslationTable {
[key: string]: string;
}
@@ -26,15 +25,30 @@ declare module ng.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): ng.IPromise<string>;
(translationId: string[], interpolateParams?: any, interpolationId?: string): ng.IPromise<{ [key: string]: string }>;
(translationId: string, interpolateParams?: any, interpolationId?: string): angular.IPromise<string>;
(translationId: string[], interpolateParams?: any, interpolationId?: string): angular.IPromise<{ [key: string]: string }>;
cloakClassName(): string;
cloakClassName(name: string): ITranslateProvider;
fallbackLanguage(langKey?: string): string;
@@ -44,17 +58,17 @@ declare module ng.translate {
isPostCompilingEnabled(): boolean;
preferredLanguage(langKey?: string): string;
proposedLanguage(): string;
refresh(langKey?: string): ng.IPromise<void>;
refresh(langKey?: string): angular.IPromise<void>;
storage(): IStorage;
storageKey(): string;
use(): string;
use(key: string): ng.IPromise<string>;
use(key: string): angular.IPromise<string>;
useFallbackLanguage(langKey?: string): void;
versionInfo(): string;
loaderCache(): any;
}
interface ITranslateProvider extends ng.IServiceProvider {
interface ITranslateProvider extends angular.IServiceProvider {
translations(): ITranslationTable;
translations(key: string, translationTable: ITranslationTable): ITranslateProvider;
cloakClassName(): string;
@@ -78,7 +92,7 @@ declare module ng.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;
@@ -131,6 +131,7 @@ testApp.controller('TestCtrl', (
var modalInstance = $modal.open({
backdrop: 'static',
controller: 'ModalTestCtrl',
controllerAs: 'vm',
keyboard: true,
resolve: {
items: ()=> {
@@ -140,6 +141,7 @@ testApp.controller('TestCtrl', (
scope: $scope,
template: "<div>i'm a template!</div>",
templateUrl: '/templates/modal.html',
backdropClass: 'modal-backdrop-test',
windowClass: 'modal-test'
});
@@ -226,4 +228,4 @@ interface IModalTestCtrlScope {
close(): void;
dismiss(): void;
}
}
+26 -8
View File
@@ -5,7 +5,7 @@
/// <reference path="../angularjs/angular.d.ts" />
declare module ng.ui.bootstrap {
declare module angular.ui.bootstrap {
interface IAccordionConfig {
/**
@@ -190,15 +190,15 @@ declare module ng.ui.bootstrap {
/**
* a promise that is resolved when a modal is closed and rejected when a modal is dismissed
*/
result: ng.IPromise<any>;
result: angular.IPromise<any>;
/**
* a promise that is resolved when a modal gets opened after downloading content's template and resolving all variables
*/
opened: ng.IPromise<any>;
opened: angular.IPromise<any>;
}
interface IModalScope extends ng.IScope {
interface IModalScope extends angular.IScope {
/**
* Those methods make it easy to close a modal window without a need to create a dedicated controller
*/
@@ -229,7 +229,7 @@ declare module ng.ui.bootstrap {
* a scope instance to be used for the modal's content (actually the $modal service is going to create a child scope of a provided scope).
* Defaults to `$rootScope`.
*/
scope?: IModalScope;
scope?: angular.IScope|IModalScope;
/**
* a controller for a modal instance - it can initialize scope used by modal.
@@ -237,6 +237,12 @@ declare module ng.ui.bootstrap {
*/
controller?: any;
/**
* an alternative to the controller-as syntax, matching the API of directive definitions.
* Requires the controller option to be provided as well
*/
controllerAs?: string;
/**
* members that will be resolved and passed to the controller as locals; it is equivalent of the `resolve` property for AngularJS routes
*/
@@ -258,6 +264,11 @@ declare module ng.ui.bootstrap {
*/
keyboard?: boolean;
/**
* additional CSS class(es) to be added to a modal backdrop template
*/
backdropClass?: string;
/**
* additional CSS class(es) to be added to a modal window template
*/
@@ -584,7 +595,14 @@ declare module ng.ui.bootstrap {
*
* @default false
*/
appendtoBody?: boolean;
appendToBody?: boolean;
/**
* Determines the default open triggers for tooltips and popovers
*
* @default 'mouseenter' for tooltip, 'click' for popover
*/
trigger?: string;
}
interface ITooltipProvider {
@@ -623,11 +641,11 @@ declare module ng.ui.bootstrap {
*
* @return A promise that is resolved when the transition finishes.
*/
(element: ng.IAugmentedJQuery, trigger: any, options?: ITransitionServiceOptions): ng.IPromise<ng.IAugmentedJQuery>;
(element: angular.IAugmentedJQuery, trigger: any, options?: ITransitionServiceOptions): angular.IPromise<angular.IAugmentedJQuery>;
}
interface ITransitionServiceOptions {
animation?: boolean;
}
}
}
@@ -13,6 +13,13 @@ myApp.config((
$urlMatcherFactory: ng.ui.IUrlMatcherFactory) => {
var matcher: ng.ui.IUrlMatcher = $urlMatcherFactory.compile("/foo/:bar?param1");
$urlMatcherFactory.type("myType2", {
encode: function (item: any) { return item; },
decode: function (item: any) { return item; },
is: function (item: any) { return true; }
});
var obj: Object = matcher.exec('/user/bob', { x:'1', q:'hello' });
var concat: ng.ui.IUrlMatcher = matcher.concat('/test');
var str: string = matcher.format({ id:'bob', q:'yes' });
@@ -57,7 +64,16 @@ myApp.config((
controller: function ($scope: MyAppScope) {
$scope.things = ["A", "Set", "Of", "Things"];
}
}).state('index', {
})
.state('list', {
parent: 'state3',
url: "/list",
templateUrl: "partials/state3.list.html",
controller: function ($scope: MyAppScope) {
$scope.things = ["A", "Set", "Of", "Things"];
}
})
.state('index', {
url: "",
views: {
"viewA": { template: "index.viewA" },
+198
View File
@@ -0,0 +1,198 @@
// Type definitions for Angular JS 1.1.5+ (ui.router module)
// Project: https://github.com/angular-ui/ui-router
// Definitions by: Michel Salib <https://github.com/michelsalib>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.ui {
interface IState {
name?: string;
/**
* String HTML content, or function that returns an HTML string
*/
template?: string | {(): string};
/**
* String URL path to template file OR Function, returns URL path string
*/
templateUrl?: string | {(): string};
/**
* Function, returns HTML content string
*/
templateProvider?: Function | Array<any>;
/**
* A controller paired to the state. Function OR name as String
*/
controller?: Function | string;
controllerAs?: string;
/**
* Function (injectable), returns the actual controller function or string.
*/
controllerProvider?: Function;
/**
* Specifies the parent state of this state
*/
parent?: string | IState
resolve?: {};
/**
* A url with optional parameters. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed.
*/
url?: string | IUrlMatcher;
/**
* A map which optionally configures parameters declared in the url, or defines additional non-url parameters. Only use this within a state if you are not using url. Otherwise you can specify your parameters within the url. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed.
*/
params?: any;
/**
* Use the views property to set up multiple views. If you don't need multiple views within a single state this property is not needed. Tip: remember that often nested views are more useful and powerful than multiple sibling views.
*/
views?: {};
abstract?: boolean;
/**
* Callback function for when a state is entered. Good way to trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to explictly annotate this function, because it won't be automatically annotated by your build tools.
*/
onEnter?: Function|(string|Function)[];
/**
* Callback functions for when a state is entered and exited. Good way to trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to explictly annotate this function, because it won't be automatically annotated by your build tools.
*/
onExit?: Function|(string|Function)[];
/**
* Arbitrary data object, useful for custom configuration.
*/
data?: any;
/**
* Boolean (default true). If false will not retrigger the same state just because a search/query parameter has changed. Useful for when you'd like to modify $location.search() without triggering a reload.
*/
reloadOnSearch?: boolean;
}
interface IStateProvider extends angular.IServiceProvider {
state(name:string, config:IState): IStateProvider;
state(config:IState): IStateProvider;
decorator(name?: string, decorator?: (state: IState, parent: Function) => any): any;
}
interface IUrlMatcher {
concat(pattern: string): IUrlMatcher;
exec(path: string, searchParams: {}): {};
parameters(): string[];
format(values: {}): string;
}
interface IUrlMatcherFactory {
compile(pattern: string): IUrlMatcher;
isMatcher(o: any): boolean;
type(name: string, definition: any, definitionFn?: any): any;
caseInsensitive(value: boolean): void;
defaultSquashPolicy(value: string): void;
strictMode(value: boolean): void;
}
interface IUrlRouterProvider extends angular.IServiceProvider {
when(whenPath: RegExp, handler: Function): IUrlRouterProvider;
when(whenPath: RegExp, handler: any[]): IUrlRouterProvider;
when(whenPath: RegExp, toPath: string): IUrlRouterProvider;
when(whenPath: IUrlMatcher, hanlder: Function): IUrlRouterProvider;
when(whenPath: IUrlMatcher, handler: any[]): IUrlRouterProvider;
when(whenPath: IUrlMatcher, toPath: string): IUrlRouterProvider;
when(whenPath: string, handler: Function): IUrlRouterProvider;
when(whenPath: string, handler: any[]): IUrlRouterProvider;
when(whenPath: string, toPath: string): IUrlRouterProvider;
otherwise(handler: Function): IUrlRouterProvider;
otherwise(handler: any[]): IUrlRouterProvider;
otherwise(path: string): IUrlRouterProvider;
rule(handler: Function): IUrlRouterProvider;
rule(handler: any[]): IUrlRouterProvider;
}
interface IStateOptions {
/**
* {boolean=true|string=} - If true will update the url in the location bar, if false will not. If string, must be "replace", which will update url and also replace last history record.
*/
location?: boolean | string;
/**
* {boolean=true}, If true will inherit url parameters from current url.
*/
inherit?: boolean;
/**
* {object=$state.$current}, When transitioning with relative path (e.g '^'), defines which state to be relative from.
*/
relative?: IState;
/**
* {boolean=true}, If true will broadcast $stateChangeStart and $stateChangeSuccess events.
*/
notify?: boolean;
/**
* {boolean=false}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params.
*/
reload?: boolean;
}
interface IHrefOptions {
lossy?: boolean;
inherit?: boolean;
relative?: IState;
absolute?: boolean;
}
interface IStateService {
/**
* Convenience method for transitioning to a new state. $state.go calls $state.transitionTo internally but automatically sets options to { location: true, inherit: true, relative: $state.$current, notify: true }. This allows you to easily use an absolute or relative to path and specify only the parameters you'd like to update (while letting unspecified parameters inherit from the currently active ancestor states).
*
* @param to Absolute state name or relative state path. Some examples:
*
* $state.go('contact.detail') - will go to the contact.detail state
* $state.go('^') - will go to a parent state
* $state.go('^.sibling') - will go to a sibling state
* $state.go('.child.grandchild') - will go to grandchild state
*
* @param params A map of the parameters that will be sent to the state, will populate $stateParams. Any parameters that are not specified will be inherited from currently defined parameters. This allows, for example, going to a sibling state that shares parameters specified in a parent state. Parameter inheritance only works between common ancestor states, I.e. transitioning to a sibling will get you the parameters for all parents, transitioning to a child will get you all current parameters, etc.
*
* @param options Options object.
*/
go(to: string, params?: {}, options?: IStateOptions): angular.IPromise<any>;
transitionTo(state: string, params?: {}, updateLocation?: boolean): void;
transitionTo(state: string, params?: {}, options?: IStateOptions): void;
includes(state: string, params?: {}): boolean;
is(state:string, params?: {}): boolean;
is(state: IState, params?: {}): boolean;
href(state: IState, params?: {}, options?: IHrefOptions): string;
href(state: string, params?: {}, options?: IHrefOptions): string;
get(state: string): IState;
get(): IState[];
current: IState;
params: IStateParamsService;
reload(): void;
}
interface IStateParamsService {
[key: string]: any;
}
interface IUrlRouterService {
/*
* Triggers an update; the same update that happens when the address bar
* url changes, aka $locationChangeSuccess.
*
* This method is useful when you need to use preventDefault() on the
* $locationChangeSuccess event, perform some custom logic (route protection,
* auth, config, redirection, etc) and then finally proceed with the transition
* by calling $urlRouter.sync().
*
*/
sync(): void;
}
interface IUiViewScrollProvider {
/*
* Reverts back to using the core $anchorScroll service for scrolling
* based on the url anchor.
*/
useAnchorScroll(): void;
}
}
@@ -0,0 +1,143 @@
/// <reference path="../angularjs/angular.d.ts" />
/// <reference path="angular-ui-sortable.d.ts" />
var myApp = angular.module('testModule');
interface MySortableControllerScope extends ng.IScope {
items: SortableModelInfo[];
sortableOptions: ng.ui.UISortableOptions<SortableModelInfo>;
sortingLog: SortLogInfo[];
}
interface SortableModelInfo {
text: string;
value: number;
}
interface SortLogInfo {
ID: number;
Text: string;
}
myApp.controller('sortableController', function ($scope: MySortableControllerScope) {
$scope.sortableOptions = {
activate: function(e, ui) {
var jQueryEventObject: JQueryEventObject = e;
var uiSortableUIParams: ng.ui.UISortableUIParams<SortableModelInfo> = ui;
},
beforeStop: function(e, ui) {
var jQueryEventObject: JQueryEventObject = e;
var uiSortableUIParams: ng.ui.UISortableUIParams<SortableModelInfo> = ui;
},
change: function(e, ui) {
var jQueryEventObject: JQueryEventObject = e;
var uiSortableUIParams: ng.ui.UISortableUIParams<SortableModelInfo> = ui;
},
deactivate: function(e, ui) {
var jQueryEventObject: JQueryEventObject = e;
var uiSortableUIParams: ng.ui.UISortableUIParams<SortableModelInfo> = ui;
},
out: function(e, ui) {
var jQueryEventObject: JQueryEventObject = e;
var uiSortableUIParams: ng.ui.UISortableUIParams<SortableModelInfo> = ui;
},
over: function(e, ui) {
var jQueryEventObject: JQueryEventObject = e;
var uiSortableUIParams: ng.ui.UISortableUIParams<SortableModelInfo> = ui;
},
receive: function(e, ui) {
var jQueryEventObject: JQueryEventObject = e;
var uiSortableUIParams: ng.ui.UISortableUIParams<SortableModelInfo> = ui;
},
remove: function(e, ui) {
var jQueryEventObject: JQueryEventObject = e;
var uiSortableUIParams: ng.ui.UISortableUIParams<SortableModelInfo> = ui;
},
sort: function(e, ui) {
var jQueryEventObject: JQueryEventObject = e;
var uiSortableUIParams: ng.ui.UISortableUIParams<SortableModelInfo> = ui;
},
start: function(e, ui) {
var jQueryEventObject: JQueryEventObject = e;
var uiSortableUIParams: ng.ui.UISortableUIParams<SortableModelInfo> = ui;
},
stop: function(e, ui) {
var jQueryEventObject: JQueryEventObject = e;
var uiSortableUIParams: ng.ui.UISortableUIParams<SortableModelInfo> = ui;
var uiitem: ng.ui.UISortableUIItem<SortableModelInfo> = ui.item;
var uiitemscope: ng.IScope = uiitem.scope();
var uiitemsortable: ng.ui.UISortableProperties<SortableModelInfo> = uiitem.sortable;
var dropindex: number = uiitemsortable.dropindex;
var droptarget: number = uiitemsortable.droptarget;
var droptargetModel: SortableModelInfo[] = uiitemsortable.droptargetModel;
var index: number = uiitemsortable.index;
var model: SortableModelInfo = uiitemsortable.model;
var moved: SortableModelInfo = uiitemsortable.moved;
var received: Boolean = uiitemsortable.received;
var source: ng.IAugmentedJQuery = uiitemsortable.source;
var sourceModel: SortableModelInfo[] = uiitemsortable.sourceModel;
var logEntry = {
ID: $scope.sortingLog.length + 1,
Text: 'Moved element: ' + ui.item.sortable.model.text
};
$scope.sortingLog.push(logEntry);
},
update: function(e, ui) {
var jQueryEventObject: JQueryEventObject = e;
var uiSortableUIParams: ng.ui.UISortableUIParams<SortableModelInfo> = ui;
var voidcanceled: void = ui.item.sortable.cancel();
var isCanceled: Boolean = ui.item.sortable.isCanceled();
var isCustomHelperUsed: Boolean =ui.item.sortable.isCustomHelperUsed();
}
};
$scope.sortableOptions.appendTo = document.body;
$scope.sortableOptions.appendTo = angular.element(document.body);
$scope.sortableOptions.appendTo = 'body';
$scope.sortableOptions.axis = 'x';
$scope.sortableOptions.axis = 'y';
$scope.sortableOptions.axis = false;
$scope.sortableOptions.cancel = '.disabled';
$scope.sortableOptions.connectWith = '.connectedSortable';
$scope.sortableOptions.connectWith = false;
$scope.sortableOptions.containment = 'parent';
$scope.sortableOptions.containment = 'body';
$scope.sortableOptions.containment = document.body;
$scope.sortableOptions.containment = false;
$scope.sortableOptions.cursor = 'move';
$scope.sortableOptions.cursorAt = false;
$scope.sortableOptions.cursorAt = { left: 5 };
$scope.sortableOptions.delay = 300;
$scope.sortableOptions.disabled = true;
$scope.sortableOptions.distance = 5;
$scope.sortableOptions.dropOnEmpty = false;
$scope.sortableOptions.forceHelperSize = true;
$scope.sortableOptions.forcePlaceholderSize = true;
$scope.sortableOptions.grid = false;
$scope.sortableOptions.grid = [20, 10];
$scope.sortableOptions.handle = '.handle';
$scope.sortableOptions.helper = 'clone';
$scope.sortableOptions.helper = function(e: JQueryEventObject, item: ng.IAugmentedJQuery) {
return item.clone();
};
$scope.sortableOptions.items = '> li:not(.disabled)';
$scope.sortableOptions.opacity = false;
$scope.sortableOptions.opacity = 0.5;
$scope.sortableOptions.placeholder = false;
$scope.sortableOptions.placeholder = 'sortable-placeholder';
$scope.sortableOptions.revert = true;
$scope.sortableOptions.revert = 300;
$scope.sortableOptions.scroll = false;
$scope.sortableOptions.scrollSensitivity = 10;
$scope.sortableOptions.scrollSpeed = 40;
$scope.sortableOptions.tolerance = 'pointer';
$scope.sortableOptions.zIndex = 9999;
$scope.sortableOptions['ui-floating'] = undefined;
$scope.sortableOptions['ui-floating'] = null;
$scope.sortableOptions['ui-floating'] = false;
$scope.sortableOptions['ui-floating'] = true;
$scope.sortableOptions['ui-floating'] = "auto";
});
+210
View File
@@ -0,0 +1,210 @@
// Type definitions for angular.ui.sortable module v0.13+
// Project: https://github.com/angular-ui/ui-sortable
// Definitions by: Thodoris Greasidis <https://github.com/thgreasi>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.ui {
interface UISortableOptions<T> extends SortableOptions<T> {
'ui-floating'?: string|boolean;
}
interface UISortableProperties<T> {
/**
* Holds the index of the drop target that the dragged item was dropped.
*/
dropindex: number;
/**
* Holds the ui-sortable element that the dragged item was dropped on.
*/
droptarget: number;
/**
* Holds the array that is specified by the `ng-model` attribute of the [`droptarget`](#droptarget) ui-sortable element.
*/
droptargetModel: Array<T>;
/**
* Holds the original index of the item dragged.
*/
index: number;
/**
* Holds the JavaScript object that is used as the model of the dragged item, as specified by the ng-repeat of the [`source`](#source) ui-sortable element and the item's [`index`](#index).
*/
model: T;
/**
* Holds the model of the dragged item only when a sorting happens between two connected ui-sortable elements.
* In other words: `'moved' in ui.item.sortable` will return false only when a sorting is withing the same ui-sortable element ([`source`](#source) equals to the [`droptarget`](#droptarget)).
*/
moved?: T;
/**
* When sorting between two connected sortables, it will be set to true inside the `update` callback of the [`droptarget`](#droptarget).
*/
received: Boolean;
/**
* Holds the ui-sortable element that the dragged item originated from.
*/
source: ng.IAugmentedJQuery
/**
* Holds the array that is specified by the `ng-model` of the [`source`](#source) ui-sortable element.
*/
sourceModel: Array<T>;
/**
* Can be called inside the `update` callback, in order to prevent/revert a sorting.
* Should be used instead of the [jquery-ui-sortable cancel()](http://api.jqueryui.com/sortable/#method-cancel) method.
*/
cancel(): void;
/**
* Returns whether the current sorting is marked as canceled, by an earlier call to [`ui.item.sortable.cancel()`](#cancel).
*/
isCanceled(): Boolean;
/**
* Returns whether the [`helper`](http://api.jqueryui.com/sortable/#option-helper) element used for the current sorting, is one of the original ui-sortable list elements.
*/
isCustomHelperUsed(): Boolean;
}
interface UISortableUIItem<T> extends ng.IAugmentedJQuery {
sortable: UISortableProperties<T>;
}
interface UISortableUIParams<T> extends SortableUIParams {
item: UISortableUIItem<T>;
}
// Base Sortable //////////////////////////////////////////////////
interface SortableCursorAtOptions {
top?: number;
left?: number;
right?: number;
bottom?: number;
}
interface SortableHelperFunctionOption {
(event: JQueryEventObject, ui: ng.IAugmentedJQuery): JQuery;
}
interface SortableOptions<T> extends SortableEvents<T> {
/**
* jQuery, Element, Selector or string
* Default: "parent"
*/
appendTo?: any;
/**
* "X", "Y" or false
* Default: false
*/
axis?: string|boolean;
/**
* Selector
* Default: "input,textarea,button,select,option"
*/
cancel?: string;
/**
* Selector or false
* Default: false
*/
connectWith?: string|boolean;
/**
* Element, Selector, string or false
* Default: false
*/
containment?: any;
cursor?: string;
/**
* Moves the sorting element or helper so the cursor always appears to drag from the same position. Coordinates can be given as a hash using a combination of one or two keys SortableCursorAtOptions: { top, left, right, bottom }
* Default: false
*/
cursorAt?: SortableCursorAtOptions|boolean;
delay?: number;
disabled?: boolean;
distance?: number;
dropOnEmpty?: boolean;
forceHelperSize?: boolean;
forcePlaceholderSize?: boolean;
/**
* Array of numbers or false
* Default: false
*/
grid?: number[]|boolean;
/**
* Selector or Element
*/
handle?: any;
/**
* "original", "clone" or Function()
* Default: "original"
*/
helper?: string|SortableHelperFunctionOption;
/**
* Selector
*/
items?: string;
/**
* Number or false
* Default: false
*/
opacity?: number|boolean;
/**
* string or false
* Default: false
*/
placeholder?: string|boolean;
/**
* boolean or number
* Default: false
*/
revert?: number|boolean;
scroll?: boolean;
scrollSensitivity?: number;
scrollSpeed?: number;
/**
* "intersect" or "pointer"
* Default: "intersect"
*/
tolerance?: string;
zIndex?: number;
}
interface SortableUIParams {
helper: ng.IAugmentedJQuery;
item: ng.IAugmentedJQuery;
offset: any;
position: any;
originalPosition: any;
sender: ng.IAugmentedJQuery;
placeholder: ng.IAugmentedJQuery;
}
interface SortableEvent<T> {
(event: JQueryEventObject, ui: UISortableUIParams<T>): void;
}
interface SortableEvents<T> {
activate?: SortableEvent<T>;
beforeStop?: SortableEvent<T>;
change?: SortableEvent<T>;
deactivate?: SortableEvent<T>;
out?: SortableEvent<T>;
over?: SortableEvent<T>;
receive?: SortableEvent<T>;
remove?: SortableEvent<T>;
sort?: SortableEvent<T>;
start?: SortableEvent<T>;
stop?: SortableEvent<T>;
update?: SortableEvent<T>;
}
}
-119
View File
@@ -1,119 +0,0 @@
// Type definitions for Angular JS 1.1.5+ (ui.router module)
// Project: https://github.com/angular-ui/ui-router
// Definitions by: Michel Salib <https://github.com/michelsalib>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module ng.ui {
interface IState {
name?: string;
template?: any;
templateUrl?: any;
templateProvider?: any;
controller?: any;
controllerAs?: string;
controllerProvider?: any;
resolve?: {};
url?: string;
params?: any;
views?: {};
abstract?: boolean;
onEnter?: any;
onExit?: any;
data?: any;
reloadOnSearch?: boolean;
}
interface IStateProvider extends IServiceProvider {
state(name:string, config:IState): IStateProvider;
state(config:IState): IStateProvider;
decorator(name?: string, decorator?: (state: IState, parent: Function) => any): any;
}
interface IUrlMatcher {
concat(pattern: string): IUrlMatcher;
exec(path: string, searchParams: {}): {};
parameters(): string[];
format(values: {}): string;
}
interface IUrlMatcherFactory {
compile(pattern: string): IUrlMatcher;
isMatcher(o: any): boolean;
}
interface IUrlRouterProvider extends IServiceProvider {
when(whenPath: RegExp, handler: Function): IUrlRouterProvider;
when(whenPath: RegExp, handler: any[]): IUrlRouterProvider;
when(whenPath: RegExp, toPath: string): IUrlRouterProvider;
when(whenPath: IUrlMatcher, hanlder: Function): IUrlRouterProvider;
when(whenPath: IUrlMatcher, handler: any[]): IUrlRouterProvider;
when(whenPath: IUrlMatcher, toPath: string): IUrlRouterProvider;
when(whenPath: string, handler: Function): IUrlRouterProvider;
when(whenPath: string, handler: any[]): IUrlRouterProvider;
when(whenPath: string, toPath: string): IUrlRouterProvider;
otherwise(handler: Function): IUrlRouterProvider;
otherwise(handler: any[]): IUrlRouterProvider;
otherwise(path: string): IUrlRouterProvider;
rule(handler: Function): IUrlRouterProvider;
rule(handler: any[]): IUrlRouterProvider;
}
interface IStateOptions {
location?: any;
inherit?: boolean;
relative?: IState;
notify?: boolean;
}
interface IHrefOptions {
lossy?: boolean;
inherit?: boolean;
relative?: IState;
absolute?: boolean;
}
interface IStateService {
go(to: string, params?: {}, options?: IStateOptions): IPromise<any>;
transitionTo(state: string, params?: {}, updateLocation?: boolean): void;
transitionTo(state: string, params?: {}, options?: IStateOptions): void;
includes(state: string, params?: {}): boolean;
is(state:string, params?: {}): boolean;
is(state: IState, params?: {}): boolean;
href(state: IState, params?: {}, options?: IHrefOptions): string;
href(state: string, params?: {}, options?: IHrefOptions): string;
get(state: string): IState;
get(): IState[];
current: IState;
params: IStateParamsService;
reload(): void;
}
interface IStateParamsService {
[key: string]: any;
}
interface IUrlRouterService {
/*
* Triggers an update; the same update that happens when the address bar
* url changes, aka $locationChangeSuccess.
*
* This method is useful when you need to use preventDefault() on the
* $locationChangeSuccess event, perform some custom logic (route protection,
* auth, config, redirection, etc) and then finally proceed with the transition
* by calling $urlRouter.sync().
*
*/
sync(): void;
}
interface IUiViewScrollProvider {
/*
* Reverts back to using the core $anchorScroll service for scrolling
* based on the url anchor.
*/
useAnchorScroll(): void;
}
}
+218
View File
@@ -0,0 +1,218 @@
/// <reference path="../jasmine/jasmine.d.ts" />
/// <reference path="../angularjs/angular.d.ts" />
/// <reference path="angular-wizard.d.ts" />
// test file taken from https://github.com/mgonto/angular-wizard
interface WizardScope extends ng.IScope {
referenceCurrentStep:string;
stepValidation:()=>void;
finishedWizard:()=>void;
enterValidation:()=>void;
}
describe('AngularWizard', function () {
var $compile:ng.ICompileService,
$rootScope:ng.IRootScopeService, WizardHandler:angular.mgoAngularWizard.WizardHandler, scope:WizardScope;
/**
* Create the view with wizard to test
* @param {Scope} scope A scope to bind to
* @return {[DOM element]} A DOM element compiled
*/
function createView(scope:WizardScope) {
scope.referenceCurrentStep = null;
var element = angular.element('<wizard on-finish="finishedWizard()" current-step="referenceCurrentStep" ng-init="msg = 14" >'
+ ' <wz-step title="Starting" canenter="enterValidation">'
+ ' <h1>This is the first step</h1>'
+ ' <p>Here you can use whatever you want. You can use other directives, binding, etc.</p>'
+ ' <input type="submit" wz-next value="Continue" />'
+ ' </wz-step>'
+ ' <wz-step title="Continuing" canexit="stepValidation">'
+ ' <h1>Continuing</h1>'
+ ' <p>You have continued here!</p>'
+ ' <input type="submit" wz-next value="Go on" />'
+ ' </wz-step>'
+ ' <wz-step title="More steps" canenter="enterValidation">'
+ ' <p>Even more steps!!</p>'
+ ' <input type="submit" wz-next value="Finish now" />'
+ ' </wz-step>'
+ '</wizard>');
var elementCompiled = $compile(element)(scope);
$rootScope.$digest();
return elementCompiled;
}
it("should correctly create the wizard", function () {
var view = createView(scope);
expect(WizardHandler).toBeTruthy();
expect(view.find('section').length).toEqual(3);
// expect the correct step to be desirable one
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("should go to the next step", function () {
var view = createView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should return to a previous step", function () {
var view = createView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
WizardHandler.wizard().previous();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("should go to a step specified by name", function () {
var view = createView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().goTo('More steps');
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should go to a step specified by index", function () {
var view = createView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().goTo(2);
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should go to next step becasue callback is truthy", function () {
var view = createView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next(function () {
return true
});
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should NOT go to next step because callback is falsey", function () {
var view = createView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next(function () {
return false
});
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("should go to next step because CANEXIT is UNDEFINED", function () {
var view = createView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should go to next step because CANEXIT is TRUE", function () {
var view = createView(scope);
scope.stepValidation = function () {
return true;
};
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should NOT go to next step because CANEXIT is FALSE", function () {
var view = createView(scope);
scope.stepValidation = function () {
return false;
};
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should go to next step because CANENTER is TRUE", function () {
var view = createView(scope);
scope.enterValidation = function () {
return true;
};
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should NOT go to next step because CANENTER is FALSE", function () {
var view = createView(scope);
scope.enterValidation = function () {
return false;
};
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should NOT return to a previous step. Although CANEXIT is false and we are heading to a previous state, the can enter validation is false", function () {
var view = createView(scope);
scope.stepValidation = function () {
return false;
};
scope.enterValidation = function () {
return false;
};
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
WizardHandler.wizard().previous();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should return to a previous step even though CANEXIT is false", function () {
var view = createView(scope);
scope.stepValidation = function () {
return false;
};
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
WizardHandler.wizard().previous();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("should finish", function () {
var flag = false;
scope.finishedWizard = function () {
flag = true;
};
var view = createView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().finish();
expect(flag).toBeTruthy();
$rootScope.$digest();
});
});
+21
View File
@@ -0,0 +1,21 @@
// Type definitions for Angular Wizard 0.4.2
// Project: https://github.com/mgonto/angular-wizard
// Definitions by: Marko Jurisic <https://github.com/mjurisic>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module angular.mgoAngularWizard {
interface WizardHandler {
wizard(name?:string): Wizard;
addWizard(name:string, wizard:Wizard):void;
removeWizard(name:string):void;
}
interface Wizard {
next(nextHandler?:Function):void;
previous():void;
goTo(step:number):void;
goTo(step:string):void;
finish():void;
currentStepNumber():number;
}
}

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