Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Arthur Langereis
2018-10-23 12:56:55 +02:00
34213 changed files with 3891521 additions and 1588876 deletions
+2 -2
View File
@@ -1,9 +1,9 @@
root = true
[*]
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
[{*.json,*.yml}]
[{*.json,*.yml,*.ts}]
indent_style = space
indent_size = 2
+5 -20
View File
@@ -1,22 +1,7 @@
# Auto detect text files and perform LF normalization
* text=none
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
# Checkout NPM package files with forced LF lineendings
# to prevent git conflicts when running npm commands
package.json text eol=lf
package-lock.json text eol=lf
+4958
View File
File diff suppressed because it is too large Load Diff
+9
View File
@@ -0,0 +1,9 @@
If you know how to fix the issue, make a pull request instead.
- [ ] I tried using the `@types/xxxx` package and had problems.
- [ ] I tried using the latest stable version of tsc. https://www.npmjs.com/package/typescript
- [ ] I have a question that is inappropriate for [StackOverflow](https://stackoverflow.com/). (Please ask any appropriate questions there).
- [ ] [Mention](https://github.com/blog/821-mention-somebody-they-re-notified) the authors (see `Definitions by:` in `index.d.ts`) so they can respond.
- Authors: @....
If you do not mention the authors the issue will be ignored.
+26
View File
@@ -0,0 +1,26 @@
Please fill in this template.
- [ ] Use a meaningful title for the pull request. Include the name of the package modified.
- [ ] Test the change in your own code. (Compile and run.)
- [ ] Add or edit tests to reflect the change. (Run with `npm test`.)
- [ ] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#make-a-pull-request).
- [ ] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#common-mistakes).
- [ ] Run `npm run lint package-name` (or `tsc` if no `tslint.json` is present).
Select one of these and delete the others:
If adding a new definition:
- [ ] The package does not already provide its own types, or cannot have its `.d.ts` files generated via `--declaration`
- [ ] If this is for an NPM package, match the name. If not, do not conflict with the name of an NPM package.
- [ ] Create it with `dts-gen --dt`, not by basing it on an existing project.
- [ ] `tslint.json` should be present, and `tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, `strictNullChecks`, and `strictFunctionTypes` set to `true`.
If changing an existing definition:
- [ ] Provide a URL to documentation or source code which provides context for the suggested changes: <<url here>>
- [ ] Increase the version number in the header if appropriate.
- [ ] If you are making substantial changes, consider adding a `tslint.json` containing `{ "extends": "dtslint/dt.json" }`.
If removing a declaration:
- [ ] If a package was never on DefinitelyTyped, you don't need to do anything. (If you wrote a package and provided types, you don't need to register it with us.)
- [ ] Delete the package's directory.
- [ ] Add it to `notNeededPackages.json`.
+54 -37
View File
@@ -1,37 +1,54 @@
*.dll
*.exe
*.cmd
*.pdb
*.suo
*.js
*.user
*.cache
*.cs
*.sln
*.csproj
*.txt
*.map
*.swp
.DS_Store
npm-debug.log
_Resharper.DefinitelyTyped
bin
obj
Properties
# VIM backup files
*~
# test folder
_infrastructure/tests/build
.idea
*.iml
*.js.map
!*.js/
node_modules
.sublimets
.settings/launch.json
*.dll
*.exe
*.cmd
*.pdb
*.suo
*.js
*.user
*.cache
*.cs
*.sln
*.csproj
*.map
*.swp
.DS_Store
_Resharper.DefinitelyTyped
bin
obj
Properties
# VIM backup files
*~
# test folder
_infrastructure/tests/build
# IntelliJ based IDEs
.idea
*.iml
*.js.map
!*.js/
!scripts/new-package.js
!scripts/not-needed.js
!scripts/lint.js
# npm
node_modules
package-lock.json
npm-debug.log
# Sublime
.sublimets
# Visual Studio Code
.settings/launch.json
.vs
.vscode
# yarn
yarn.lock
# pnpm
shrinkwrap.yaml
+1 -1
View File
@@ -1,6 +1,6 @@
language: node_js
node_js:
- 4
- 8
sudo: false
-1
View File
@@ -1 +0,0 @@
Please see the [contribution guide](http://definitelytyped.org/guides/contributing.html) at [definitelytyped.org](http://definitelytyped.org/guides/contributing.html) for information on how to contribute to DefinitelyTyped.
-1599
View File
File diff suppressed because it is too large Load Diff
-180
View File
@@ -1,180 +0,0 @@
/// <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
@@ -1,937 +0,0 @@
// 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;
}
-12
View File
@@ -1,12 +0,0 @@
/// <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';
var disableAutoBOM = true;
saveAs(data, filename, disableAutoBOM);
}
-33
View File
@@ -1,33 +0,0 @@
// 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,
/**
* @summary Disable Unicode text encoding hints or not.
* @type {boolean}
*/
disableAutoBOM?: boolean
): void
}
declare var saveAs: FileSaver;
-368
View File
@@ -1,368 +0,0 @@
/// <reference path="Finch.d.ts" />
function test_Finch() {
Finch.route("Hello/Route", function() {
return console.log("Well hello there! How you doin'?!");
});
Finch.route("Hello/Route/:someId", function(bindings) {
return console.log("Hey! Here's Some Id: " + bindings.someId);
});
Finch.route("Hello/Route/:someId", function(bindings, childCallback) {
console.log("Hey! Here's Some Id: " + bindings.someId);
return childCallback();
});
Finch.route("some/route", {
setup: function(bindings) {
return console.log("Some Route has been setup! :)");
},
load: function(bindings) {
return console.log("Some Route has been loaed! :D");
},
unload: function(bindings) {
return console.log("Some Route has been loaed! :(");
},
teardown: function(bindings) {
return console.log("Some Route has been torndown! :'(");
}
});
Finch.route("some/route", {
setup: function(bindings, childCallback) {
console.log("Some Route has been setup! :)");
return childCallback();
},
load: function(bindings, childCallback) {
console.log("Some Route has been loaed! :D");
return childCallback();
},
unload: function(bindings, childCallback) {
console.log("Some Route has been loaed! :(");
return childCallback();
},
teardown: function(bindings, childCallback) {
console.log("Some Route has been torndown! :'(");
return childCallback();
}
});
Finch.call("Some/Route");
Finch.route("Some/Route", function() {
return Finch.observe("hello", "foo", function(hello: any, foo: string) {
return console.log("" + hello + " and " + foo);
});
});
Finch.route("Some/Route", function() {
return Finch.observe(["hello", "foo"], function(hello: any, foo: any) {
return console.log("" + hello + " and " + foo);
});
});
Finch.route("Some/Route", function(bindings) {
return Finch.observe(function(params) {
});
});
Finch.navigate("Some/Route");
Finch.navigate("Some/Route", {
hello: 'world',
foo: 'bar'
});
Finch.navigate("Some/Route", {
foo: 'bar'
}, true);
Finch.navigate("Some/Route", true);
Finch.navigate({
hello: 'world2',
wow: 'wee'
});
Finch.navigate({
foo: 'bar',
wow: 'wee!!!'
});
Finch.navigate({
hello: 'world2'
}, true);
Finch.listen();
Finch.ignore();
Finch.abort();
//test from Finch
Finch.call("/foo/bar");
Finch.call("/foo/bar/123");
Finch.call("/foo/bar/123");
Finch.call("/foo/bar/123?x=Hello&y=World");
Finch.call("/foo/baz/456");
Finch.call("/quux/789?band=Sunn O)))&genre=Post-Progressive Fridgecore");
Finch.call("/foo/bar/baz");
Finch.call("/foo/bar/quux");
Finch.call("/foo");
Finch.call("/foo/bar");
Finch.call("/foo");
Finch.call("/foo");
Finch.call("/");
Finch.call("/");
Finch.call("/foo");
Finch.call("/foo/bar");
Finch.call("/foo/bar?baz=quux");
Finch.call("/foo/bar?baz=xyzzy");
var cb: any;
Finch.route("foo", {
setup: cb.setup_foo = this.stub(),
load: cb.load_foo = this.stub(),
unload: cb.unload_foo = this.stub(),
teardown: cb.teardown_foo = this.stub()
});
Finch.route("[foo]/bar", {
setup: cb.setup_foo_bar = this.stub(),
load: cb.load_foo_bar = this.stub(),
unload: cb.unload_foo_bar = this.stub(),
teardown: cb.teardown_foo_bar = this.stub()
});
Finch.route("[foo/bar]/:id", {
setup: cb.setup_foo_bar_id = this.stub(),
load: cb.load_foo_bar_id = this.stub(),
unload: cb.unload_foo_bar_id = this.stub(),
teardown: cb.teardown_foo_bar_id = this.stub()
});
Finch.route("[foo]/baz", {
setup: cb.setup_foo_baz = this.stub(),
load: cb.load_foo_baz = this.stub(),
unload: cb.unload_foo_baz = this.stub(),
teardown: cb.teardown_foo_baz = this.stub()
});
Finch.route("[foo/baz]/:id", {
setup: cb.setup_foo_baz_id = this.stub(),
load: cb.load_foo_baz_id = this.stub(),
unload: cb.unload_foo_baz_id = this.stub(),
teardown: cb.teardown_foo_baz_id = this.stub()
});
Finch.call("/foo");
Finch.call("/foo/bar");
Finch.call("/foo");
Finch.call("/foo/bar/123?x=abc");
Finch.call("/foo/bar/456?x=aaa&y=zzz");
Finch.call("/foo/bar/456?x=bbb&y=zzz");
Finch.call("/foo/bar/456?y=zzz&x=bbb");
Finch.call("/foo/baz/789");
Finch.call("/foo/baz/abc?term=Hello");
Finch.call("/foo/baz/abc?term=World");
Finch.route("bar", this.stub());
Finch.call("/foo");
Finch.call("/bar");
Finch.route("/", function() {
});
Finch.route("[/]home", function() {
});
Finch.route("[/home]/news", {
setup: function() {
},
load: function() {
},
unload: function() {
return true;
},
teardown: function() {
return false;
}
});
Finch.route("/foo", {
setup: function() {
return true;
},
load: function() {
return true;
},
unload: function() {
},
teardown: function() {
}
});
Finch.route("[/]bar", {
setup: function() {
},
load: function() {
},
unload: function() {
},
teardown: function() {
}
});
Finch.call("/bar");
Finch.call("/home/news");
Finch.call("/foo");
Finch.call("/home/news");
Finch.call("/bar");
Finch.route("baz", this.stub());
Finch.call("/foo");
Finch.call("/foo/bar");
Finch.call("/baz");
Finch.route("/home", {
setup: function(bindings, next) {
return next();
},
load: function(bindings, next) {
return next();
},
unload: function(bindings, next) {
return next();
},
teardown: function(bindings, next) {
return next();
}
});
Finch.route("[/home]/news", {
setup: function(bindings, next) {
return next();
},
load: function(bindings, next) {
return next();
},
unload: function(bindings, next) {
return next();
},
teardown: function(bindings, next) {
return next();
}
});
Finch.call("/home");
Finch.call("/home/news");
Finch.call("/foo");
Finch.route("/", function(bindings) {
return Finch.observe(["x"], function(x) {
});
});
Finch.call("/?x=123");
Finch.call("/?x=123.456");
Finch.call("/?x=true");
Finch.call("/?x=false");
Finch.call("/?x=stuff");
Finch.options({
CoerceParameterTypes: true
});
Finch.call("/?x=123");
Finch.call("/?x=123.456");
Finch.call("/?x=true");
Finch.call("/?x=false");
Finch.call("/?x=stuff");
Finch.route("/:x", function(_arg) {
});
Finch.call("/123");
Finch.call("/123.456");
Finch.call("/true");
Finch.call("/false");
Finch.call("/stuff");
Finch.options({
CoerceParameterTypes: true
});
Finch.call("/123");
Finch.call("/123.456");
Finch.call("/true");
Finch.call("/false");
Finch.call("/stuff");
Finch.navigate("/home");
Finch.navigate("/home/news");
Finch.navigate("/home");
Finch.navigate("/home", {
foo: "bar"
});
Finch.navigate("/home", {
hello: "world"
});
Finch.navigate({
foos: "bars"
});
Finch.navigate({
foos: "baz"
});
Finch.navigate({
hello: "world"
}, true);
Finch.navigate({
foos: null
}, true);
Finch.navigate("/home/news", true);
Finch.navigate("/hello world", {});
Finch.navigate("/hello world", {
foo: "bar bar"
});
Finch.navigate({
foo: "baz baz"
});
Finch.navigate({
hello: 'world world'
}, true);
Finch.navigate("/home?foo=bar", {
hello: "world"
});
Finch.navigate("/home?foo=bar", {
hello: "world",
foo: "baz"
});
Finch.navigate("/home?foo=bar", {
hello: "world",
free: "bird"
});
Finch.navigate("#/home", true);
Finch.navigate("#/home");
Finch.navigate("#/home/news", {
free: "birds",
hello: "worlds"
});
Finch.navigate("#/home/news", {
foo: "bar"
}, true);
Finch.navigate("/home/news");
Finch.navigate("../");
Finch.navigate("./");
Finch.navigate("./news");
Finch.navigate("/home/news/article");
Finch.navigate("../../account");
Finch.listen();
Finch.ignore();
Finch.route("/home", function(bindings, continuation) {
});
Finch.route("/foo", function(bindings, continuation) {
});
Finch.call("home");
Finch.call("foo");
Finch.abort();
Finch.call("foo");
Finch.route("/", {
'setup': cb.slash_setup = this.stub(),
'load': cb.slash_load = this.stub(),
'unload': cb.slash_unload = this.stub(),
'teardown': cb.slash_teardown = this.stub()
});
Finch.route("[/]users/profile", {
'setup': cb.profile_setup = this.stub(),
'load': cb.profile_load = this.stub(),
'unload': cb.profile_unload = this.stub(),
'teardown': cb.profile_teardown = this.stub()
});
Finch.route("[/]:page", {
'setup': cb.page_setup = this.stub(),
'load': cb.page_load = this.stub(),
'unload': cb.page_unload = this.stub(),
'teardown': cb.page_teardown = this.stub()
});
Finch.call("/users");
}
-47
View File
@@ -1,47 +0,0 @@
// Type definitions for Finch 0.5.13
// Project: https://github.com/stoodder/finchjs
// Definitions by: David Sichau <https://github.com/DavidSichau>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface FinchCallback {
(bindings?: any, childCallback? : () => void): any;
}
interface ExpandedCallback {
setup?: FinchCallback;
load?: FinchCallback;
unload?: FinchCallback;
teardown?: FinchCallback;
}
interface ObserveCallback {
(...args: any[]): string;
}
interface FinchOptions {
CoerceParameterTypes?: boolean;
}
interface FinchStatic {
route(route: string, callback: FinchCallback): void;
route(route: string, callbacks: ExpandedCallback): void;
call( uri: string ): void;
observe(argN: string[], callback: (params: ObserveCallback ) => void): void;
observe(callback: (params: ObserveCallback) => void): void;
observe(...args: any[]): void;
navigate(uri:string, queryParams?:any, doUpdate?:boolean ): void;
navigate(uri:string, doUpdate:boolean ): void;
navigate(queryParams:any, doUpdate?:boolean ): void;
listen(): boolean;
ignore(): boolean;
abort(): void;
options(options: FinchOptions): void;
}
declare var Finch: FinchStatic;
declare module "finch" {
export = Finch;
}
-28
View File
@@ -1,28 +0,0 @@
// Type definitions for headroom.js v0.7.0
// Project: http://wicky.nillia.ms/headroom.js/
// Definitions by: Jakub Olek <https://github.com/hakubo/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface HeadroomOptions {
offset?: number;
tolerance?: any;
classes?: {
initial?: string;
pinned?: string;
unpinned?: string;
top?: string;
notTop?: string;
};
scroller?: Element;
onPin?: () => void;
onUnPin?: () => void;
onTop?: () => void;
onNotTop?: () => void;
}
declare class Headroom {
constructor(element: Node, options?: HeadroomOptions);
constructor(element: Element, options?: HeadroomOptions);
init: () => void;
}
-15
View File
@@ -1,15 +0,0 @@
/// <reference path="JSONStream.d.ts" />
import json = require('JSONStream');
var read: NodeJS.ReadableStream;
var write: NodeJS.WritableStream;
read = read.pipe(json.parse('*'));
read = read.pipe(json.parse(['foo/*', 'bar/*']));
read = json.stringify();
read = json.stringify('{', ',', '}');
read = json.stringifyObject();
read = json.stringifyObject('{', ',', '}');
-22
View File
@@ -1,22 +0,0 @@
// Type definitions for JSONStream v0.8.0
// Project: http://github.com/dominictarr/JSONStream
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module 'JSONStream' {
export interface Options {
recurse: boolean;
}
export function parse(pattern: any): NodeJS.ReadWriteStream;
export function parse(patterns: any[]): NodeJS.ReadWriteStream;
export function stringify(): NodeJS.ReadWriteStream;
export function stringify(open: string, sep: string, close: string): NodeJS.ReadWriteStream;
export function stringifyObject(): NodeJS.ReadWriteStream;
export function stringifyObject(open: string, sep: string, close: string): NodeJS.ReadWriteStream;
}
-912
View File
@@ -1,912 +0,0 @@
// Type definitions for OpenJsCad.js
// Project: https://github.com/joostn/OpenJsCad
// Definitions by: Dan Marshall <https://github.com/danmarshall>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../threejs/three.d.ts" />
declare module THREE {
var CSG: {
fromCSG: (csg: CSG, defaultColor: any) => {
colorMesh: Mesh;
wireframe: Mesh;
boundLen: number;
};
getGeometryVertex: (geometry: any, vertex_position: any) => number;
};
function OrbitControls(object: any, domElement: any): void;
function SpriteCanvasMaterial(parameters?: any): void;
interface ICanvasRendererOptions {
canvas?: HTMLCanvasElement;
alpha?: boolean;
}
class CanvasRenderer implements Renderer {
domElement: HTMLCanvasElement;
private pixelRatio;
private autoClear;
private sortObjects;
private sortElements;
private info;
private _projector;
private _renderData;
private _elements;
private _lights;
private _canvas;
private _canvasWidth;
private _canvasHeight;
private _canvasWidthHalf;
private _canvasHeightHalf;
private _viewportX;
private _viewportY;
private _viewportWidth;
private _viewportHeight;
private _context;
private _clearColor;
private _clearAlpha;
private _contextGlobalAlpha;
private _contextGlobalCompositeOperation;
private _contextStrokeStyle;
private _camera;
private _contextFillStyle;
private _contextLineWidth;
private _contextLineCap;
private _contextLineJoin;
private _contextLineDash;
private _v1;
private _v2;
private _v3;
private _v4;
private _v5;
private _v6;
private _v1x;
private _v1y;
private _v2x;
private _v2y;
private _v3x;
private _v3y;
private _v4x;
private _v4y;
private _v5x;
private _v5y;
private _v6x;
private _v6y;
private _color;
private _color1;
private _color2;
private _color3;
private _color4;
private _diffuseColor;
private _emissiveColor;
private _lightColor;
private _patterns;
private _image;
private _uvs;
private _uv1x;
private _uv1y;
private _uv2x;
private _uv2y;
private _uv3x;
private _uv3y;
private _clipBox;
private _clearBox;
private _elemBox;
private _ambientLight;
private _directionalLights;
private _pointLights;
private _vector3;
private _centroid;
private _normal;
private _normalViewMatrix;
constructor(parameters: ICanvasRendererOptions);
supportsVertexTextures(): void;
setFaceCulling: () => void;
getPixelRatio(): number;
setPixelRatio(value: any): void;
setSize(width: any, height: any, updateStyle: any): void;
setViewport(x: any, y: any, width: any, height: any): void;
setScissor(): void;
enableScissorTest(): void;
setClearColor(color: any, alpha: any): void;
setClearColorHex(hex: any, alpha: any): void;
getClearColor(): Color;
getClearAlpha(): number;
getMaxAnisotropy(): number;
clear(): void;
clearColor(): void;
clearDepth(): void;
clearStencil(): void;
render(scene: Scene, camera: Camera, renderTarget?: RenderTarget, forceClear?: boolean): void;
calculateLights(): void;
calculateLight(position: any, normal: any, color: any): void;
renderSprite(v1: any, element: any, material: any): void;
renderLine(v1: any, v2: any, element: any, material: any): void;
renderFace3(v1: any, v2: any, v3: any, uv1: any, uv2: any, uv3: any, element: any, material: any): void;
drawTriangle(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any): void;
strokePath(color: any, linewidth: any, linecap: any, linejoin: any): void;
fillPath(color: any): void;
onTextureUpdate(event: any): void;
textureToPattern(texture: any): void;
patternPath(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any, u0: any, v0: any, u1: any, v1: any, u2: any, v2: any, texture: any): void;
clipImage(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any, u0: any, v0: any, u1: any, v1: any, u2: any, v2: any, image: any): void;
expand(v1: any, v2: any, pixels: any): void;
setOpacity(value: any): void;
setBlending(value: any): void;
setLineWidth(value: any): void;
setLineCap(value: any): void;
setLineJoin(value: any): void;
setStrokeStyle(value: any): void;
setFillStyle(value: any): void;
setLineDash(value: any): void;
}
function RenderableObject(): void;
function RenderableFace(): void;
function RenderableVertex(): void;
function RenderableLine(): void;
function RenderableSprite(): void;
function Projector(): void;
}
declare module OpenJsCad {
interface ILog {
(x: string): void;
prevLogTime?: number;
}
var log: ILog;
interface IViewerOptions {
drawLines?: boolean;
drawFaces?: boolean;
color?: number[];
bgColor?: number;
noWebGL?: boolean;
}
interface ProcessorOptions extends IViewerOptions {
verbose?: boolean;
viewerwidth?: number;
viewerheight?: number;
viewerheightratio?: number;
}
class Viewer {
private perspective;
private drawOptions;
private size;
private defaultColor_;
private bgColor_;
private containerElm_;
private scene_;
private camera_;
private controls_;
private renderer_;
private canvas;
private pauseRender_;
private requestID_;
constructor(containerElm: any, size: any, options: IViewerOptions);
createScene(drawAxes: any, axLen: any): void;
createCamera(): void;
createControls(canvas: any): void;
webGLAvailable(): boolean;
createRenderer(bool_noWebGL: any): void;
render(): void;
animate(): void;
cancelAnimate(): void;
refreshRenderer(bool_noWebGL: any): void;
drawAxes(axLen: any): void;
setCsg(csg: any, resetZoom: any): void;
applyDrawOptions(): void;
clear(): void;
getUserMeshes(str?: any): THREE.Object3D[];
resetZoom(r: any): void;
parseSizeParams(): void;
handleResize(): void;
}
function makeAbsoluteUrl(url: any, baseurl: any): any;
function isChrome(): boolean;
function runMainInWorker(mainParameters: any): void;
function expandResultObjectArray(result: any): any;
function checkResult(result: any): void;
function resultToCompactBinary(resultin: any): any;
function resultFromCompactBinary(resultin: any): any;
function parseJsCadScriptSync(script: any, mainParameters: any, debugging: any): any;
function parseJsCadScriptASync(script: any, mainParameters: any, options: any, callback: any): Worker;
function getWindowURL(): URL;
function textToBlobUrl(txt: any): string;
function revokeBlobUrl(url: any): void;
function FileSystemApiErrorHandler(fileError: any, operation: any): void;
function AlertUserOfUncaughtExceptions(): void;
function getParamDefinitions(script: any): any[];
interface EventHandler {
(ev?: Event): any;
}
/**
* options parameter:
* - drawLines: display wireframe lines
* - drawFaces: display surfaces
* - bgColor: canvas background color
* - color: object color
* - viewerwidth, viewerheight: set rendering size. Works with any css unit.
* viewerheight can also be specified as a ratio to width, ie number e (0, 1]
* - noWebGL: force render without webGL
* - verbose: show additional info (currently only time used for rendering)
*/
interface ViewerSize {
widthDefault: string;
heightDefault: string;
width: number;
height: number;
heightratio: number;
}
class Processor {
private containerdiv;
private options;
private onchange;
private static widthDefault;
private static heightDefault;
private viewerdiv;
private viewer;
private viewerSize;
private processing;
private currentObject;
private hasValidCurrentObject;
private hasOutputFile;
private worker;
private paramDefinitions;
private paramControls;
private script;
private hasError;
private debugging;
private errordiv;
private errorpre;
private statusdiv;
private controldiv;
private statusspan;
private statusbuttons;
private abortbutton;
private renderedElementDropdown;
private formatDropdown;
private generateOutputFileButton;
private downloadOutputFileLink;
private parametersdiv;
private parameterstable;
private currentFormat;
private filename;
private currentObjects;
private currentObjectIndex;
private isFirstRender_;
private outputFileDirEntry;
private outputFileBlobUrl;
constructor(containerdiv: HTMLDivElement, options?: ProcessorOptions, onchange?: EventHandler);
static convertToSolid(obj: any): any;
cleanOption(option: any, deflt: any): any;
toggleDrawOption(str: any): boolean;
setDrawOption(str: any, bool: any): void;
handleResize(): void;
createElements(): void;
getFilenameForRenderedObject(): string;
setRenderedObjects(obj: any): void;
setSelectedObjectIndex(index: number): void;
selectedFormat(): any;
selectedFormatInfo(): any;
updateDownloadLink(): void;
clearViewer(): void;
abort(): void;
enableItems(): void;
setOpenJsCadPath(path: string): void;
addLibrary(lib: any): void;
setError(txt: string): void;
setDebugging(debugging: boolean): void;
setJsCad(script: string, filename?: string): void;
getParamValues(): {};
rebuildSolid(): void;
hasSolid(): boolean;
isProcessing(): boolean;
clearOutputFile(): void;
generateOutputFile(): void;
currentObjectToBlob(): any;
supportedFormatsForCurrentObject(): string[];
formatInfo(format: any): any;
downloadLinkTextForCurrentObject(): string;
generateOutputFileBlobUrl(): void;
generateOutputFileFileSystem(): void;
createParamControls(): void;
}
}
interface Window {
Worker: Worker;
// URL: URL;
webkitURL: URL;
requestFileSystem: any;
webkitRequestFileSystem: any;
}
interface IAMFStringOptions {
unit: string;
}
declare class CxG {
toStlString(): string;
toStlBinary(): void;
toAMFString(AMFStringOptions?: IAMFStringOptions): void;
getBounds(): CxG[];
transform(matrix4x4: CSG.Matrix4x4): CxG;
mirrored(plane: CSG.Plane): CxG;
mirroredX(): CxG;
mirroredY(): CxG;
mirroredZ(): CxG;
translate(v: number[]): CxG;
translate(v: CSG.Vector3D): CxG;
scale(f: CSG.Vector3D): CxG;
rotateX(deg: number): CxG;
rotateY(deg: number): CxG;
rotateZ(deg: number): CxG;
rotate(rotationCenter: CSG.Vector3D, rotationAxis: CSG.Vector3D, degrees: number): CxG;
rotateEulerAngles(alpha: number, beta: number, gamma: number, position: number[]): CxG;
}
interface ICenter {
center(cAxes: string[]): CxG;
}
declare class CSG extends CxG implements ICenter {
polygons: CSG.Polygon[];
properties: CSG.Properties;
isCanonicalized: boolean;
isRetesselated: boolean;
cachedBoundingBox: CSG.Vector3D[];
static defaultResolution2D: number;
static defaultResolution3D: number;
static fromPolygons(polygons: CSG.Polygon[]): CSG;
static fromSlices(options: any): CSG;
static fromObject(obj: any): CSG;
static fromCompactBinary(bin: any): CSG;
toPolygons(): CSG.Polygon[];
union(csg: CSG[]): CSG;
union(csg: CSG): CSG;
unionSub(csg: CSG, retesselate?: boolean, canonicalize?: boolean): CSG;
unionForNonIntersecting(csg: CSG): CSG;
subtract(csg: CSG[]): CSG;
subtract(csg: CSG): CSG;
subtractSub(csg: CSG, retesselate: boolean, canonicalize: boolean): CSG;
intersect(csg: CSG[]): CSG;
intersect(csg: CSG): CSG;
intersectSub(csg: CSG, retesselate?: boolean, canonicalize?: boolean): CSG;
invert(): CSG;
transform1(matrix4x4: CSG.Matrix4x4): CSG;
transform(matrix4x4: CSG.Matrix4x4): CSG;
toString(): string;
expand(radius: number, resolution: number): CSG;
contract(radius: number, resolution: number): CSG;
stretchAtPlane(normal: number[], point: number[], length: number): CSG;
expandedShell(radius: number, resolution: number, unionWithThis: boolean): CSG;
canonicalized(): CSG;
reTesselated(): CSG;
getBounds(): CSG.Vector3D[];
mayOverlap(csg: CSG): boolean;
cutByPlane(plane: CSG.Plane): CSG;
connectTo(myConnector: CSG.Connector, otherConnector: CSG.Connector, mirror: boolean, normalrotation: number): CSG;
setShared(shared: CSG.Polygon.Shared): CSG;
setColor(args: any): CSG;
toCompactBinary(): {
"class": string;
numPolygons: number;
numVerticesPerPolygon: Uint32Array;
polygonPlaneIndexes: Uint32Array;
polygonSharedIndexes: Uint32Array;
polygonVertices: Uint32Array;
vertexData: Float64Array;
planeData: Float64Array;
shared: CSG.Polygon.Shared[];
};
toPointCloud(cuberadius: any): CSG;
getTransformationAndInverseTransformationToFlatLying(): any;
getTransformationToFlatLying(): any;
lieFlat(): CSG;
projectToOrthoNormalBasis(orthobasis: CSG.OrthoNormalBasis): CAG;
sectionCut(orthobasis: CSG.OrthoNormalBasis): CAG;
fixTJunctions(): CSG;
toTriangles(): any[];
getFeatures(features: any): any;
center(cAxes: string[]): CxG;
toX3D(): Blob;
toStlBinary(): Blob;
toStlString(): string;
toAMFString(m: IAMFStringOptions): Blob;
}
declare module CSG {
function fnNumberSort(a: any, b: any): number;
function parseOption(options: any, optionname: any, defaultvalue: any): any;
function parseOptionAs3DVector(options: any, optionname: any, defaultvalue: any): Vector3D;
function parseOptionAs3DVectorList(options: any, optionname: any, defaultvalue: any): any;
function parseOptionAs2DVector(options: any, optionname: any, defaultvalue: any): any;
function parseOptionAsFloat(options: any, optionname: any, defaultvalue: any): any;
function parseOptionAsInt(options: any, optionname: any, defaultvalue: any): any;
function parseOptionAsBool(options: any, optionname: any, defaultvalue: any): any;
function cube(options: any): CSG;
function sphere(options: any): CSG;
function cylinder(options: any): CSG;
function roundedCylinder(options: any): CSG;
function roundedCube(options: any): CSG;
/**
* polyhedron accepts openscad style arguments. I.e. define face vertices clockwise looking from outside
*/
function polyhedron(options: any): CSG;
function IsFloat(n: any): boolean;
function solve2Linear(a: any, b: any, c: any, d: any, u: any, v: any): number[];
class Vector3D extends CxG {
x: number;
y: number;
z: number;
constructor(v3: Vector3D);
constructor(v2: Vector2D);
constructor(v2: number[]);
constructor(x: number, y: number);
constructor(x: number, y: number, z: number);
static Create(x: number, y: number, z: number): Vector3D;
clone(): Vector3D;
negated(): Vector3D;
abs(): Vector3D;
plus(a: Vector3D): Vector3D;
minus(a: Vector3D): Vector3D;
times(a: number): Vector3D;
dividedBy(a: number): Vector3D;
dot(a: Vector3D): number;
lerp(a: Vector3D, t: number): Vector3D;
lengthSquared(): number;
length(): number;
unit(): Vector3D;
cross(a: Vector3D): Vector3D;
distanceTo(a: Vector3D): number;
distanceToSquared(a: Vector3D): number;
equals(a: Vector3D): boolean;
multiply4x4(matrix4x4: Matrix4x4): Vector3D;
transform(matrix4x4: Matrix4x4): Vector3D;
toString(): string;
randomNonParallelVector(): Vector3D;
min(p: Vector3D): Vector3D;
max(p: Vector3D): Vector3D;
toStlString(): string;
toAMFString(): string;
}
class Vertex extends CxG {
pos: Vector3D;
tag: number;
constructor(pos: Vector3D);
static fromObject(obj: any): Vertex;
flipped(): Vertex;
getTag(): number;
interpolate(other: Vertex, t: number): Vertex;
transform(matrix4x4: Matrix4x4): Vertex;
toString(): string;
toStlString(): string;
toAMFString(): string;
}
class Plane extends CxG {
normal: Vector3D;
w: number;
tag: number;
constructor(normal: Vector3D, w: number);
static fromObject(obj: any): Plane;
static EPSILON: number;
static fromVector3Ds(a: Vector3D, b: Vector3D, c: Vector3D): Plane;
static anyPlaneFromVector3Ds(a: Vector3D, b: Vector3D, c: Vector3D): Plane;
static fromPoints(a: Vector3D, b: Vector3D, c: Vector3D): Plane;
static fromNormalAndPoint(normal: Vector3D, point: Vector3D): Plane;
static fromNormalAndPoint(normal: number[], point: number[]): Plane;
flipped(): Plane;
getTag(): number;
equals(n: Plane): boolean;
transform(matrix4x4: Matrix4x4): Plane;
splitPolygon(polygon: Polygon): {
type: any;
front: any;
back: any;
};
splitLineBetweenPoints(p1: Vector3D, p2: Vector3D): Vector3D;
intersectWithLine(line3d: Line3D): Vector3D;
intersectWithPlane(plane: Plane): Line3D;
signedDistanceToPoint(point: Vector3D): number;
toString(): string;
mirrorPoint(point3d: Vector3D): Vector3D;
}
class Polygon extends CxG {
vertices: Vertex[];
shared: Polygon.Shared;
plane: Plane;
cachedBoundingSphere: any;
cachedBoundingBox: Vector3D[];
static defaultShared: CSG.Polygon.Shared;
constructor(vertices: Vector3D, shared?: Polygon.Shared, plane?: Plane);
constructor(vertices: Vertex[], shared?: Polygon.Shared, plane?: Plane);
static fromObject(obj: any): Polygon;
checkIfConvex(): void;
setColor(args: any): Polygon;
getSignedVolume(): number;
getArea(): number;
getTetraFeatures(features: any): any[];
extrude(offsetvector: any): CSG;
boundingSphere(): any;
boundingBox(): Vector3D[];
flipped(): Polygon;
transform(matrix4x4: Matrix4x4): Polygon;
toString(): string;
projectToOrthoNormalBasis(orthobasis: OrthoNormalBasis): CAG;
/**
* Creates solid from slices (CSG.Polygon) by generating walls
* @param {Object} options Solid generating options
* - numslices {Number} Number of slices to be generated
* - callback(t, slice) {Function} Callback function generating slices.
* arguments: t = [0..1], slice = [0..numslices - 1]
* return: CSG.Polygon or null to skip
* - loop {Boolean} no flats, only walls, it's used to generate solids like a tor
*/
solidFromSlices(options: any): CSG;
/**
*
* @param walls Array of wall polygons
* @param bottom Bottom polygon
* @param top Top polygon
*/
private _addWalls(walls, bottom, top, bFlipped);
static verticesConvex(vertices: Vertex[], planenormal: any): boolean;
static createFromPoints(points: number[][], shared?: CSG.Polygon.Shared, plane?: Plane): Polygon;
static isConvexPoint(prevpoint: any, point: any, nextpoint: any, normal: any): boolean;
static isStrictlyConvexPoint(prevpoint: any, point: any, nextpoint: any, normal: any): boolean;
toStlString(): string;
}
}
declare module CSG.Polygon {
class Shared {
color: any;
tag: any;
constructor(color: any);
static fromObject(obj: any): Shared;
static fromColor(args: any): Shared;
getTag(): any;
getHash(): any;
}
}
declare module CSG {
class PolygonTreeNode {
parent: any;
children: any;
polygon: Polygon;
removed: boolean;
constructor();
addPolygons(polygons: any): void;
remove(): void;
isRemoved(): boolean;
isRootNode(): boolean;
invert(): void;
getPolygon(): Polygon;
getPolygons(result: Polygon[]): void;
splitByPlane(plane: any, coplanarfrontnodes: any, coplanarbacknodes: any, frontnodes: any, backnodes: any): void;
_splitByPlane(plane: any, coplanarfrontnodes: any, coplanarbacknodes: any, frontnodes: any, backnodes: any): void;
addChild(polygon: Polygon): PolygonTreeNode;
invertSub(): void;
recursivelyInvalidatePolygon(): void;
}
class Tree {
polygonTree: PolygonTreeNode;
rootnode: Node;
constructor(polygons: Polygon[]);
invert(): void;
clipTo(tree: Tree, alsoRemovecoplanarFront?: boolean): void;
allPolygons(): Polygon[];
addPolygons(polygons: Polygon[]): void;
}
class Node {
parent: Node;
plane: Plane;
front: any;
back: any;
polygontreenodes: PolygonTreeNode[];
constructor(parent: Node);
invert(): void;
clipPolygons(polygontreenodes: PolygonTreeNode[], alsoRemovecoplanarFront: boolean): void;
clipTo(tree: Tree, alsoRemovecoplanarFront: boolean): void;
addPolygonTreeNodes(polygontreenodes: PolygonTreeNode[]): void;
getParentPlaneNormals(normals: Vector3D[], maxdepth: number): void;
}
class Matrix4x4 {
elements: number[];
constructor(elements?: number[]);
plus(m: Matrix4x4): Matrix4x4;
minus(m: Matrix4x4): Matrix4x4;
multiply(m: Matrix4x4): Matrix4x4;
clone(): Matrix4x4;
rightMultiply1x3Vector(v: Vector3D): Vector3D;
leftMultiply1x3Vector(v: Vector3D): Vector3D;
rightMultiply1x2Vector(v: Vector2D): Vector2D;
leftMultiply1x2Vector(v: Vector2D): Vector2D;
isMirroring(): boolean;
static unity(): Matrix4x4;
static rotationX(degrees: number): Matrix4x4;
static rotationY(degrees: number): Matrix4x4;
static rotationZ(degrees: number): Matrix4x4;
static rotation(rotationCenter: CSG.Vector3D, rotationAxis: CSG.Vector3D, degrees: number): Matrix4x4;
static translation(v: number[]): Matrix4x4;
static translation(v: Vector3D): Matrix4x4;
static mirroring(plane: Plane): Matrix4x4;
static scaling(v: number[]): Matrix4x4;
static scaling(v: Vector3D): Matrix4x4;
}
class Vector2D extends CxG {
x: number;
y: number;
constructor(x: number, y: number);
constructor(x: number[]);
constructor(x: Vector2D);
static fromAngle(radians: number): Vector2D;
static fromAngleDegrees(degrees: number): Vector2D;
static fromAngleRadians(radians: number): Vector2D;
static Create(x: number, y: number): Vector2D;
toVector3D(z: number): Vector3D;
equals(a: Vector2D): boolean;
clone(): Vector2D;
negated(): Vector2D;
plus(a: Vector2D): Vector2D;
minus(a: Vector2D): Vector2D;
times(a: number): Vector2D;
dividedBy(a: number): Vector2D;
dot(a: Vector2D): number;
lerp(a: Vector2D, t: number): Vector2D;
length(): number;
distanceTo(a: Vector2D): number;
distanceToSquared(a: Vector2D): number;
lengthSquared(): number;
unit(): Vector2D;
cross(a: Vector2D): number;
normal(): Vector2D;
multiply4x4(matrix4x4: Matrix4x4): Vector2D;
transform(matrix4x4: Matrix4x4): Vector2D;
angle(): number;
angleDegrees(): number;
angleRadians(): number;
min(p: Vector2D): Vector2D;
max(p: Vector2D): Vector2D;
toString(): string;
abs(): Vector2D;
}
class Line2D extends CxG {
normal: Vector2D;
w: number;
constructor(normal: Vector2D, w: number);
static fromPoints(p1: Vector2D, p2: Vector2D): Line2D;
reverse(): Line2D;
equals(l: Line2D): boolean;
origin(): Vector2D;
direction(): Vector2D;
xAtY(y: number): number;
absDistanceToPoint(point: Vector2D): number;
intersectWithLine(line2d: Line2D): Vector2D;
transform(matrix4x4: Matrix4x4): Line2D;
}
class Line3D extends CxG {
point: Vector3D;
direction: Vector3D;
constructor(point: Vector3D, direction: Vector3D);
static fromPoints(p1: Vector3D, p2: Vector3D): Line3D;
static fromPlanes(p1: Plane, p2: Plane): Line3D;
intersectWithPlane(plane: Plane): Vector3D;
clone(): Line3D;
reverse(): Line3D;
transform(matrix4x4: Matrix4x4): Line3D;
closestPointOnLine(point: Vector3D): Vector3D;
distanceToPoint(point: Vector3D): number;
equals(line3d: Line3D): boolean;
}
class OrthoNormalBasis extends CxG {
v: Vector3D;
u: Vector3D;
plane: Plane;
planeorigin: Vector3D;
constructor(plane: Plane, rightvector?: Vector3D);
static GetCartesian(xaxisid: string, yaxisid: string): OrthoNormalBasis;
static Z0Plane(): OrthoNormalBasis;
getProjectionMatrix(): Matrix4x4;
getInverseProjectionMatrix(): Matrix4x4;
to2D(vec3: Vector3D): Vector2D;
to3D(vec2: Vector2D): Vector3D;
line3Dto2D(line3d: Line3D): Line2D;
line2Dto3D(line2d: Line2D): Line3D;
transform(matrix4x4: Matrix4x4): OrthoNormalBasis;
}
function interpolateBetween2DPointsForY(point1: Vector2D, point2: Vector2D, y: number): number;
function reTesselateCoplanarPolygons(sourcepolygons: CSG.Polygon[], destpolygons: CSG.Polygon[]): void;
class fuzzyFactory {
multiplier: number;
lookuptable: any;
constructor(numdimensions: number, tolerance: number);
lookupOrCreate(els: any, creatorCallback: any): any;
}
class fuzzyCSGFactory {
vertexfactory: fuzzyFactory;
planefactory: fuzzyFactory;
polygonsharedfactory: any;
constructor();
getPolygonShared(sourceshared: Polygon.Shared): Polygon.Shared;
getVertex(sourcevertex: Vertex): Vertex;
getPlane(sourceplane: Plane): Plane;
getPolygon(sourcepolygon: Polygon): Polygon;
getCSG(sourcecsg: CSG): CSG;
}
var staticTag: number;
function getTag(): number;
class Properties {
cube: Properties;
center: any;
facecenters: any[];
roundedCube: Properties;
cylinder: Properties;
start: any;
end: any;
facepointH: any;
facepointH90: any;
sphere: Properties;
facepoint: any;
roundedCylinder: any;
_transform(matrix4x4: Matrix4x4): Properties;
_merge(otherproperties: Properties): Properties;
static transformObj(source: any, result: any, matrix4x4: Matrix4x4): void;
static cloneObj(source: any, result: any): void;
static addFrom(result: any, otherproperties: Properties): void;
}
class Connector extends CxG {
point: Vector3D;
axisvector: Vector3D;
normalvector: Vector3D;
constructor(point: number[], axisvector: Vector3D, normalvector: number[]);
constructor(point: number[], axisvector: number[], normalvector: number[]);
constructor(point: number[], axisvector: number[], normalvector: Vector3D);
constructor(point: Vector3D, axisvector: number[], normalvector: Vector3D);
constructor(point: Vector3D, axisvector: number[], normalvector: number[]);
constructor(point: Vector3D, axisvector: Vector3D, normalvector: Vector3D);
normalized(): Connector;
transform(matrix4x4: Matrix4x4): Connector;
getTransformationTo(other: Connector, mirror: boolean, normalrotation: number): Matrix4x4;
axisLine(): Line3D;
extend(distance: number): Connector;
}
class ConnectorList {
connectors_: Connector[];
closed: boolean;
constructor(connectors: Connector[]);
static defaultNormal: number[];
static fromPath2D(path2D: CSG.Path2D, arg1: any, arg2: any): ConnectorList;
static _fromPath2DTangents(path2D: any, start: any, end: any): ConnectorList;
static _fromPath2DExplicit(path2D: any, angleIsh: any): ConnectorList;
setClosed(bool: boolean): void;
appendConnector(conn: Connector): void;
followWith(cagish: any): CSG;
verify(): void;
}
interface IRadiusOptions {
radius?: number;
resolution?: number;
}
interface ICircleOptions extends IRadiusOptions {
center?: Vector2D | number[];
}
interface IArcOptions extends ICircleOptions {
startangle?: number;
endangle?: number;
maketangent?: boolean;
}
interface IEllpiticalArcOptions extends IRadiusOptions {
clockwise?: boolean;
large?: boolean;
xaxisrotation?: number;
xradius?: number;
yradius?: number;
}
interface IRectangleOptions {
center?: Vector2D;
corner1?: Vector2D;
corner2?: Vector2D;
radius?: Vector2D;
}
interface IRoundRectangleOptions {
roundradius: number;
resolution?: number;
}
class Path2D extends CxG {
closed: boolean;
points: Vector2D[];
lastBezierControlPoint: Vector2D;
constructor(points: number[], closed?: boolean);
constructor(points: Vector2D[], closed?: boolean);
static arc(options: IArcOptions): Path2D;
concat(otherpath: Path2D): Path2D;
appendPoint(point: Vector2D): Path2D;
appendPoints(points: Vector2D[]): Path2D;
close(): Path2D;
rectangularExtrude(width: number, height: number, resolution: number): CSG;
expandToCAG(pathradius: number, resolution: number): CAG;
innerToCAG(): CAG;
transform(matrix4x4: Matrix4x4): Path2D;
appendBezier(controlpoints: any, options: any): Path2D;
appendArc(endpoint: Vector2D, options: IEllpiticalArcOptions): Path2D;
}
}
declare class CAG extends CxG implements ICenter {
sides: CAG.Side[];
isCanonicalized: boolean;
constructor();
static fromSides(sides: CAG.Side[]): CAG;
static fromPoints(points: CSG.Vector2D[]): CAG;
static fromPointsNoCheck(points: CSG.Vector2D[]): CAG;
static fromFakeCSG(csg: CSG): CAG;
static linesIntersect(p0start: CSG.Vector2D, p0end: CSG.Vector2D, p1start: CSG.Vector2D, p1end: CSG.Vector2D): boolean;
static circle(options: CSG.ICircleOptions): CAG;
static rectangle(options: CSG.IRectangleOptions): CAG;
static roundedRectangle(options: any): CAG;
static fromCompactBinary(bin: any): CAG;
toString(): string;
_toCSGWall(z0: any, z1: any): CSG;
_toVector3DPairs(m: CSG.Matrix4x4): CSG.Vector3D[][];
_toPlanePolygons(options: any): CSG.Polygon[];
_toWallPolygons(options: any): any[];
union(cag: CAG[]): CAG;
union(cag: CAG): CAG;
subtract(cag: CAG[]): CAG;
subtract(cag: CAG): CAG;
intersect(cag: CAG[]): CAG;
intersect(cag: CAG): CAG;
transform(matrix4x4: CSG.Matrix4x4): CAG;
area(): number;
flipped(): CAG;
getBounds(): CSG.Vector2D[];
isSelfIntersecting(): boolean;
expandedShell(radius: number, resolution: number): CAG;
expand(radius: number, resolution: number): CAG;
contract(radius: number, resolution: number): CAG;
extrudeInOrthonormalBasis(orthonormalbasis: CSG.OrthoNormalBasis, depth: number, options?: any): CSG;
extrudeInPlane(axis1: any, axis2: any, depth: any, options: any): CSG;
extrude(options: CAG_extrude_options): CSG;
rotateExtrude(options: any): CSG;
check(): void;
canonicalized(): CAG;
toCompactBinary(): {
'class': string;
sideVertexIndices: Uint32Array;
vertexData: Float64Array;
};
getOutlinePaths(): CSG.Path2D[];
overCutInsideCorners(cutterradius: any): CAG;
center(cAxes: string[]): CxG;
toDxf(): Blob;
static PathsToDxf(paths: CSG.Path2D[]): Blob;
}
declare module CAG {
class Vertex {
pos: CSG.Vector2D;
tag: number;
constructor(pos: CSG.Vector2D);
toString(): string;
getTag(): number;
}
class Side extends CxG {
vertex0: Vertex;
vertex1: Vertex;
tag: number;
constructor(vertex0: Vertex, vertex1: Vertex);
static _fromFakePolygon(polygon: CSG.Polygon): Side;
toString(): string;
toPolygon3D(z0: any, z1: any): CSG.Polygon;
transform(matrix4x4: CSG.Matrix4x4): Side;
flipped(): Side;
direction(): CSG.Vector2D;
getTag(): number;
lengthSquared(): number;
length(): number;
}
class fuzzyCAGFactory {
vertexfactory: CSG.fuzzyFactory;
constructor();
getVertex(sourcevertex: Vertex): Vertex;
getSide(sourceside: Side): Side;
getCAG(sourcecag: CAG): CAG;
}
}
interface CAG_extrude_options {
offset?: number[];
twistangle?: number;
twiststeps?: number;
}
declare module CSG {
class Polygon2D extends CAG {
constructor(points: Vector2D[]);
}
}
@@ -1,115 +0,0 @@
/// <reference path="PayPal-Cordova-Plugin.d.ts"/>
var item: PayPalItem;
item = new PayPalItem("name", 10, "25.00", "USD");
item = new PayPalItem("name", 10, "25.00", "USD", null);
item = new PayPalItem("name", 10, "25.00", "USD", "SKU_ID");
var item_name: string = item.name;
var item_quantity: number = item.quantity;
var item_price: string = item.price;
var item_currency: string = item.currency;
var item_sku: string = item.sku;
var paymentDetails: PayPalPaymentDetails;
paymentDetails = new PayPalPaymentDetails("10.50", "2.50", "1.25");
var paymentDetails_subtotal: string = paymentDetails.subtotal;
var paymentDetails_shipping: string = paymentDetails.shipping;
var paymentDetails_tax: string = paymentDetails.tax;
var shippingAddress: PayPalShippingAddress;
shippingAddress = new PayPalShippingAddress("name", "line1", "line2", "city", "state", "postalCode", "countryCode");
var shippingAddress_recipientName: string = shippingAddress.recipientName;
var shippingAddress_line1: string = shippingAddress.line1;
var shippingAddress_line2: string = shippingAddress.line2;
var shippingAddress_city: string = shippingAddress.city;
var shippingAddress_state: string = shippingAddress.state;
var shippingAddress_postalCode: string = shippingAddress.postalCode;
var shippingAddress_countryCode: string = shippingAddress.countryCode;
var payment: PayPalPayment;
payment = new PayPalPayment("10.00", "USD", "description", "Auth");
payment = new PayPalPayment("10.00", "USD", "description", "Auth", paymentDetails);
var payment_amount: string = payment.amount;
var payment_currency: string = payment.currency;
var payment_shortDescription: string = payment.shortDescription;
var payment_intent: string = payment.intent;
var payment_details: PayPalPaymentDetails = payment.details;
var payment_invoiceNumber: string = payment.invoiceNumber;
var payment_custom: string = payment.custom;
var payment_softDescriptor: string = payment.softDescriptor;
var payment_bnCode: string = payment.bnCode;
var payment_items: PayPalItem[] = [item, item, item];
var payment_shippingAddress: PayPalShippingAddress = shippingAddress;
var configOptions: PayPalConfigurationOptions = {
defaultUserEmail: "email",
defaultUserPhoneCountryCode: "countryCode",
defaultUserPhoneNumber: "phoneNumber",
merchantName: "merchantName",
merchantPrivacyPolicyURL: "merchantPrivacyPolicyURL",
merchantUserAgreementURL: "merchantUserAgreementURL",
acceptCreditCards: true,
payPalShippingAddressOption: 10,
rememberUser: true,
languageOrLocale: "languageOrLocal",
disableBlurWhenBackgrounding: true,
presentingInPopover: true,
forceDefaultsInSandbox: true,
sandboxUserPassword: "sandboxUserPassword",
sandboxUserPin: "sandboxUserPin"
};
var config: PayPalConfiguration;
config = new PayPalConfiguration();
config = new PayPalConfiguration(null);
config = new PayPalConfiguration(configOptions);
var config_defaultUserEmail: string = config.defaultUserEmail;
var config_defaultUserPhoneCountryCode: string = config.defaultUserPhoneCountryCode;
var config_defaultUserPhoneNumber: string = config.defaultUserPhoneNumber;
var config_merchantName: string = config.merchantName;
var config_merchantPrivacyPolicyURL: string = config.merchantPrivacyPolicyURL;
var config_merchantUserAgreementURL: string = config.merchantUserAgreementURL;
var config_acceptCreditCards: boolean = config.acceptCreditCards;
var config_payPalShippingAddressOption: number = config.payPalShippingAddressOption;
var config_rememberUser: boolean = config.rememberUser;
var config_languageOrLocale: string = config.languageOrLocale;
var config_disableBlurWhenBackgrounding: boolean = config.disableBlurWhenBackgrounding;
var config_presentingInPopover: boolean = config.presentingInPopover;
var config_forceDefaultsInSandbox: boolean = config.forceDefaultsInSandbox;
var config_sandboxUserPasword: string = config.sandboxUserPassword;
var config_sandboxUserPin: string = config.sandboxUserPin;
var clientIds: PayPalCordovaPlugin.PayPalClientIds = {
PayPalEnvironmentProduction: "",
PayPalEnvironmentSandbox: ""
};
var apiModule: PayPalCordovaPlugin.PayPalMobileStatic = PayPalMobile;
apiModule.version((result: string) => {});
apiModule.init(clientIds, () => {});
apiModule.prepareToRender("environment", config, () => {});
apiModule.renderSinglePaymentUI(payment, (result: any) => {}, (cancelReason: string) => {});
apiModule.applicationCorrelationIDForEnvironment("environment", (applicationCorrelationId: string) => {});
apiModule.clientMetadataID((clientMetadataId: string) => {});
apiModule.renderFuturePaymentUI((result: any) => {}, (cancelReason: string) => {});
apiModule.renderProfileSharingUI(["openid", "profile", "email"], (result: any) => {}, (cancelReason: string) => {});
-615
View File
@@ -1,615 +0,0 @@
// Type definitions for PayPal-Cordova-Plugin 3.1.10
// Project: https://github.com/paypal/PayPal-Cordova-Plugin
// Definitions by: Justin Unterreiner <https://github.com/Justin-Credible>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
//#region paypal-mobile-js-helper.js
/**
* The PayPalItem class defines an optional itemization for a payment.
*
* @see https://developer.paypal.com/docs/api/#item-object for more details.
*/
declare class PayPalItem {
/**
* @param name Name of the item. 127 characters max.
* @param quantity Number of units. 10 characters max.
* @param price Unit price for this item 10 characters max.
* May be negative for "coupon" etc.
* @param currency ISO standard currency code.
* @param sku The stock keeping unit for this item. 50 characters max (optional).
*/
constructor(name: string, quantity: number, price: string, currency: string, sku?: string);
/**
* Name of the item. 127 characters max.
*/
name: string;
/**
* Number of units. 10 characters max.
*/
quantity: number;
/**
* Unit price for this item 10 characters max.
* May be negative for "coupon" etc.
*/
price: string;
/**
* ISO standard currency code.
*/
currency: string;
/**
* The stock keeping unit for this item. 50 characters max (optional).
*/
sku: string;
}
/**
* The PayPalPaymentDetails class defines optional amount details.
*
* @see https://developer.paypal.com/webapps/developer/docs/api/#details-object for more details.
*/
declare class PayPalPaymentDetails {
/**
* @param subtotal Sub-total (amount) of items being paid for. 10 characters max with support for 2 decimal places.
* @param shipping Amount charged for shipping. 10 characters max with support for 2 decimal places.
* @param tax Amount charged for tax. 10 characters max with support for 2 decimal places.
*/
constructor(subtotal: string, shipping: string, tax: string);
/**
* Sub-total (amount) of items being paid for. 10 characters max with support for 2 decimal places.
*/
subtotal: string;
/**
* Amount charged for shipping. 10 characters max with support for 2 decimal places.
*/
shipping: string;
/**
* Amount charged for tax. 10 characters max with support for 2 decimal places.
*/
tax: string;
}
/**
* Convenience constructor. Returns a PayPalPayment with the specified amount, currency code, and short description.
*/
declare class PayPalPayment {
/**
* @param amount The amount of the payment.
* @param currencyCode The ISO 4217 currency for the payment.
* @param shortDescription A short descripton of the payment.
* @param intent • "Sale" for an immediate payment.
* • "Auth" for payment authorization only, to be captured separately at a later time.
* • "Order" for taking an order, with authorization and capture to be done separately at a later time.
* @param details PayPalPaymentDetails object (optional).
*/
constructor(amount: string, currency: string, shortDescription: string, intent: string, details?: PayPalPaymentDetails);
/**
* The amount of the payment.
*/
amount: string;
/**
* The ISO 4217 currency for the payment.
*/
currency: string;
/**
* A short descripton of the payment.
*/
shortDescription: string;
/**
* • "Sale" for an immediate payment.
* • "Auth" for payment authorization only, to be captured separately at a later time.
* • "Order" for taking an order, with authorization and capture to be done separately at a later time.
*/
intent: string;
/**
* PayPalPaymentDetails object (optional).
*/
details: PayPalPaymentDetails;
/**
* Optional invoice number, for your tracking purposes. (up to 256 characters).
*/
invoiceNumber: string;
/**
* Optional text, for your tracking purposes. (up to 256 characters).
*/
custom: string;
/**
* Optional text which will appear on the customer's credit card statement. (up to 22 characters).
*/
softDescriptor: string;
/**
* Optional Build Notation code ("BN code"), obtained from partnerprogram@paypal.com, for your tracking purposes.
*/
bnCode: string;
/**
* Optional array of PayPalItem objects.
* @see PayPalItem
* @note If you provide one or more items, be sure that the various prices correctly sum to the payment `amount` or to `paymentDetails.subtotal`.
*/
items: PayPalItem[];
/**
* Optional customer shipping address, if your app wishes to provide this to the SDK.
* @note make sure to set `payPalShippingAddressOption` in PayPalConfiguration to 1 or 3.
*/
shippingAddress: PayPalShippingAddress;
}
declare class PayPalShippingAddress {
/**
* @param recipientName Name of the recipient at this address. 50 characters max.
* @param line1 Line 1 of the address (e.g., Number, street, etc). 100 characters max.
* @param line2 Line 2 of the address (e.g., Suite, apt #, etc). 100 characters max. Optional.
* @param city City name. 50 characters max.
* @param state 2-letter code for US states, and the equivalent for other countries. 100 characters max. Required in certain countries.
* @param postalCode ZIP code or equivalent is usually required for countries that have them. 20 characters max. Required in certain countries.
* @param countryCode 2-letter country code. 2 characters max.
*/
constructor(recipientName: string, line1: string, line2: string, city: string, state: string, postalCode: string, countryCode: string);
/**
* Name of the recipient at this address. 50 characters max.
*/
recipientName: string;
/**
* Line 1 of the address (e.g., Number, street, etc). 100 characters max.
*/
line1: string;
/**
* Line 2 of the address (e.g., Suite, apt #, etc). 100 characters max. Optional.
*/
line2: string;
/**
* City name. 50 characters max.
*/
city: string;
/**
* 2-letter code for US states, and the equivalent for other countries. 100 characters max. Required in certain countries.
*/
state: string;
/**
* ZIP code or equivalent is usually required for countries that have them. 20 characters max. Required in certain countries.
*/
postalCode: string;
/**
* 2-letter country code. 2 characters max.
*/
countryCode: string;
}
declare class PayPalConfiguration {
/**
* @param options A set of options to use. Any options not specified will assume default values.
*/
constructor(options?: PayPalConfigurationOptions);
/**
* Will be overridden by email used in most recent PayPal login.
*/
defaultUserEmail: string;
/**
* Will be overridden by phone country code used in most recent PayPal login
*/
defaultUserPhoneCountryCode: string;
/**
* Will be overridden by phone number used in most recent PayPal login.
* @note If you set defaultUserPhoneNumber, be sure to also set defaultUserPhoneCountryCode.
*/
defaultUserPhoneNumber: string;
/**
* Your company name, as it should be displayed to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantName: string;
/**
* URL of your company's privacy policy, which will be offered to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantPrivacyPolicyURL: string;
/**
* URL of your company's user agreement, which will be offered to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantUserAgreementURL: string;
/**
* If set to false, the SDK will only support paying with PayPal, not with credit cards.
* This applies only to single payments (via PayPalPaymentViewController).
* Future payments (via PayPalFuturePaymentViewController) always use PayPal.
* Defaults to true.
*/
acceptCreditCards: boolean;
/**
* For single payments, options for the shipping address.
*
* - 0 - PayPalShippingAddressOptionNone: no shipping address applies.
*
* - 1 - PayPalShippingAddressOptionProvided: shipping address will be provided by your app,
* in the shippingAddress property of PayPalPayment.
*
* - 2 - PayPalShippingAddressOptionPayPal: user will choose from shipping addresses on file
* for their PayPal account.
*
* - 3 - PayPalShippingAddressOptionBoth: user will choose from the shipping address provided by your app,
* in the shippingAddress property of PayPalPayment, plus the shipping addresses on file for the user's PayPal account.
*
* Defaults to 0 (PayPalShippingAddressOptionNone).
*/
payPalShippingAddressOption: number;
/**
* If set to true, then if the user pays via their PayPal account,
* the SDK will remember the user's PayPal username or phone number;
* if the user pays via their credit card, then the SDK will remember
* the PayPal Vault token representing the user's credit card.
*
* If set to false, then any previously-remembered username, phone number, or
* credit card token will be erased, and subsequent payment information will
* not be remembered.
*
* Defaults to true.
*/
rememberUser: boolean;
/**
* If not set, or if set to nil, defaults to the device's current language setting.
*
* Can be specified as a language code ("en", "fr", "zh-Hans", etc.) or as a locale ("en_AU", "fr_FR", "zh-Hant_HK", etc.).
* If the library does not contain localized strings for a specified locale, then will fall back to the language. E.g., "es_CO" -> "es".
* If the library does not contain localized strings for a specified language, then will fall back to American English.
*
* If you specify only a language code, and that code matches the device's currently preferred language,
* then the library will attempt to use the device's current region as well.
* E.g., specifying "en" on a device set to "English" and "United Kingdom" will result in "en_GB".
*
* These localizations are currently included:
* da,de,en,en_AU,en_GB,en_SV,es,es_MX,fr,he,it,ja,ko,nb,nl,pl,pt,pt_BR,ru,sv,tr,zh-Hans,zh-Hant_HK,zh-Hant_TW.
*/
languageOrLocale: string;
/**
* Normally, the SDK blurs the screen when the app is backgrounded,
* to obscure credit card or PayPal account details in the iOS-saved screenshot.
* If your app already does its own blurring upon backgrounding, you might choose to disable this.
* Defaults to false.
*/
disableBlurWhenBackgrounding: boolean;
/**
* If you will present the SDK's view controller within a popover, then set this property to true.
* Defaults to false. (iOS only)
*/
presentingInPopover: boolean;
/**
* Sandbox credentials can be difficult to type on a mobile device. Setting this flag to true will
* cause the sandboxUserPassword and sandboxUserPin to always be pre-populated into login fields.
*
* This setting will have no effect if the operation mode is production.
* Defaults to false.
*/
forceDefaultsInSandbox: boolean;
/**
* Password to use for sandbox if 'forceDefaultsInSandbox' is set.
*/
sandboxUserPassword: string;
/**
* PIN to use for sandbox if 'forceDefaultsInSandbox' is set.
*/
sandboxUserPin: string;
}
/**
* Describes the options that can be passed into the PayPalConfiguration class constructor.
*/
interface PayPalConfigurationOptions {
/**
* Will be overridden by email used in most recent PayPal login.
*/
defaultUserEmail?: string;
/**
* Will be overridden by phone country code used in most recent PayPal login
*/
defaultUserPhoneCountryCode?: string;
/**
* Will be overridden by phone number used in most recent PayPal login.
* @note If you set defaultUserPhoneNumber, be sure to also set defaultUserPhoneCountryCode.
*/
defaultUserPhoneNumber?: string;
/**
* Your company name, as it should be displayed to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantName?: string;
/**
* URL of your company's privacy policy, which will be offered to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantPrivacyPolicyURL?: string;
/**
* URL of your company's user agreement, which will be offered to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantUserAgreementURL?: string;
/**
* If set to false, the SDK will only support paying with PayPal, not with credit cards.
* This applies only to single payments (via PayPalPaymentViewController).
* Future payments (via PayPalFuturePaymentViewController) always use PayPal.
* Defaults to true.
*/
acceptCreditCards?: boolean;
/**
* For single payments, options for the shipping address.
*
* - 0 - PayPalShippingAddressOptionNone?: no shipping address applies.
*
* - 1 - PayPalShippingAddressOptionProvided?: shipping address will be provided by your app,
* in the shippingAddress property of PayPalPayment.
*
* - 2 - PayPalShippingAddressOptionPayPal?: user will choose from shipping addresses on file
* for their PayPal account.
*
* - 3 - PayPalShippingAddressOptionBoth?: user will choose from the shipping address provided by your app,
* in the shippingAddress property of PayPalPayment, plus the shipping addresses on file for the user's PayPal account.
*
* Defaults to 0 (PayPalShippingAddressOptionNone).
*/
payPalShippingAddressOption?: number;
/**
* If set to true, then if the user pays via their PayPal account,
* the SDK will remember the user's PayPal username or phone number;
* if the user pays via their credit card, then the SDK will remember
* the PayPal Vault token representing the user's credit card.
*
* If set to false, then any previously-remembered username, phone number, or
* credit card token will be erased, and subsequent payment information will
* not be remembered.
*
* Defaults to true.
*/
rememberUser?: boolean;
/**
* If not set, or if set to nil, defaults to the device's current language setting.
*
* Can be specified as a language code ("en", "fr", "zh-Hans", etc.) or as a locale ("en_AU", "fr_FR", "zh-Hant_HK", etc.).
* If the library does not contain localized strings for a specified locale, then will fall back to the language. E.g., "es_CO" -> "es".
* If the library does not contain localized strings for a specified language, then will fall back to American English.
*
* If you specify only a language code, and that code matches the device's currently preferred language,
* then the library will attempt to use the device's current region as well.
* E.g., specifying "en" on a device set to "English" and "United Kingdom" will result in "en_GB".
*
* These localizations are currently included:
* da,de,en,en_AU,en_GB,en_SV,es,es_MX,fr,he,it,ja,ko,nb,nl,pl,pt,pt_BR,ru,sv,tr,zh-Hans,zh-Hant_HK,zh-Hant_TW.
*/
languageOrLocale?: string;
/**
* Normally, the SDK blurs the screen when the app is backgrounded,
* to obscure credit card or PayPal account details in the iOS-saved screenshot.
* If your app already does its own blurring upon backgrounding, you might choose to disable this.
* Defaults to false.
*/
disableBlurWhenBackgrounding?: boolean;
/**
* If you will present the SDK's view controller within a popover, then set this property to true.
* Defaults to false. (iOS only)
*/
presentingInPopover?: boolean;
/**
* Sandbox credentials can be difficult to type on a mobile device. Setting this flag to true will
* cause the sandboxUserPassword and sandboxUserPin to always be pre-populated into login fields.
*
* This setting will have no effect if the operation mode is production.
* Defaults to false.
*/
forceDefaultsInSandbox?: boolean;
/**
* Password to use for sandbox if 'forceDefaultsInSandbox' is set.
*/
sandboxUserPassword?: string;
/**
* PIN to use for sandbox if 'forceDefaultsInSandbox' is set.
*/
sandboxUserPin?: string;
}
//#endregion
//#region cdv-plugin-paypal-mobile-sdk.js
declare module PayPalCordovaPlugin {
export interface PayPalClientIds {
PayPalEnvironmentProduction: string;
PayPalEnvironmentSandbox: string;
}
/**
* Represents the portion of an object that is common to all responses.
*/
export interface BaseResult {
client: Client;
response_type: string;
}
/**
* Represents the client portion of the response.
*/
export interface Client {
paypal_sdk_version: string;
environment: string;
platform: string;
product_name: string;
}
/**
* Represents the response for a successful callback from renderSinglePaymentUI().
*/
export interface SinglePaymentResult extends BaseResult {
response: {
intent: string;
id: string;
state: string;
authorization_id: string;
create_time: string;
};
}
/**
* Represents the response for a successful callback from renderFuturePaymentUI().
*/
export interface FuturePaymentResult extends BaseResult {
response: {
code: string;
};
}
export interface PayPalMobileStatic {
/**
* Retrieve the version of the PayPal iOS SDK library. Useful when contacting support.
*
* @param completionCallback a callback function accepting a string
*/
version(completionCallback: (result: string) => void): void;
/**
* You MUST call this method to initialize the PayPal Mobile SDK.
*
* The PayPal Mobile SDK can operate in different environments to facilitate development and testing.
*
* @param clientIdsForEnvironments set of client ids for environments
* Example: var clientIdsForEnvironments = {
* PayPalEnvironmentProduction : @"my-client-id-for-Production",
* PayPalEnvironmentSandbox : @"my-client-id-for-Sandbox"
* }
* @param completionCallback a callback function on success
*/
init(clientIdsForEnvironments: PayPalCordovaPlugin.PayPalClientIds, completionCallback: () => void): void;
/**
* You must preconnect to PayPal to prepare the device for processing payments.
* This improves the user experience, by making the presentation of the
* UI faster. The preconnect is valid for a limited time, so
* the recommended time to preconnect is on page load.
*
* @param environment available options are "PayPalEnvironmentNoNetwork", "PayPalEnvironmentProduction" and "PayPalEnvironmentSandbox"
* @param configuration PayPalConfiguration object, for Future Payments merchantName, merchantPrivacyPolicyURL
* and merchantUserAgreementURL must be set be set
* @param completionCallback a callback function on success
*/
prepareToRender(environment: string, configuration: PayPalConfiguration, completionCallback: () => void): void;
/**
* Start PayPal UI to collect payment from the user.
* See https://developer.paypal.com/webapps/developer/docs/integration/mobile/ios-integration-guide/
* for more documentation of the params.
*
* @param payment PayPalPayment object
* @param completionCallback a callback function accepting a js object, called when the user has completed payment
* @param cancelCallback a callback function accepting a reason string, called when the user cancels the payment
*/
renderSinglePaymentUI(payment: PayPalPayment, completionCallback: (result: PayPalCordovaPlugin.SinglePaymentResult) => void, cancelCallback: (cancelReason: string) => void): void;
/**
* @deprecated
* Once a user has consented to future payments, when the user subsequently initiates a PayPal payment
* from their device to be completed by your server, PayPal uses a Correlation ID to verify that the
* payment is originating from a valid, user-consented device+application.
* This helps reduce fraud and decrease declines.
* This method MUST be called prior to initiating a pre-consented payment (a "future payment") from a mobile device.
* Pass the result to your server, to include in the payment request sent to PayPal.
* Do not otherwise cache or store this value.
*
* @param environment available options are "PayPalEnvironmentNoNetwork", "PayPalEnvironmentProduction" and "PayPalEnvironmentSandbox"
* @param callback applicationCorrelationID Your server will send this to PayPal in a 'Paypal-Application-Correlation-Id' header.
*/
applicationCorrelationIDForEnvironment(environment: string, completionCallback: (applicationCorrelationId: string) => void): void;
/**
* Once a user has consented to future payments, when the user subsequently initiates a PayPal payment
* from their device to be completed by your server, PayPal uses a Correlation ID to verify that the
* payment is originating from a valid, user-consented device+application.
* This helps reduce fraud and decrease declines.
* This method MUST be called prior to initiating a pre-consented payment (a "future payment") from a mobile device.
* Pass the result to your server, to include in the payment request sent to PayPal.
* Do not otherwise cache or store this value.
*
* @param callback clientMetadataID Your server will send this to PayPal in a 'PayPal-Client-Metadata-Id' header.
*/
clientMetadataID(completionCallback: (clientMetadataId: string) => void): void;
/**
* Please Read Docs on Future Payments at https://github.com/paypal/PayPal-iOS-SDK#future-payments
*
* @param completionCallback a callback function accepting a js object with future payment authorization
* @param cancelCallback a callback function accepting a reason string, called when the user canceled without agreement
*/
renderFuturePaymentUI(completionCallback: (result: PayPalCordovaPlugin.FuturePaymentResult) => void, cancelCallback: (cancelReason: string) => void): void;
/**
* Please Read Docs on Profile Sharing at https://github.com/paypal/PayPal-iOS-SDK#profile-sharing
*
* @param scopes scopes Set of requested scope-values. Accepted scopes are: openid, profile, address, email, phone, futurepayments and paypalattributes
* See https://developer.paypal.com/docs/integration/direct/identity/attributes/ for more details
* @param completionCallback a callback function accepting a js object with future payment authorization
* @param cancelCallback a callback function accepting a reason string, called when the user canceled without agreement
*/
renderProfileSharingUI(scopes: string[], completionCallback: (result: any) => void, cancelCallback: (cancelReason: string) => void): void;
}
}
declare var PayPalMobile: PayPalCordovaPlugin.PayPalMobileStatic;
//#endregion
+336
View File
@@ -0,0 +1,336 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/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)
> El repositorio de definiciones de TypeScript de alta calidad.
Vea también el sitio web [definitelytyped.org](http://definitelytyped.org), aunque la información en este README está más actualizada.
## ¿Qué son los `declaration files`?
Vea el [Manual de TypeScript](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
## ¿Cómo los obtengo?
### npm
Este es el método preferido. Solo está disponible para usuarios TypeScript 2.0+. Por ejemplo:
```sh
npm install --save-dev @types/node
```
Los types deberían ser incluidos automaticamente por el compilador.
Vea más en el [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html).
Para un paquete NPM "foo", Estos `typings` estarán en "@types/foo".
Si no puedes encontrar tu paquete, búscalo en [TypeSearch](https://microsoft.github.io/TypeSearch/).
Si aún no puedes encontrarlo, comprueba si el paquete ya [incluye](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) los typings.
Esto es provisto usualmente en el campo `"types"` o `"typings"` en el `package.json`,
o solo busca por cualquier archivo ".d.ts" en el paquete e incluyelo manualmente con un `/// <reference path="" />`.
### Otros métodos
Estos pueden ser utilizados por TypeScript 1.0.
* [Typings](https://github.com/typings/typings)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use las alternativas preferidas, la publicación DT type de nuget ha sido desactivada)
* Descarguelo manualmente desde la `master` branch de este repositorio
Tal vez debas añadir manualmente las [referencias](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
## ¿Cómo puedo contribuir?
¡DefinitelyTyped solo trabaja gracias a contribuidores como tú!
### Prueba
Antes de compartir tu mejora con el mundo, úselo usted mismo.
#### Prueba editando un paquete existente
Para agregar nuevas funciones puedes usar el [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html).
También puedes editar directamente los types en `node_modules/@types/foo/index.d.ts`, o copiarlos de ahí y seguir los pasos explicados a continuación.
#### Prueba un nuevo paquete
Añade a tu `tsconfig.json`:
```json
"baseUrl": "types",
"typeRoots": ["types"],
```
(También puedes usar `src/types`.)
Crea un `types/foo/index.d.ts` que contenga declaraciones del módulo "foo".
Ahora deberías poder importar desde `"foo"` a tu código y te enviara a un nuevo tipo de definición.
Entonces compila *y* ejecuta el código para asegurarte que el tipo de definición en realidad corresponde a lo que suceda en el momento de la ejecución.
Una vez que hayas probado tus definiciones con el código real, haz un [PR](#make-a-pull-request)
luego sigue las instrucciones para [editar un paquete existente](#edit-an-existing-package) o
[crear un nuevo paquete](#create-a-new-package).
### Haz un pull request
Una vez que hayas probado tu paquete, podrás compartirlo en DefinitelyTyped.
Primero, haz un [fork](https://guides.github.com/activities/forking/) en este repositorio, instala [node](https://nodejs.org/), y luego ejecuta la `npm install`.
#### Editar un paquete existente
* `cd types/my-package-to-edit`
* Haz cambios. Recuerda editar las pruebas.
Si realiza cambios importantes, no olvide [actualizar una versión principal](#quiero-actualizar-un-paquete-a-una-nueva-versión-principal).
* También puede que quieras añadirte la sección "Definitions by" en el encabezado del paquete.
- Esto hará que seas notificado (a través de tu nombre de usuario en GitHub) cada vez que alguien haga un pull request o issue sobre el paquete.
- Haz esto añadiendo tu nombre al final de la línea, así como en `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
- O si hay más personas, puede ser multiline
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* Si hay un `tslint.json`, ejecuta `npm run lint package-name`. De lo contrario, ejecuta `tsc` en el directorio del paquete.
Cuando hagas un PR para editar un paquete existente, `dt-bot` deberá @-mencionar a los autores previos.
Si no lo hace, puedes hacerlo en el comentario asociado con el PR.
#### Crear un nuevo paquete
Si eres el autor de la librería, o puedes hacer un pull request a la biblioteca, [bundle types](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) en vez de publicarlo en DefinitelyTyped.
Si estás agregando typings para un paquete NPM, crea un directorio con el mismo nombre.
Si el paquete al que le estás agregando typings no es para NPM, asegurate de que el nombre que escojas no genere problemas con el nombre del paquete en NPM.
(Puedes usar `npm info foo` para verificar la existencia del paquete `foo`.)
Tu paquete debería tener esta estructura:
| Archivo | Propósito |
| --- | --- |
| index.d.ts | Este contiene los typings del paquete. |
| foo-tests.ts | Este contiene una muestra del código con el que se realiza la prueba de escritura. Este código *no* es ejecutable, pero sí es type-checked. |
| tsconfig.json | Este permite ejecutar `tsc` dentro del paquete. |
| tslint.json | Permite linting. |
Generalas ejecutando `npm install -g dts-gen` y `dts-gen --dt --name my-package-name --template module`.
Ve todas las opciones en [dts-gen](https://github.com/Microsoft/dts-gen).
También puedes configurar el `tsconfig.json` para añadir nuevos archivos, para agregar un `"target": "es6"` (necesitado por las funciones asíncronas), para agregar a la `"lib"`, o para agregar la opción de compilación `"jsx"`.
Los miembros de DefinitelyTyped frecuentemente monitorean nuevos PRs, pero ten en mente que la cantidad de PRs podrian ralentizar el proceso.
Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).
#### Errores comunes
* Primero, sigue el consejo del [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
* Formatear: Ya sea utilizar todo en tabs, o siempre utiliza 4 espacios.
* `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una funcion no escribe a sus parámetros.
* `interface Foo { new(): Foo; }`:
Este define el tipo de objeto que esten nuevos. Probablemente quieras `declare class Foo { constructor(); }`.
* `const Class: { new(): IClass; }`:
Prefiere usar una declaración de clase `class Class { constructor(); }` En vez de una nueva constante.
* `getMeAT<T>(): T`:
Si un tipo de parámetro no aparece en los tipos de ningún parámetro, no tienes una función genérica, solo tienes un afirmación del tipo disfrazado.
Prefiera utilizar una afirmación de tipo real, p.ej. `getMeAT() as number`.
Un ejemplo donde un tipo de parámetro es aceptable: `function id<T>(value: T): T;`.
Un ejemplo donde no es aceptable: `function parseJson<T>(json: string): T;`.
Una excepción: `new Map<string, number>()` está bien.
* Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más especifico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`.
* `var foo: string | any`:
Cuando es usado `any` en un tipo de unión, el tipo resultante todavía es `any`. Así que mientras la porción `string` de este tipo de anotación puede _verse_ útil, de hecho, no ofrece ningún typechecking adicional más que un simple `any`.
Dependiendo de la intención, una alternativa aceptable puede ser `any`, `string`, o `string | object`.
#### Remover un paquete
Cuando un paquete [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) sus propios tipos, estos tipos deberán ser removidos de DefinitelyTyped para evitar que generen confusión.
Se puede remover ejecutando `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`.
- `typingsPackageName`: Este es el nombre del directorio que tienes que eliminar.
- `asOfVersion`: Un stub será publicado a `@types/foo` con esta versión. Debería ser más grande que cualquier versión publicada actualmente.
- `sourceRepoURL`: Esto debería señalar el repositorio que contiene los typings.
- `libraryName`: Un nombre descriptivo de la librería, p.ej. "Angular 2" en vez de "angular2". (Si es omitido, será idéntico a "typingsPackageName".)
Cualquier otro paquete en DefinitelyTyped que referencie el paquete eliminado deberá ser actualizado para referenciar los tipos bundled. para hacer esto, añade `package.json` con `"dependencies": { "foo": "x.y.z" }`.
Si un paquete nunca estuvo en DefinitelyTyped, no será necesario añadirlo a `notNeededPackages.json`.
#### Lint
Para realizar el lint a un paquete, solo añade `tslint.json` al paquete que contiene `{ "extends": "dtslint/dt.json" }`. Todos los paquetes nuevos deberán pasar por el proceso de linted.
Si el `tslint.json` deshabilita algunas reglas esto se debe a que aún no se ha acomodado. Por ejemplo:
```js
{
"extends": "dtslint/dt.json",
"rules": {
// This package uses the Function type, and it will take effort to fix.
"ban-types": false
}
}
```
(Para indicar que la regla lint realmente no es utilizada, usa `// tslint:disable rule-name` o mejor, `//tslint:disable-next-line rule-name`.)
Para afirmar que una expresión es de un tipo dado, utilice `$ExpectType`. Para afirmar que una expresión causa un error de compilación, utilice `$ExpectError`.
```js
// $ExpectType void
f(1);
// $ExpectError
f("one");
```
Para más detalles, vea el [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.
Realiza una prueba ejecutando `npm run lint package-name` donde `package-name` es el nombre de tu paquete.
Este script utiliza [dtslint](https://github.com/Microsoft/dtslint).
## FAQ
#### ¿Cuál es exactamente la relación entre este repositorio y los paquetes de `@types` en NPM?
La `master` branch es automaticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher).
#### He enviado un pull request. ¿Cuánto tardará en ser merged?
Esto depende, pero la mayoría de los pull requests serán merged en alrededor de una semana. PRs que hayan sido aprovados por un autor listado en el encabezado de las definiciones usualmente son merged más rápidamente; PRs para nuevas definiciones tomarán más tiempo ya que requieren más revisiones de los mantenedores. Cada PR es revisado por un miembro de TypeScript o DefinitelyTyped antes de ser merged, por favor se paciente debido a que factores humanos pueden causar retrasos. Revisa el [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) para ver el progreso mientras los mantenedores trabajan on los PRs abiertos.
#### Mi PR ha sido merged; ¿cuándo será actualizado el paquete de `@types` NPM?
Los paquetes NPM deberán ser actualizados en unas cuantas horas. Si ha pasado más de 24 horas, menciona a @RyanCavanaugh y/o a @andy-ms en el PR para investigar.
#### Estoy escribiendo una definición que depende de otra definición. Debería utilizar `<reference types="" />` o una import?
Si el modulo al cual te estás refiriendo es un módulo externo (utiliza `export`), utilice una import.
Si el módulo al cual te refieres es un módulo ambiente (utiliza `declare module`, o simplemente declara las globales), utilice `<reference types="" />`.
#### He notado que algunos paquetes aquí tienen `package.json`.
Normalmente no lo necesitaras. Cuando publicas un paquete normalmente nosotros automáticamente crearemos un `package.json` para eso.
Un `package.json` puede ser incluido por el bien de especificar dependencias. Aquí tienen un [ejemplo](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
No aceptamos otros campos, tales como `"description"`, para que sean definidos manualmente.
Además, si necesitas referencia a una versión anterior de typings, debes hacerlo añadiendo `"dependencies": { "@types/foo": "x.y.z" }` al package.json.
#### Algunos paquetes no tienen `tslint.json`, y algunos `tsconfig.json` no contienen `"noImplicitAny": true`, `"noImplicitThis": true`, o `"strictNullChecks": true`.
Entonces están equivocados. Puedes ayudar enviando un pull request para arreglarlos.
#### Puedo pedir una definition?
Aquí están las [definiciones solicitadas actualmente](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest).
#### ¿Qué pasa con las type definitions para el DOM?
Si las types son parte de los estándares web, estas deberán ser contribuidas a [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) para que se hagan parte de la librería predeterminada `lib.dom.d.ts`.
#### Un paquete utiliza `export =`, pero prefiero utilizar las import predeterminadas. ¿Puedo cambiar `export =` por `export default`?
Si la import predeterminada trabaja en tu ambiente, considera hacer un cambio en la opción de compilación [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) opción compilar.
No cambies la type definition si es preciso.
Para un paquete NPM, `export =` es exacto si `node -p 'require("foo")'` es la export, y `export default` es exacto si `node -p 'require("foo").default'` es el export.
#### Quiero usar las características de TypeScript 2.1 o superior.
Entonces deberás añadir un comentario a la última línea de la definición en el encabezado (despues de `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
#### Quiero añadir un DOM API que no está presente en TypeScript por defecto.
Esto puede pertenecer a [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). Vea las guías allí.
Si el estándar sigue siendo un borrador, este pertenece aquí.
Utilice un nombre que empiece con `dom-` e incluya un link al estándar como el "Project" con el link en el encabezado.
Cuando ya no sea un borrador, lo podremos eliminar desde DefinitelyType y hacer obsoleto el paquete `@types` asociado.
#### Quiero actualizar un paquete a una nueva versión principal
Si planeas continuar actualizando la versión anterior del paquete, puedes crear una subcarpeta con la versión actual p.ej. `v2`, y copia los archivos existentes. Si es así, necesitarás:
1. Actualiza las rutas relativas en `tsconfig.json` al igual que `tslint.json`.
2. Añadir reglas de mapeo de rutas para asegurart de que la prueba se está ejecutando contra la versión prevista.
Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) se ve así:
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": [ "history/v2" ]
},
},
"files": [
"index.d.ts",
"history-tests.ts"
]
}
```
Si hay otros paquetes en DefinitelyTyped que son incompatibles con la nueva versión, necesitaras mapear las rutas a la versión anterior. También deberá hacer esto para los paquetes que dependen de paquetes que dependen de una version anterior.
Por ejemplo, `react-router` depende de `history@2`, así que [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) tiene una ruta mapeada a "history": `[ "history/v2" ]`;
transitivo así mismo, `react-router-bootstrap` (que depende de `react-router`) también añade una ruta mapeada en su [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
Además, `/// <reference types=".." />` no trabajara con rutas mapeadas, así que las dependencias deberán utilizar `import`.
#### ¿Cómo escribo definitions para paquetes que pueden ser usados globalmente y como un módulo?
El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), ademas [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada practicamente en la [definición para big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a travéz de una etiqueta script en una página web, o importada via require o imports estilo ES6.
Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas un propiedad `files` en tu archivo tsconfig.json, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de big.js.
Por favor tenga en cuenta que no es necesario para ejercer plenamente la definición en cada archivo de prueba - Es suficiente con probar solo los elementos globalmente accesibles en la prueba de archivos globales y ejercer la definición en el módulo del archivo de prueba, o viceversa.
#### ¿Qué pasa con paquetes scoped?
Types para un paquete scoped `@foo/bar` deberán ir en `types/foo__bar`. tenga en cuenta el doble guion bajo.
Cuando `dts-gen` es utilizado como scaffold en un paquete scoped, las propiedades `paths` deberán ser adaptadas manualmente en el paquete generado
`tsconfig.json` para referenciar correctamente el paquete scoped:
```json
{
"paths":{
"@foo/bar": ["foo__bar"]
}
}
```
#### El historial de archivos en GitHub parece incompleto.
GitHub no le hace [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) historial de archivos para archivos renombrados. Utilice [`git log --follow`](https://www.git-scm.com/docs/git-log) en su lugar.
#### Debería añadir un namespace que no exporte un módulo que utilice que utilice imports estilo ES6?
Algunos paquetes, como [chai-http](https://github.com/chaijs/chai-http), exportan una función.
importar este módulo con un ES6 style import de forma `import * as foo from "foo";` conduce al error:
> error ts2497: El módulo 'foo' se resuelve en una entidad que no es un módulo y no se puede importar mediante esta construcción
Este error puede ser suprimido al unir la declaración de una función con un namespace vacío del mismo nombre pero esta práctica no es recomendable.
Esto es un citado común [Respuestas de Stack Overflow](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) con respecto a este asunto.
Es más apropiado importar este módulo utilizando la sintaxis `import foo = require("foo");`, o utilizando una importación predeterminada como `import foo from "foo";` si usas la bandera `--allowSyntheticDefaultImports` si la ejecución de tu módulo soporta un esquema de interoperación para módulos no ECMAScript como tal.
## Licencia
Este proyecto es licenciado bajo la licencia MIT.
Los derechos de autor de cada archivo de definición son respectivos de cada contribuidor listado al comienzo de cada archivo de definición.
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)
+338
View File
@@ -0,0 +1,338 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
[![깃터(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)
> 이 저장소는 고품질의 타입스크립트(TypeScript) 자료형 정의(Type definition)를 위한 저장소입니다.
이 문서가 가장 최신 내용을 담고있긴 하지만, [공식 사이트(definitelytyped.org)](http://definitelytyped.org)도 확인해보시면 좋습니다.
## 선언 파일(Declaration file)이 뭔가요?
[타입스크립트 안내서(TypeScript handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)를 읽어보세요.
## 선언 파일(Declaration file)을 어떻게 받을 수 있나요??
### npm 사용하기
아래 방법은 타입스크립트(TypeScript) 2.0+ 이상의 버전을 사용하는 사람들만 사용할 수 있는 방법이기는 합니다만, 이 방법을 사용하기를 장려합니다.
```sh
npm install --save-dev @types/node
```
`node` 를 위한 자료형(Typing)이 컴파일 과정에 자동으로 포함될 겁니다.
더 자세한 내용은 [안내서(Handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html)에서 확인해보실 수 있습니다.
NPM 의 "foo" 패키지에 대응되는 자료형 패키지는 "@types/foo" 입니다.
원하시는 패키지를 찾을 수 없는 경우, [타입서치(TypeSearch)](https://microsoft.github.io/TypeSearch/) 사이트에서 한 번 찾아보세요.
타입서치(TypeSearch)에서도 찾을 수 없는 경우, 찾고 있는 패키지가 자료형(Typing)을
[함께 제공](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)하고 있지는 않은지 확인해보세요.
패키지에 포함된 자료형(Typing)은 주로 `package.json` 파일의 `"types"``"typings"` 필드(Field)를 통해 제공되지만,
`/// <reference path="" />` 같은 주석을 사용하여 패키지 안의 ".d.ts" 파일들을 직접 가져와야 할 수도 있습니다.
### 그 외의 방법들
타입스크립트(TypeScript) 1.0 버전에서 사용할 수 있는 방법은 다음과 같습니다.
* [Typings](https://github.com/typings/typings) 을 사용하기
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped) 을 사용하기~~ (다른 방법을 사용해주세요. NuGet 은 더 이상 DT 자료형(Typing)을 제공하지 않습니다.)
* 이 저장소의 `master` 브랜치를 직접 내려받기
위 방법을 사용할 경우 수동으로 [참조(Reference)](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html)를 추가해주어야 할 수 있습니다.
## 어떻게 이곳에 기여할 수 있나요?
여러분과 같은 많은 기여자들의 도움 덕분에 이 저장소가 돌아가고 있습니다. 감사합니다.
### 테스트
여러분이 만든 자료형 선언(Type declation)을 세상에 공유하기에 앞서, 여러분이 스스로 여러분의 자료형 선언(Type declation)을 사용하고 확인해주세요.
#### 이미 존재하는 자료형 패키지를 임시로 수정하기
이미 존재하는 패키지의 자료형 선언(Type declaration)에 새로운 기능을 추가하려면 [모듈 증강(module augmentation)](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)를 사용할 수 있습니다.
물론 `node_modules/@types/foo/index.d.ts` 를 직접 수정하실 수도 있으며, 이 파일을 복사한 다음 아래의 과정을 따라하실 수도 있습니다.
#### 새 자료형 패키지를 임시로 추가하기
사용하고 계신 `tsconfig.json` 에 다음 내용을 추가해주세요.
```json
"baseUrl": "types",
"typeRoots": ["types"],
```
(`types` 대신 `src/types` 을 사용하실 수도 있습니다.)
그리고 "foo" 모듈(Module)에 대한 선언(Declaration)을 포함하는 `types/foo/index.d.ts` 파일을 만들어주세요.
이제 코드 안에서 여러분의 새 자료형 선언(Type declaration)을 사용하는 `"foo"` 모듈(Module)을 임포트(Import)하실 수 있을 겁니다.
코드를 컴파일하고 실행시켜서 여러분의 자료형(Typing)이 실행 중에 실제로 벌어지는 일과 잘 맞아떨어지는지 확인해주세요.
실제 코드를 통한 확인이 끝나면, [풀 리퀘스트(Pull request)](#풀-리퀘스트pull-request-만들기)를 만들어주세요.
[이미 존재하는 패키지를 수정](#이미-존재하는-패키지를-수정하기)하거나 [새 패키지를 만들기](#새-패키지-만들기)위한 과정들을 따라하시면 됩니다.
### 풀 리퀘스트(Pull request) 만들기
여러분의 자료형 선언이 잘 작동하는지 확인하셨다면, DefinitelyTyped 에 공유해주세요.
우선, 이 저장소를 [포크(fork)](https://guides.github.com/activities/forking/)해 주시고, [node](https://nodejs.org/) 를 설치하신 뒤, `npm install` 명령을 실행해주세요.
#### 이미 존재하는 패키지를 수정하기
* `cd types/my-package-to-edit` 명령을 실행합니다.
* 자료형(Typing) 파일들을 수정합니다. 테스트를 추가하는 것도 잊지마세요!
만약 브레이킹 체인지(Breaking change)를 만드셨다면, [메이저 버전(major version)](#i-want-to-update-a-package-to-a-new-major-version)을 꼭 올려주세요.
* 패키지 머릿주석의 "Definitions by" 부분에 여러분의 이름을 추가하실 수도 있습니다.
- 이름을 추가하시면 다른 사람들이 그 패키지에 대한 풀 리퀘스트(Pull request)나 이슈(Issue)를 만들 때 여러분에게 알람이 갑니다.
- `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>` 와 같이 여러분의 이름을 줄의 맨 마지막에 추가할 수 있습니다.
- 사람이 너무 많을 경우엔, 다음과 같이 여러 줄로 쓰실 수도 있습니다.
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* `tslint.json` 파일이 있는 경우에는, `npm run lint package-name` 명령을 실행시키고 결과를 확인해주세요. 그렇지 않은 경우에는, 해당 패키지가 있는 디렉토리 안에서 `tsc` 명령을 실행시키고 결과를 확인해주세요.
이미 존재하는 패키지에 대한 풀 리퀘스트(Pull request)를 만들었을 경우에는, `dt-bot` 이 이전 저자들을 자동으로 호출하는지 확인해주세요.
그렇지 않은 경우에는, 여러분이 직접 풀 리퀘스트(Pull request)와 관계있는 사람들을 호출할 수도 있습니다.
#### 새 패키지를 만들기
만약 라이브러리를 만드는 중이고 라이브러리가 타입스크립트(TypeScript)로 쓰여있다면, DefinitelyTyped 에 선언(Declaration)을 올리는 대신 패키지에 [자동생성된 선언(Declaration) 파일을 포함](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)시킬 수 있습니다.
NPM 패키지를 위한 자료형(Typing) 패키지를 만드시려면, 패키지의 이름과 같은 이름의 디렉토리를 만들어주세요.
NPM 에 올라가 있지 않은 패키지를 위한 자료형(Typing) 패키지를 만드시려면, 그 패키지가 NPM 에 올라와 있는 패키지와 이름이 겹치지 않는지 확인해주세요.
(`npm info foo` 명령어를 사용하여 `foo` 패키지가 NPM 에 있는지 확인할 수 있습니다.)
새 자료형 패키지는 다음과 같은 구조로 구성되어있어야만 합니다.
| 파일 이름 | 용도 |
| --- | --- |
| index.d.ts | 패키지를 위한 자료형(Typing)을 포함하는 파일입니다. |
| foo-tests.ts | 자료형(Typing)의 테스트를 위한 파일입니다. 이 파일의 코드는 실행되지는 않지만, 자료형 검사(Type checking)를 통과해야 합니다. |
| tsconfig.json | `tsc` 명령을 돌릴 수 있게 해주는 파일입니다. |
| tslint.json | 린터(Linter)를 사용할 수 있게 해주는 파일입니다. |
이 파일들은, npm ≥ 5.2.0 에서는 `npx dts-gen --dt --name my-package-name --template module` 명령으로,
그 이하 경우에는 `npm install -g dts-gen` 와 `dts-gen --dt --name my-package-name --template module` 명령으로 만들 수 있습니다.
`dts-gen` 의 모든 옵션(Option)을 보고싶으시면 [dts-gen](https://github.com/Microsoft/dts-gen) 저장소를 확인해주세요.
자료형(Typing) 패키지에 새 파일을 추가하거나, `async` 키워드를 사용하기 위해 `"target"` 을 `"es6"` 로 설정하거나, `"lib"` 를 추가하거나, `jsx` 지원을 추가하기 위해서 `tsconfig.json` 파일을 변경해야 할 수도 있습니다.
DefinitelyTyped 의 관리자들이 주기적으로 새로운 풀 리퀘스트(Pull request)들을 확인하기는 하지만,
다른 풀 리퀘스트(Pull request)가 많을 경우 확인이 느려질 수 있다는 걸 알아주세요.
[base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js) 패키지는 좋은 예시 중 하나입니다.
#### 많이 저지르는 실수들
* 우선, [안내서(Handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html)에 나와있는 내용들을 따라주세요.
* 코드에서는 모든 곳에서 탭(Tab)을 사용하거나, 항상 4 개의 띄어쓰기를 사용해주세요.
* `function sum(nums: number[]): number`의 경우, 만약 함수가 인자를 변경하지 않는다면 `ReadonlyArray` 를 사용해주세요.
* `interface Foo { new(): Foo; }`의 경우,
이런 선언은 이 형(Type)을 가진 객체(Object)에 `new` 를 사용할 수 있도록 만듭니다. 많은 경우 여러분은 `declare class Foo { constructor(); }` 를 사용하려는 것일 겁니다.
* `const Class: { new(): IClass; }`의 경우,
`new` 를 사용할 수 있는 상수를 만드는 대신, `class Class { constructor(); }` 와 같이 클래스 선언(Class declaration)을 사용하는 게 더 좋습니다.
* `getMeAT<T>(): T`의 경우,
만일 자료형 매개변수(Type parameter)가 함수의 매개변수에 등장하지 않는다면, 그런 제너릭(Generic) 함수를 사용할 필요가 없습니다.
그 제너릭(Generic) 함수는 단순히 자료형 단언(Type assertion)을 위장시킨 것뿐입니다. 이 경우 `getMeAT() as number` 와 같이 진짜 자료형 단언(Type assertion) 을 사용하는 게 더 좋습니다.
다음은 괜찮은 제너릭(Generic)의 예시입니다. `function id<T>(value: T): T;`.
다음은 문제가 있는 제너릭(Generic)의 예시입니다. `function parseJson<T>(json: string): T;`.
예외적으로, `new Map<string, number>()` 와 같은 경우는 괜찮습니다.
* `Function` 이나 `Object` 와 같은 형(Type)을 사용하는 것은 대부분의 경우 문제를 일으킵니다. 99% 의 경우 더 구체적인 형(Type)을 사용하는게 가능합니다. [함수(Function)](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) 를 위해서는 `(x: number) => number` 와 같은, 객체를 위해서는 `{ x: number, y: number }` 와 같은 형(Type)들을 사용할 수 있습니다. 형(Type)에 대한 정보가 전혀 없을 경우에는, `Object` 형(Type)이 아니라 [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) 형(Type)을 사용해야 합니다. 만일 어떤 형(Type)이 객체라는 사실만 알고 있는 경우, `Object` 나 `{ [key: string]: any }` 가 아니라 [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type) 를 사용해주세요.
* `var foo: string | any`의 경우,
`any` 가 합 자료형(Union type)의 안에서 사용될 경우, 결과 형(Type)은 언제나 `any` 가 됩니다. 따라서 형(Type)의 `string` 부분이 유용해 보인다 하더라도, 사실은 자료형 검사(Type checking)의 측면에서 `any` 와 다른 것이 없습니다.
대신, `any`, `string`, 나 `string | object` 중 하나를 필요에 맞게 골라서 사용해주세요.
#### 패키지 삭제하기
패키지가 스스로의 형(Type)을 [포함](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)하게 되면, DefinitelyTyped 에 있는 자료형(Typing) 패키지를 삭제하는 것이 좋습니다.
`npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]` 명령어를 사용하여 자료형(Typing) 패키지를 삭제할 수 있습니다.
- `typingsPackageName` 는 삭제할 디렉토리의 이름입니다.
- `asOfVersion` 는 새 스텁(Stub) 용 `@types/foo` 를 퍼블리시(Publish)할 버전입니다. 이 버전은 현재 NPM 에 올라간 버전보다 더 높은 버전이어야 합니다.
- `sourceRepoURL` 는 자료형(Typing)을 포함하게 된 저장소의 주소입니다.
- `libraryName` 는 패키지의 이름을 읽기 쉽게 쓴 것입니다. 즉, "angular2" 대신에 "Angular 2" 와 같이 쓰는 것이 좋습니다. (생략했을 경우에는 "typingsPackageName" 와 같은 것으로 취급됩니다.)
DefinitelyTyped 의 다른 패키지들이 삭제된 자료형(Typing) 패키지를 사용하고 있을 경우, 형(Type)을 포함하기 시작한 원래 패키지를 사용하도록 수정해야합니다. 삭제된 자료형(Typing) 패키지를 사용하는 각 DefinitelyTyped 패키지들의 `package.json` 파일에 `"dependencies": { "foo": "x.y.z" }` 를 추가해주시면 됩니다.
DefinitelyTyped 에 한 번도 올라온 적 없는 패키지가 형(Type)을 포함하게 되었다면, `notNeededPackages.json` 파일에 추가할 필요도 없습니다.
#### 린트(Lint)하기
자료형(Typing) 패키지를 린트(Lint)하려면, 패키지 디렉토리에 `{ "extends": "dtslint/dt.json" }` 를 포함하고 있는 `tslint.json` 파일을 추가해주시면 됩니다. 모든 새 패키지는 해당 파일을 가지고 있어야 합니다.
고쳐야 하지만 아직 고쳐지지 않은 린트(Lint) 결과가 있을 때에만 `tslint.json` 에서 린트 규칙(Lint rule)을 사용하지 않도록 설정할 수 있습니다. 예를 들어,
```js
{
"extends": "dtslint/dt.json",
"rules": {
// 이 패키지는 Function 형을 사용하고 있으며, 고치는 게 쉽지 않다.
"ban-types": false
}
}
```
(린트 규칙(Lint rule)이 절대로 적용되서는 안되는 경우에는, `// tslint:disable rule-name` 나 `//tslint:disable-next-line rule-name` 를 사용하는 것이 좋습니다. 후자가 더 나은 방식입니다.)
어떤 표현식(Expression)이 특정한 형(Type)을 가진다고 단언(Assert)하고 싶을 때에는 `$ExpectType` 를 사용하시면 됩니다. 어떤 표현식(Expression)이 컴파일에 실패해야하는 경우에는 `$ExpectError` 를 하시면 됩니다.
```js
// $ExpectType void
f(1);
// $ExpectError
f("one");
```
[dtslint](https://github.com/Microsoft/dtslint#write-tests) 저장소의 README 파일에서 더 자세한 내용을 확인하실 수 있습니다.
이런 테스트들은 `npm run lint package-name` 명령으로 실행해볼 수 있습니다. 이 때, `package-name` 은 테스트하고 싶은 패키지의 이름입니다.
테스트 스크립트는 [dtslint](https://github.com/Microsoft/dtslint) 를 사용하고 있습니다.
## 자주 하는 질문들
#### 이 저장소와 `@types` 패키지들이 대체 무슨 관계가 있는 건가요?
`master` 브랜치(Branch)의 내용들이 [types-publisher](https://github.com/Microsoft/types-publisher) 를 사용해 자동으로 `@types` 퍼블리시(Publish)됩니다.
#### 풀 리퀘스트(Pull request)를 제출했습니다. 이게 합쳐질 때까지 얼마나 걸리나요?
상황에 따라 다르지만, 대부분의 풀 리퀘스트(Pull request)들은 일주일 안에 합쳐집니다. 머릿주석에 있는 저자 중 한명에 의해 승인된 풀 리퀘스트(Pull request)는 보통 더 빨리 합쳐집니다. 새로운 패키지에 대한 풀 리퀘스트(Pull request)는 관리자의 세세한 코드 리뷰를 필요로 하기 때문에 더 오래 걸리는 경우가 많습니다. 각 PR 들은 합쳐지기 전에 TypeScript or DefinitelyTyped 팀 구성원의 코드 리뷰를 받아야 하며, 이는 사람이 하는 일이기 때문에 느려질 수도 있으니 양해를 바랍니다. [풀 리퀘스트 번다운 보드(PR Burndown Board)](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen)에서 열린 풀 리퀘스트에 대한 관리자들의 진행도를 확인하실 수 있습니다.
#### 내 풀 리퀘스트(Pull request)는 합쳐졌습니다. 언제 NPM 에 `@types` 패키지가 갱신되나요?
NPM 의 패키지들은 수시간 안에 갱신될 겁니다. 만약 24 시간이 지나도 갱신되지 않으면, 문제를 파악하기 위해 @RyanCavanaugh 나 @andy-ms 를 풀 리퀘스트(Pull request)에서 호출해주세요.
#### 다른 자료형 정의(Type definition)에 의존하는 자료형 정의(Type definition)을 만들고 있습니다. `<reference types="" />` 와 임포트(import) 중 무엇을 사용해야하나요?
외부 모듈(`export` 를 사용하는 모듈)을 사용할 경우, 임포트(import)를 사용해주세요.
환경과 관련된 모듈(ambient module)(`declare module` 를 쓰거나 전역 변수들을 선언한 모듈)을 사용할 경우, `<reference types="" />` 를 사용해주세요.
#### `package.json` 파일이 가끔 보이던데?
일반적으로는 `package.json` 파일을 사용할 필요가 없습니다. 패키지가 퍼블리시(Publish)될 때 패키지를 위한 `package.json` 파일은 자동으로 생성됩니다.
가끔 보이는 `package.json` 파일은 의존하는 것들을 표시하기 위해 사용됩니다. [예시](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json)를 한 번 보세요.
의존성을 제외한 다른 필드(Field)들, 그러니까 `"description"` 같은 것들은 사용해서는 안됩니다.
옛날 `@types` 패키지를 사용하고 싶으실 경우에도 `"dependencies": { "@types/foo": "x.y.z" }` 와 같은 내용을 `package.json` 파일에 넣으셔야 합니다.
#### 어떤 패키지들에 `tslint.json` 이 없거나, `tsconfig.json` 에 `"noImplicitAny": true`, `"noImplicitThis": true`, 나 `"strictNullChecks": true` 가 없어요.
그럼 그 패키지들이 잘못된 겁니다. 고쳐서 풀 리퀘스트(Pull request)를 제출해주시면 고맙겠습니다.
#### 자료형 정의(Type definition)을 요청할 수 있나요?
이미 요청된 자료형 정의(Type definition)들을 [여기서](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest) 보실 수 있습니다.
#### DOM 을 위한 자료형 정의(Type definitions)는요?
웹 표준(Web standard)과 관련이 있는 자료형(Typing)들은 [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) 저장소에 기여해서 고치실 수 있습니다. 고쳐진 자료형(Typing)은 `lib.dom.d.ts` 파일에 포함될 겁니다.
#### 어떤 패키지가 `export =` 를 쓰고 있는데, 저는 디폴트 임포트(Default import)가 더 좋습니다. `export =` 를 `export default` 로 바꿔도 되나요?
타입스크립트(TypeScript) 2.7 이상을 사용하고 계시면 프로젝트 안에서 `--esModuleInterop` 를 사용해주세요.
그 이하의 경우, 디폴트 임포트(Default import)가 동작하는 환경(Webpack, SystemJS, esm)에서 작업 중이시면 [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) 를 사용하는 걸 고려해보세요.
자료형 정의(Type definition)가 맞는 경우에는 자료형 정의(Type definition)을 수정하지 마세요.
NPM 패키지의 경우, `node -p 'require("foo")'` 가 원하는 값이라면 `export =` 이 맞고, `node -p 'require("foo").default'` 이 원하는 값이라면 `export default` 이 맞습니다.
#### 자료형 선언(Type declaration)에서 타입스크립트(TypeScript) 2.1 이상의 기능을 사용하고 싶습니다.
정의(Definition) 머릿주석(`// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`) 뒤에 `// TypeScript Version: 2.1` 를 추가해주시면 됩니다.
#### 타입스크립트(TypeScript)에 기본으로 포함되지 않은 DOM API 를 추가하고 싶어요.
[TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme) 저장소가 관련되어있을 가능성이 있습니다. 해당 저장소의 안내를 따라주세요.
해당 표준이 아직 초안인 상태라면, 이 저장소와 관련된 일입니다.
`dom-` 으로 시작하는 패키지를 만드신 뒤, "Project" 머릿주석 부분에 해당 표준의 링크를 써 주세요.
다만 표준이 초안을 벗어나면 DefinitelyTyped 에서 삭제되고 `@types` 패키지가 지원이 중단된(Deprecated) 것으로 표시될 수도 있습니다.
#### 패키지를 새 메이저 버전(major version)에 맞게 갱신하고 싶어요.
옛날 버전도 계속해서 수정할 예정이라면, 이전 버전에 해당하는 새 디렉토리(예를 들어 `2.` 버전을 위해서는 `v2`)를 만들고 현재 파일들을 그 디렉토리로 옮겨야 합니다. 새 디렉토리로 옮긴 뒤에는
1. `tsconfig.json` 와 `tslint.json` 에 포함된 상대경로들을 수정해주어야 합니다.
2. 경로 대응 규칙(Path mapping rule)을 추가하여 테스트가 올바른 버전을 검사하도록 해야합니다.
예를 들어, [history 패키지의 2 버전의 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) 파일은 다음과 같이 생겼습니다.
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": [ "history/v2" ]
},
},
"files": [
"index.d.ts",
"history-tests.ts"
]
}
```
수정 중인 패키지에 의존하는 DefinitelyTyped 의 다른 패키지들이 새 버전과 호환되지 않을 경우, 그 패키지들에도 옛날 버전으로의 경로 대응 규칙(Path mapping rule)을 추가해주어야 합니다. 수정 중인 패키지에 의존하는 패키지에 의존하는 패키지들에도 똑같은 작업을 해 주셔야 합니다.
예를 들어, `react-router` 패키지는 `history@2` 패키지에 의존하고 있기 때문에, [react-router 패키지의 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) 파일이 `"history": [ "history/v2" ]` 와 같은 경로 대응 규칙(Path mapping rule)을 가지고 있는 걸 볼 수 있습니다.
이어서 (`react-router` 패키지에 의존하는 패키지인) `react-router-bootstrap` 또한 [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json) 파일 안에 경로 대응 규칙(Path mapping rule)을 가지고 있는 것을 보실 수 있습니다.
`/// <reference types=".." />` 에서는 경로 대응 규칙(Path mapping rule)이 동작하지 않기 때문에, DefinitelyTyped 패키지로에 의존할 때에는 임포트(import) 를 사용해야 합니다.
#### 전역적으로도 모듈로도 사용될 수 있는 패키지의 자료형 선언(Type declaration)은 어떻게 쓰나요?
타입스크립트 안내서(TypeScript Handbook)은 [선언(Declaration)을 쓰는 방법에 대한 전반적인 정보](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)와 [예시들](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html)을 포함하고 있습니다. 이 내용에는 ES6 식의 모듈 문법을 사용할 수 있는 자료형 선언(Type declaration)을 만드는 방법과 객체를 전역에서 사용할 수 있도록 하는 방법이 포함되어 있습니다. [big.js 패키지의 자료형 선언(Type declaration)](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts)이 실례입니다. 이 패키지는 웹 페이지의 스크립트 태그를 사용해 불러올 수 있으며, 또한 ES6 식의 임포트(Import) 구문을 사용해서 불러올 수도 있습니다.
여러분의 패키지가 임포트(Import) 구문을 사용했을 때와 전역적으로 불렀을 때를 테스트 해보고 싶다면, `test` 디렉토리를 추가하고 `YourLibraryName-global.test.ts` 그리고 `YourLibraryName-module.test.ts` 라는 이름으로 테스트 파일 두 개를 추가해주세요. **전역(Global)** 테스트 파일은 웹 페이지에서 전역적으로 사용될 때를 테스트하는 파일입니다. 이 파일에서는 임포트(Import) 구문을 사용하지 않아야 합니다. **모듈(Module)** 테스트 파일은 임포트(Import) 구문을 사용할 때를 테스트 하는 파일입니다. 만약 여러분의 `tsconfig.json` 파일이 `files` 필드(Field)를 가지고 있다면, 이 필드(Field)는 반드시 두 테스트 파일을 모두 포함해야 합니다. [이 방식을 사용하는 실례](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) 또한 big.js 패키지의 자료형 선언(Type declaration)에서 확인해보실 수 있습니다.
각각의 테스트 파일에 모든 상황을 테스트할 필요는 없다는 걸 잊지마세요. 전역 테스트 파일에서는 전역적으로 사용될 때만 테스트하고, 모듈 테스트 파일에서 나머지 상황들을 모두 테스트 할 수 있으며, 그 반대의 경우도 괜찮습니다.
#### 지역 패키지(Scoped package)의 경우는 어떻게 하죠?
`@foo/bar` 패키지와 같은 지역 패키지(Scoped package)를 위한 자료형 패키지(Type package)는 `types/foo__bar` 디렉토리에 추가하면 됩니다. 밑줄 문자가 두 번 있는 것에 주의하세요.
지역 패키지(Scoped package)를 위한 자료형 패키지(Type package)를 생성하기 위해 `dts-gen` 를 사용한 경우에는,
다음과 같이 생성된 `tsconfig.json` 안에 지역 패키지(Scoped package)를 위한 적절한 경로 대응 규칙(Path mapping rule)을 추가해주어야 합니다.
```json
{
"paths":{
"@foo/bar": ["foo__bar"]
}
}
```
#### 깃헙(GitHub)이 보여주는 파일 히스토리(History)가 불완전해요.
깃헙은 이름이 바뀐 파일의 히스토리(History)를 [지원하지 않습니다](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames). 대신 [`git log --follow`](https://www.git-scm.com/docs/git-log) 명령을 사용하세요.
#### ES6 에서 사용하는 임포트(Import)를 사용하기 위해 모듈을 익스포트(Export)하지 않는 패키지들에 빈 이름공간을 추가해야 하나요?
[chai-http](https://github.com/chaijs/chai-http) 패키지와 같은 몇몇 패키지들은 함수를 익스포트(Export)합니다.
이런 패키지들을 `import * as foo from "foo";` 와 같이 임포트(Import)하면 다음과 같은 오류가 발생합니다.
> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
이 오류는 함수의 이름과 똑같은 빈 이름공간(Namespace)을 정의해서 없앨 수 있으나, 좋은 방법은 아닙니다.
[스택오버플로(Stack Overflow)의 이 질문의 답변](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this)이 이 문제와 관련되어 자주 언급됩니다.
`import foo = require("foo");` 를 사용하여 모듈을 임포트(Import)하거나, 환경에서 ES6 모듈 변환(Module interop)을 지원한다면 `--allowSyntheticDefaultImports` 와 함께 `import foo from "foo";` 같은 디폴트 임포트(Default import)를 사용하는 것이 더 나은 방법입니다.
## 라이센스
이 프로젝트는 MIT license 가 적용되어 있습니다.
각 자료형 정의(Type definition) 파일들의 저작권은 각 기여자들에게 있으며, 기여자들은 해당 자료형 정의(Type definition) 파일들의 맨 위에 나열되어 있습니다.
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)
+311 -16
View File
@@ -1,38 +1,333 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.png?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/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.
Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date.
## Usage
*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) and [Korean!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md)*
Include a line like this:
## What are declaration files?
```typescript
/// <reference path="jquery.d.ts" />
See the [TypeScript handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
## How do I get them?
### npm
This is the preferred method. This is only available for TypeScript 2.0+ users. For example:
```sh
npm install --save-dev @types/node
```
## Contributions
The types should then be automatically included by the compiler.
See more in the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html).
For an NPM package "foo", typings for it will be at "@types/foo".
If you can't find your package, look for it on [TypeSearch](https://microsoft.github.io/TypeSearch/).
If you still can't find it, check if it [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) its own typings.
This is usually provided in a `"types"` or `"typings"` field in the `package.json`,
or just look for any ".d.ts" files in the package and manually include them with a `/// <reference path="" />`.
### Other methods
These can be used by TypeScript 1.0.
* [Typings](https://github.com/typings/typings)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off)
* Manually download from the `master` branch of this repository
You may need to add manual [references](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
## How can I contribute?
DefinitelyTyped only works because of contributions by users like you!
Please see the [contribution guide](http://definitelytyped.org/guides/contributing.html) on how to contribute to DefinitelyTyped.
### Test
## How to get the definitions
Before you share your improvement with the world, use it yourself.
* Directly from the Github repos
* [NuGet packages](http://nuget.org/packages?q=DefinitelyTyped)
* [TypeScript Definition manager](https://github.com/DefinitelyTyped/tsd)
#### Test editing an existing package
## List of definitions
To add new features you can use [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation).
You can also directly edit the types in `node_modules/@types/foo/index.d.ts`, or copy them from there and follow the steps below.
* See [CONTRIBUTORS.md](CONTRIBUTORS.md)
## Requested definitions
#### Test a new package
Here is are the [currently requested definitions](https://github.com/borisyankov/DefinitelyTyped/labels/Definition%3ARequest).
Add to your `tsconfig.json`:
```json
"baseUrl": "types",
"typeRoots": ["types"],
```
(You can also use `src/types`.)
Create `types/foo/index.d.ts` containing declarations for the module "foo".
You should now be able import from `"foo"` in your code and it will route to the new type definition.
Then build *and* run the code to make sure your type definition actually corresponds to what happens at runtime.
Once you've tested your definitions with real code, make a [PR](#make-a-pull-request)
then follow the instructions to [edit an existing package](#edit-an-existing-package) or
[create a new package](#create-a-new-package).
### Make a pull request
Once you've tested your package, you can share it on DefinitelyTyped.
First, [fork](https://guides.github.com/activities/forking/) this repository, install [node](https://nodejs.org/), and run `npm install`.
#### Edit an existing package
* `cd types/my-package-to-edit`
* Make changes. Remember to edit tests.
If you make breaking changes, do not forget to [update a major version](#i-want-to-update-a-package-to-a-new-major-version).
* You may also want to add yourself to "Definitions by" section of the package header.
- This will cause you to be notified (via your GitHub username) whenever someone makes a pull request or issue about the package.
- Do this by adding your name to the end of the line, as in `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
- Or if there are more people, it can be multiline
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* If there is a `tslint.json`, run `npm run lint package-name`. Otherwise, run `tsc` in the package directory.
When you make a PR to edit an existing package, `dt-bot` should @-mention previous authors.
If it doesn't, you can do so yourself in the comment associated with the PR.
#### Create a new package
If you are the library author and your package is written in TypeScript, [bundle the autogenerated declaration files](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) in your package instead of publishing to DefinitelyTyped.
If you are adding typings for an NPM package, create a directory with the same name.
If the package you are adding typings for is not on NPM, make sure the name you choose for it does not conflict with the name of a package on NPM.
(You can use `npm info foo` to check for the existence of the `foo` package.)
Your package should have this structure:
| File | Purpose |
| --- | --- |
| index.d.ts | This contains the typings for the package. |
| foo-tests.ts | This contains sample code which tests the typings. This code does *not* run, but it is type-checked. |
| tsconfig.json | This allows you to run `tsc` within the package. |
| tslint.json | Enables linting. |
Generate these by running `npx dts-gen --dt --name my-package-name --template module` if you have npm ≥ 5.2.0, `npm install -g dts-gen` and `dts-gen --dt --name my-package-name --template module` otherwise.
See all options at [dts-gen](https://github.com/Microsoft/dts-gen).
You may edit the `tsconfig.json` to add new files, to add `"target": "es6"` (needed for async functions), to add to `"lib"`, or to add the `"jsx"` compiler option.
DefinitelyTyped members routinely monitor for new PRs, though keep in mind that the number of other PRs may slow things down.
For a good example package, see [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).
#### Common mistakes
* First, follow advice from the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
* Formatting: Either use all tabs, or always use 4 spaces.
* `function sum(nums: number[]): number`: Use `ReadonlyArray` if a function does not write to its parameters.
* `interface Foo { new(): Foo; }`:
This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); }`.
* `const Class: { new(): IClass; }`:
Prefer to use a class declaration `class Class { constructor(); }` instead of a new-able constant.
* `getMeAT<T>(): T`:
If a type parameter does not appear in the types of any parameters, you don't really have a generic function, you just have a disguised type assertion.
Prefer to use a real type assertion, e.g. `getMeAT() as number`.
Example where a type parameter is acceptable: `function id<T>(value: T): T;`.
Example where it is not acceptable: `function parseJson<T>(json: string): T;`.
Exception: `new Map<string, number>()` is OK.
* Using the types `Function` and `Object` is almost never a good idea. In 99% of cases it's possible to specify a more specific type. Examples are `(x: number) => number` for [functions](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) and `{ x: number, y: number }` for objects. If there is no certainty at all about the type, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) is the right choice, not `Object`. If the only known fact about the type is that it's some object, use the type [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), not `Object` or `{ [key: string]: any }`.
* `var foo: string | any`:
When `any` is used in a union type, the resulting type is still `any`. So while the `string` portion of this type annotation may _look_ useful, it in fact offers no additional typechecking over simply using `any`.
Depending on the intention, acceptable alternatives could be `any`, `string`, or `string | object`.
#### Removing a package
When a package [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) its own types, types should be removed from DefinitelyTyped to avoid confusion.
You can remove it by running `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`.
- `typingsPackageName`: This is the name of the directory to delete.
- `asOfVersion`: A stub will be published to `@types/foo` with this version. Should be higher than any currently published version.
- `sourceRepoURL`: This should point to the repository that contains the typings.
- `libraryName`: Descriptive name of the library, e.g. "Angular 2" instead of "angular2". (If ommitted, will be identical to "typingsPackageName".)
Any other packages in DefinitelyTyped that referenced the deleted package should be updated to reference the bundled types. To do this, add a `package.json` with `"dependencies": { "foo": "x.y.z" }`.
If a package was never on DefinitelyTyped, it does not need to be added to `notNeededPackages.json`.
#### Lint
To lint a package, just add a `tslint.json` to that package containing `{ "extends": "dtslint/dt.json" }`. All new packages must be linted.
If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example:
```js
{
"extends": "dtslint/dt.json",
"rules": {
// This package uses the Function type, and it will take effort to fix.
"ban-types": false
}
}
```
(To indicate that a lint rule truly does not apply, use `// tslint:disable rule-name` or better, `//tslint:disable-next-line rule-name`.)
To assert that an expression is of a given type, use `$ExpectType`. To assert that an expression causes a compile error, use `$ExpectError`.
```js
// $ExpectType void
f(1);
// $ExpectError
f("one");
```
For more details, see [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.
Test by running `npm run lint package-name` where `package-name` is the name of your package.
This script uses [dtslint](https://github.com/Microsoft/dtslint).
## FAQ
#### What exactly is the relationship between this repository and the `@types` packages on NPM?
The `master` branch is automatically published to the `@types` scope on NPM thanks to [types-publisher](https://github.com/Microsoft/types-publisher).
#### I've submitted a pull request. How long until it is merged?
It depends, but most pull requests will be merged within a week. PRs that have been approved by an author listed in the definition's header are usually merged more quickly; PRs for new definitions will take more time as they require more review from maintainers. Each PR is reviewed by a TypeScript or DefinitelyTyped team member before being merged, so please be patient as human factors may cause delays. Check the [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) to see progress as maintainers work through the open PRs.
#### My PR is merged; when will the `@types` NPM package be updated?
NPM packages should update within a few hours. If it's been more than 24 hours, ping @RyanCavanaugh and @andy-ms on the PR to investigate.
#### I'm writing a definition that depends on another definition. Should I use `<reference types="" />` or an import?
If the module you're referencing is an external module (uses `export`), use an import.
If the module you're referencing is an ambient module (uses `declare module`, or just declares globals), use `<reference types="" />`.
#### I notice some packages having a `package.json` here.
Usually you won't need this. When publishing a package we will normally automatically create a `package.json` for it.
A `package.json` may be included for the sake of specifying dependencies. Here's an [example](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
We do not allow other fields, such as `"description"`, to be defined manually.
Also, if you need to reference an older version of typings, you must do that by adding `"dependencies": { "@types/foo": "x.y.z" }` to the package.json.
#### Some packages have no `tslint.json`, and some `tsconfig.json` are missing `"noImplicitAny": true`, `"noImplicitThis": true`, or `"strictNullChecks": true`.
Then they are wrong. You can help by submitting a pull request to fix them.
#### Can I request a definition?
Here are the [currently requested definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest).
#### What about type definitions for the DOM?
If types are part of a web standard, they should be contributed to [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) so that they can become part of the default `lib.dom.d.ts`.
#### A package uses `export =`, but I prefer to use default imports. Can I change `export =` to `export default`?
If you are using TypeScript 2.7 or later, use `--esModuleInterop` in your project.
Otherwise, if default imports work in your environment (e.g. Webpack, SystemJS, esm), consider turning on the [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) compiler option.
Do not change the type definition if it is accurate.
For an NPM package, `export =` is accurate if `node -p 'require("foo")'` is the export, and `export default` is accurate if `node -p 'require("foo").default'` is the export.
#### I want to use features from TypeScript 2.1 or above.
Then you will have to add a comment to the last line of your definition header (after `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
#### I want to add a DOM API not present in TypeScript by default.
This may belong in [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). See the guidelines there.
If the standard is still a draft, it belongs here.
Use a name beginning with `dom-` and include a link to the standard as the "Project" link in the header.
When it graduates draft mode, we may remove it from DefinitelyTyped and deprecate the associated `@types` package.
#### I want to update a package to a new major version
If you intend to continue updating the older version of the package, you may create a new subfolder with the current version e.g. `v2`, and copy existing files to it. If so, you will need to:
1. Update the relative paths in `tsconfig.json` as well as `tslint.json`.
2. Add path mapping rules to ensure that tests are running against the intended version.
For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like:
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": [ "history/v2" ]
},
},
"files": [
"index.d.ts",
"history-tests.ts"
]
}
```
If there are other packages on DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this for packages depending on packages depending on the old version.
For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`;
transitively `react-router-bootstrap` (which depends on `react-router`) also adds a path mapping in its [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
Also, `/// <reference types=".." />` will not work with path mapping, so dependencies must use `import`.
#### How do I write definitions for packages that can be used globally and as a module?
The TypeScript handbook contains excellent [general information about writing definitions](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), and also [this example definition file](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) which shows how to create a definition using ES6-style module syntax, while also specifying objects made available to the global scope. This technique is demonstrated practically in the [definition for big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), which is a library that can be loaded globally via script tag on a web page, or imported via require or ES6-style imports.
To test how your definition can be used both when referenced globally or as an imported module, create a `test` folder, and place two test files in there. Name one `YourLibraryName-global.test.ts` and the other `YourLibraryName-module.test.ts`. The *global* test file should exercise the definition according to how it would be used in a script loaded on a web page where the library is available on the global scope - in this scenario you should not specify an import statement. The *module* test file should exercise the definition according to how it would be used when imported (including the `import` statement(s)). If you specify a `files` property in your `tsconfig.json` file, be sure to include both test files. A [practical example of this](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) is also available on the big.js definition.
Please note that it is not required to fully exercise the definition in each test file - it is sufficient to test only the globally-accessible elements on the global test file and fully exercise the definition in the module test file, or vice versa.
#### What about scoped packages?
Types for a scoped package `@foo/bar` should go in `types/foo__bar`. Note the double underscore.
When `dts-gen` is used to scaffold a scoped package, the `paths` property has to be manually adapted in the generated
`tsconfig.json` to correctly reference the scoped package:
```json
{
"paths":{
"@foo/bar": ["foo__bar"]
}
}
```
#### The file history in GitHub looks incomplete.
GitHub doesn't [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) file history for renamed files. Use [`git log --follow`](https://www.git-scm.com/docs/git-log) instead.
#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports?
Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function.
Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error:
> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged.
This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter.
It is more appropriate to import the module using the `import foo = require("foo");` syntax, or to use a default import like `import foo from "foo";` if using the `--allowSyntheticDefaultImports` flag if your module runtime supports an interop scheme for non-ECMAScript modules as such.
## License
-10
View File
@@ -1,10 +0,0 @@
/// <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
@@ -1,135 +0,0 @@
// 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;
}
-5
View File
@@ -1,5 +0,0 @@
/// <reference path="./abs.d.ts" />
import Abs from 'abs';
const x: string = Abs('/foo');
-14
View File
@@ -1,14 +0,0 @@
// Type definitions for abs 1.1.0
// Project: https://github.com/IonicaBizau/node-abs
// Definitions by: Aya Morisawa <https://github.com/AyaMorisawa>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "abs" {
/**
* Compute the absolute path of an input.
* @param input The input path.
*/
function Abs(input: string): string;
export default Abs;
}
-5
View File
@@ -1,5 +0,0 @@
/// <reference path="./absolute.d.ts" />
import absolute from 'absolute';
const x: boolean = absolute('/home/foo');
-13
View File
@@ -1,13 +0,0 @@
// Type definitions for absolute 0.0.1
// Project: https://github.com/bahamas10/node-absolute
// Definitions by: Aya Morisawa <https://github.com/AyaMorisawa>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "absolute" {
/**
* Test if a path is absolute
*/
function absolute(path: string): boolean;
export default absolute;
}
-113
View File
@@ -1,113 +0,0 @@
// 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}
*/
backText: string;
/**
* @summary HTML input type for next button. (default: "submit")
* @type {string}
*/
nextType: string;
/**
* @summary HTML input type for back button. (default: "reset")
* @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;
}
-79
View File
@@ -1,79 +0,0 @@
// Type definitions for accounting.js 0.3.2
// Project: http://josscrowcroft.github.io/accounting.js/
// Definitions by: Sergey Gerasimov <https://github.com/gerich-home/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface IAccountingCurrencyFormat {
pos: string; // for positive values, eg. "$ 1.00"
neg?: string; // for negative values, eg. "$ (1.00)"
zero?: string; // for zero values, eg. "$ --"
}
interface IAccountingCurrencySettings<TFormat> {
symbol?: string; // default currency symbol is '$'
format?: TFormat; // controls output: %s = symbol, %v = value/number
decimal?: string; // decimal point separator
thousand?: string; // thousands separator
precision?: number // decimal places
}
interface IAccountingNumberSettings {
precision?: number; // default precision on numbers is 0
thousand?: string;
decimal?: string;
}
interface IAccountingSettings {
currency: IAccountingCurrencySettings<any>; // IAccountingCurrencySettings<string> or IAccountingCurrencySettings<IAccountingCurrencyFormat>
number: IAccountingNumberSettings;
}
interface IAccountingStatic {
// format any number into currency
formatMoney(number: number, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string;
formatMoney(number: number, options: IAccountingCurrencySettings<string>): string;
formatMoney(number: number, options: IAccountingCurrencySettings<IAccountingCurrencyFormat>): string;
formatMoney(numbers: number[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[];
formatMoney(numbers: number[], options: IAccountingCurrencySettings<string>): string[];
formatMoney(numbers: number[], options: IAccountingCurrencySettings<IAccountingCurrencyFormat>): string[];
// generic case (any array of numbers)
formatMoney(numbers: any[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): any[];
formatMoney(numbers: any[], options: IAccountingCurrencySettings<string>): any[];
formatMoney(numbers: any[], options: IAccountingCurrencySettings<IAccountingCurrencyFormat>): any[];
// format a list of values for column-display
formatColumn(numbers: number[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[];
formatColumn(numbers: number[], options: IAccountingCurrencySettings<string>): string[];
formatColumn(numbers: number[], options: IAccountingCurrencySettings<IAccountingCurrencyFormat>): string[];
formatColumn(numbers: number[][], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[][];
formatColumn(numbers: number[][], options: IAccountingCurrencySettings<string>): string[][];
formatColumn(numbers: number[][], options: IAccountingCurrencySettings<IAccountingCurrencyFormat>): string[][];
// format a number with custom precision and localisation
formatNumber(number: number, precision?: number, thousand?: string, decimal?: string): string;
formatNumber(number: number, options: IAccountingNumberSettings): string;
formatNumber(number: number[], precision?: number, thousand?: string, decimal?: string): string[];
formatNumber(number: number[], options: IAccountingNumberSettings): string[];
formatNumber(number: any[], precision?: number, thousand?: string, decimal?: string): any[];
formatNumber(number: any[], options: IAccountingNumberSettings): any[];
// better rounding for floating point numbers
toFixed(number: number, precision?: number): string;
// get a value from any formatted number/currency string
unformat(string: string, decimal?: string): number;
// settings object that controls default parameters for library methods
settings: IAccountingSettings;
}
declare var accounting: IAccountingStatic;
declare module "accounting" {
export = accounting;
}
-2984
View File
File diff suppressed because it is too large Load Diff
-26
View File
@@ -1,26 +0,0 @@
/// <reference path="ace.d.ts" />
var exports: any;
var assert: any;
var MockRenderer = null;
var JavaScriptMode = null;
/// <reference path="tests/ace-default-tests.ts" />
/// <reference path="tests/ace-background_tokenizer-tests.ts" />
/// <reference path="tests/ace-document-tests.ts" />
/// <reference path="tests/ace-edit_session-tests.ts" />
/// <reference path="tests/ace-editor1-tests.ts" />
/// <reference path="tests/ace-editor_highlight_selected_word-tests.ts" />
/// <reference path="tests/ace-editor_navigation-tests.ts" />
/// <reference path="tests/ace-editor_text_edit-tests.ts" />
/// <reference path="tests/ace-multi_select-tests.ts" />
/// <reference path="tests/ace-placeholder-tests.ts" />
/// <reference path="tests/ace-range_list-tests.ts" />
/// <reference path="tests/ace-range-tests.ts" />
/// <reference path="tests/ace-search-tests.ts" />
/// <reference path="tests/ace-selection-tests.ts" />
/// <reference path="tests/ace-token_iterator-tests.ts" />
/// <reference path="tests/ace-virtual_renderer-tests.ts" />
-1
View File
@@ -1 +0,0 @@
-132
View File
@@ -1,132 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var exports = {
"test create anchor" : function() {
var doc = new AceAjax.Document("juhu");
var anchor = new AceAjax.Anchor(doc, 0, 0);
assert.position(anchor.getPosition(), 0, 0);
assert.equal(anchor.getDocument(), doc);
},
"test insert text in same row before cursor should move anchor column": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.insert({row: 1, column: 1}, "123");
assert.position(anchor.getPosition(), 1, 7);
},
"test insert lines before cursor should move anchor row": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.insertLines(1, ["123", "456"]);
assert.position(anchor.getPosition(), 3, 4);
},
"test insert new line before cursor should move anchor column": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.insertNewLine({row: 0, column: 0});
assert.position(anchor.getPosition(), 2, 4);
},
"test insert new line in anchor line before anchor should move anchor column and row": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.insertNewLine({row: 1, column: 2});
assert.position(anchor.getPosition(), 2, 2);
},
"test delete text in anchor line before anchor should move anchor column": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.remove(new AceAjax.Range(1, 1, 1, 3));
assert.position(anchor.getPosition(), 1, 2);
},
"test remove range which contains the anchor should move the anchor to the start of the range": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 0, 3);
doc.remove(new AceAjax.Range(0, 1, 1, 3));
assert.position(anchor.getPosition(), 0, 1);
},
"test delete character before the anchor should have no effect": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.remove(new AceAjax.Range(1, 4, 1, 5));
assert.position(anchor.getPosition(), 1, 4);
},
"test delete lines in anchor line before anchor should move anchor row": function() {
var doc = new AceAjax.Document("juhu\n1\n2\nkinners");
var anchor = new AceAjax.Anchor(doc, 3, 4);
doc.removeLines(1, 2);
assert.position(anchor.getPosition(), 1, 4);
},
"test remove new line before the cursor": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.removeNewLine(0);
assert.position(anchor.getPosition(), 0, 8);
},
"test delete range which contains the anchor should move anchor to the end of the range": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.remove(new AceAjax.Range(0, 2, 1, 2));
assert.position(anchor.getPosition(), 0, 4);
},
"test delete line which contains the anchor should move anchor to the end of the range": function() {
var doc = new AceAjax.Document("juhu\nkinners\n123");
var anchor = new AceAjax.Anchor(doc, 1, 5);
doc.removeLines(1, 1);
assert.position(anchor.getPosition(), 1, 0);
},
"test remove after the anchor should have no effect": function() {
var doc = new AceAjax.Document("juhu\nkinners\n123");
var anchor = new AceAjax.Anchor(doc, 1, 2);
doc.remove(new AceAjax.Range(1, 4, 2, 2));
assert.position(anchor.getPosition(), 1, 2);
},
"test anchor changes triggered by document changes should emit change event": function(next) {
var doc = new AceAjax.Document("juhu\nkinners\n123");
var anchor = new AceAjax.Anchor(doc, 1, 5);
anchor.on("change", function(e) {
assert.position(anchor.getPosition(), 0, 0);
next();
});
doc.remove(new AceAjax.Range(0, 0, 2, 1));
},
"test only fire change event if position changes": function() {
var doc = new AceAjax.Document("juhu\nkinners\n123");
var anchor = new AceAjax.Anchor(doc, 1, 5);
anchor.on("change", function(e) {
assert.fail();
});
doc.remove(new AceAjax.Range(2, 0, 2, 1));
}
};
-1
View File
@@ -1 +0,0 @@
@@ -1,41 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
function forceTokenize(session) {
for (var i = 0, l = session.getLength(); i < l; i++)
session.getTokens(i)
}
function testStates(session, states) {
for (var i = 0, l = session.getLength(); i < l; i++)
assert.equal(session.bgTokenizer.states[i], states[i])
assert.ok(l == states.length)
}
var exports = {
"test background tokenizer update on session change": function() {
var doc = new AceAjax.EditSession([
"/*",
"*/",
"var juhu"
]);
doc.setMode("./mode/javascript")
forceTokenize(doc)
testStates(doc, ["comment", "start", "start"])
doc.remove(new AceAjax.Range(0, 2, 1, 2))
testStates(doc, [null, "start"])
forceTokenize(doc)
testStates(doc, ["comment", "comment"])
doc.insert({ row: 0, column: 2 }, "\n*/")
testStates(doc, [undefined, undefined, "comment"])
forceTokenize(doc)
testStates(doc, ["comment", "start", "start"])
}
};
@@ -1 +0,0 @@
-451
View File
@@ -1,451 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
editor.setTheme("ace/theme/twilight");
editor.getSession().setMode("ace/mode/javascript");
editor.setValue("the new text here"); // or session.setValue
editor.getValue(); // or session.getValue
editor.session.getTextRange(editor.getSelectionRange());
editor.insert("Something cool");
editor.selection.getCursor();
editor.gotoLine(123);
editor.session.getLength();
editor.getSession().setTabSize(4);
editor.getSession().setUseSoftTabs(true);
document.getElementById('editor').style.fontSize = '12px';
editor.getSession().setUseWrapMode(true);
editor.setHighlightActiveLine(false);
editor.setShowPrintMargin(false);
editor.setReadOnly(true); // false to make it editable
editor.resize()
editor.find('needle', {
backwards: false,
wrap: false,
caseSensitive: false,
wholeWord: false,
regExp: false
});
editor.findNext();
editor.findPrevious();
editor.find('foo');
editor.replace('bar');
editor.replaceAll('bar');
editor.getSession().on('change', function (e) {
// e.type, etc
});
editor.getSession().selection.on('changeSelection', function (e) {
});
editor.getSession().selection.on('changeCursor', function (e) {
});
editor.commands.addCommand({
name: 'myCommand',
bindKey: { win: 'Ctrl-M', mac: 'Command-M' },
exec: function (editor) {
//...
},
readOnly: true // false if this command should not apply in readOnly mode
});
editor.moveCursorTo(1, 1);
editor.removeLines();
editor.removeLines();
editor.removeLines();
editor.removeLines();
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.removeLines();
editor.removeLines();
editor.moveCursorTo(3, 0);
editor.removeLines();
editor.removeLines();
editor.moveCursorTo(1, 3);
editor.getSelection().selectDown();
editor.indent();
var range = editor.getSelectionRange();
editor.moveCursorTo(1, 0);
editor.getSelection().selectDown();
editor.indent();
editor.moveCursorTo(0, 0);
editor.onTextInput("\n");
editor.moveCursorTo(0, 5);
editor.getSelection().selectDown();
editor.getSelection().selectDown();
editor.blockOutdent();
editor.moveCursorTo(1, 1);
editor.removeLines();
var session = new AceAjax.EditSession(["a", "b", "c", "d"].join("\n"));
assert.equal(session.toString(), "a\nc\nd");
assert.position(editor.getCursorPosition(), 1, 0);
editor.removeLines();
assert.equal(session.toString(), "a\nd");
assert.position(editor.getCursorPosition(), 1, 0);
editor.removeLines();
assert.equal(session.toString(), "a");
assert.position(editor.getCursorPosition(), 0, 1);
editor.removeLines();
assert.equal(session.toString(), "");
assert.position(editor.getCursorPosition(), 0, 0);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.removeLines();
assert.equal(session.toString(), "a\nd");
assert.position(editor.getCursorPosition(), 1, 0);
editor.removeLines();
assert.equal(session.toString(), "b\nc");
assert.position(editor.getCursorPosition(), 0, 0);
editor.moveCursorTo(3, 0);
editor.removeLines();
assert.equal(session.toString(), "a\nb\nc");
assert.position(editor.getCursorPosition(), 2, 1);
editor.removeLines();
assert.equal(session.toString(), "a\nb");
assert.position(editor.getCursorPosition(), 1, 1);
editor.moveCursorTo(1, 3);
editor.getSelection().selectDown();
editor.indent();
assert.equal(["a12345", " b12345", " c12345"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 7);
range = editor.getSelectionRange();
assert.position(range.start, 1, 7);
assert.position(range.end, 2, 7);
editor.moveCursorTo(1, 0);
editor.getSelection().selectDown();
editor.indent();
assert.equal(["a12345", " b12345", "c12345"].join("\n"), session.toString());
editor.moveCursorTo(0, 0);
editor.onTextInput("\n");
assert.equal(["", "{"].join("\n"), session.toString());
editor.moveCursorTo(0, 5);
editor.getSelection().selectDown();
editor.getSelection().selectDown();
editor.blockOutdent();
assert.equal(session.toString(), [" a12345", "b12345", " c12345"].join("\n"));
assert.position(editor.getCursorPosition(), 2, 1);
range = editor.getSelectionRange();
assert.position(range.start, 0, 1);
assert.position(range.end, 2, 1);
editor.blockOutdent();
assert.equal(session.toString(), ["a12345", "b12345", "c12345"].join("\n"));
range = editor.getSelectionRange();
assert.position(range.start, 0, 0);
assert.position(range.end, 2, 0);
editor.moveCursorTo(0, 3);
editor.blockOutdent(" ");
assert.equal(session.toString(), " 12");
assert.position(editor.getCursorPosition(), 0, 0);
editor.moveCursorTo(0, 2);
editor.getSelection().selectDown();
editor.toggleCommentLines();
assert.equal(["// abc", "//cde"].join("\n"), session.toString());
var selection = editor.getSelectionRange();
assert.position(selection.start, 0, 4);
assert.position(selection.end, 1, 4);
editor.moveCursorTo(0, 1);
editor.getSelection().selectDown();
editor.getSelection().selectRight();
editor.getSelection().selectRight();
editor.toggleCommentLines();
assert.equal([" abc", "cde"].join("\n"), session.toString());
assert.range(editor.getSelectionRange(), 0, 0, 1, 1);
editor.moveCursorTo(0, 0);
editor.getSelection().selectDown();
editor.getSelection().selectDown();
editor.toggleCommentLines();
editor.toggleCommentLines();
assert.equal([" abc", "cde", "fg"].join("\n"), session.toString());
editor.moveCursorTo(0, 0);
editor.getSelection().selectDown();
editor.toggleCommentLines();
assert.range(editor.getSelectionRange(), 0, 2, 1, 0);
editor.moveCursorTo(1, 0);
editor.getSelection().selectUp();
editor.toggleCommentLines();
assert.range(editor.getSelectionRange(), 0, 2, 1, 0);
editor.moveCursorTo(0, 1);
editor.getSelection().selectDown();
editor.moveLinesDown();
assert.equal(["33", "11", "22", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 1, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 0);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
editor.moveLinesDown();
assert.equal(["33", "44", "11", "22"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 2);
assert.position(editor.getSelection().getSelectionLead(), 2, 0);
// moving again should have no effect
editor.moveLinesDown();
assert.equal(["33", "44", "11", "22"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 2);
assert.position(editor.getSelection().getSelectionLead(), 2, 0);
editor.moveCursorTo(2, 1);
editor.getSelection().selectDown();
editor.moveLinesUp();
assert.equal(session.toString(), ["11", "33", "44", "22"].join("\n"));
assert.position(editor.getCursorPosition(), 1, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 0);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
editor.moveLinesUp();
assert.equal(session.toString(), ["33", "44", "11", "22"].join("\n"));
assert.position(editor.getCursorPosition(), 0, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 2, 0);
assert.position(editor.getSelection().getSelectionLead(), 0, 0);
editor.moveCursorTo(1, 1);
editor.clearSelection();
editor.moveLinesDown();
assert.equal(["11", "33", "22", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 1);
editor.clearSelection();
editor.moveLinesUp();
assert.equal(["11", "22", "33", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 1, 1);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.copyLinesDown();
assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 3, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 5, 0);
assert.position(editor.getSelection().getSelectionLead(), 3, 0);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.copyLinesUp();
assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 1, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 0);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
session.setTabSize(2);
session.setUseSoftTabs(true);
editor.onTextInput("\t");
assert.equal(session.toString(), " ");
session.setTabSize(5);
editor.onTextInput("\t");
assert.equal(session.toString(), " ");
session.setUseSoftTabs(false);
editor.onTextInput("\t");
assert.equal(session.toString(), "\t");
editor.removeLines();
var step1 = session.toString();
assert.equal(step1, "222\n333");
editor.removeLines();
var step2 = session.toString();
assert.equal(step2, "333");
editor.removeLines();
var step3 = session.toString();
assert.equal(step3, "");
var undoManager = new AceAjax.UndoManager();
undoManager.undo();
assert.equal(session.toString(), step2);
undoManager.undo();
assert.equal(session.toString(), step1);
undoManager.undo();
assert.equal(session.toString(), "");
undoManager.undo();
assert.equal(session.toString(), "");
editor.moveCursorTo(1, 1);
editor.remove("left");
assert.equal(session.toString(), "123\n56");
editor.moveCursorTo(1, 0);
editor.remove("left");
assert.equal(session.toString(), "123456");
session.setUseSoftTabs(true);
session.setTabSize(4);
editor.moveCursorTo(1, 8);
editor.remove("left");
assert.equal(session.toString(), "123\n 456");
editor.moveCursorTo(1, 0);
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4567", "89"].join("\n"));
editor.moveCursorTo(1, 2);
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4657", "89"].join("\n"));
editor.moveCursorTo(1, 4);
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4576", "89"].join("\n"));
editor.moveCursorTo(1, 1);
editor.getSelection().selectRight();
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4567", "89"].join("\n"));
editor.moveCursorTo(1, 2);
editor.transposeLetters();
assert.position(editor.getCursorPosition(), 1, 3);
editor.moveCursorTo(1, 2);
editor.removeToLineEnd();
assert.equal(session.getValue(), ["123", "45", "89"].join("\n"));
editor.moveCursorTo(1, 4);
editor.removeToLineEnd();
assert.position(editor.getCursorPosition(), 1, 4);
assert.equal(session.getValue(), ["123", "456789"].join("\n"));
editor.moveCursorTo(1, 0);
editor.getSelection().selectLineEnd();
editor.toUpperCase()
assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n"));
editor.moveCursorTo(1, 0);
editor.toUpperCase()
assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n"));
assert.position(editor.getCursorPosition(), 1, 0);
editor.moveCursorTo(1, 0);
editor.getSelection().selectLineEnd();
editor.toLowerCase()
assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n"));
editor.moveCursorTo(1, 0);
editor.toLowerCase()
assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n"));
assert.position(editor.getCursorPosition(), 1, 0);
-1
View File
@@ -1 +0,0 @@
-255
View File
@@ -1,255 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var exports = {
"test: insert text in line": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insert({ row: 0, column: 1 }, "juhu");
assert.equal(doc.getValue(), ["1juhu2", "34"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["1juhu2", "34"].join("\n"));
} ,
"test: insert new line": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insertNewLine({ row: 0, column: 1 });
assert.equal(doc.getValue(), ["1", "2", "34"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["1", "2", "34"].join("\n"));
} ,
"test: insert lines at the beginning": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insertLines(0, ["aa", "bb"]);
assert.equal(doc.getValue(), ["aa", "bb", "12", "34"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["aa", "bb", "12", "34"].join("\n"));
} ,
"test: insert lines at the end": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insertLines(2, ["aa", "bb"]);
assert.equal(doc.getValue(), ["12", "34", "aa", "bb"].join("\n"));
} ,
"test: insert lines in the middle": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insertLines(1, ["aa", "bb"]);
assert.equal(doc.getValue(), ["12", "aa", "bb", "34"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["12", "aa", "bb", "34"].join("\n"));
} ,
"test: insert multi line string at the start": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insert({ row: 0, column: 0 }, "aa\nbb\ncc");
assert.equal(doc.getValue(), ["aa", "bb", "cc12", "34"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["aa", "bb", "cc12", "34"].join("\n"));
} ,
"test: insert multi line string at the end": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insert({ row: 2, column: 0 }, "aa\nbb\ncc");
assert.equal(doc.getValue(), ["12", "34aa", "bb", "cc"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["12", "34aa", "bb", "cc"].join("\n"));
} ,
"test: insert multi line string in the middle": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insert({ row: 0, column: 1 }, "aa\nbb\ncc");
assert.equal(doc.getValue(), ["1aa", "bb", "cc2", "34"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["1aa", "bb", "cc2", "34"].join("\n"));
} ,
"test: delete in line": function() {
var doc = new AceAjax.Document(["1234", "5678"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.remove(new AceAjax.Range(0, 1, 0, 3));
assert.equal(doc.getValue(), ["14", "5678"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["1234", "5678"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["14", "5678"].join("\n"));
} ,
"test: delete new line": function() {
var doc = new AceAjax.Document(["1234", "5678"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.remove(new AceAjax.Range(0, 4, 1, 0));
assert.equal(doc.getValue(), ["12345678"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["1234", "5678"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["12345678"].join("\n"));
} ,
"test: delete multi line range line": function() {
var doc = new AceAjax.Document(["1234", "5678", "abcd"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.remove(new AceAjax.Range(0, 2, 2, 2));
assert.equal(doc.getValue(), ["12cd"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["1234", "5678", "abcd"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["12cd"].join("\n"));
} ,
"test: delete full lines": function() {
var doc = new AceAjax.Document(["1234", "5678", "abcd"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.remove(new AceAjax.Range(1, 0, 3, 0));
assert.equal(doc.getValue(), ["1234", ""].join("\n"));
} ,
"test: remove lines should return the removed lines": function() {
var doc = new AceAjax.Document(["1234", "5678", "abcd"]);
var removed = doc.removeLines(1, 2);
assert.equal(removed.join("\n"), ["5678", "abcd"].join("\n"));
} ,
"test: should handle unix style new lines": function() {
var doc = new AceAjax.Document(["1", "2", "3"]);
assert.equal(doc.getValue(), ["1", "2", "3"].join("\n"));
} ,
"test: should handle windows style new lines": function() {
var doc = new AceAjax.Document(["1", "2", "3"].join("\r\n"));
doc.setNewLineMode("unix");
assert.equal(doc.getValue(), ["1", "2", "3"].join("\n"));
} ,
"test: set new line mode to 'windows' should use '\\r\\n' as new lines": function() {
var doc = new AceAjax.Document(["1", "2", "3"].join("\n"));
doc.setNewLineMode("windows");
assert.equal(doc.getValue(), ["1", "2", "3"].join("\r\n"));
} ,
"test: set new line mode to 'unix' should use '\\n' as new lines": function() {
var doc = new AceAjax.Document(["1", "2", "3"].join("\r\n"));
doc.setNewLineMode("unix");
assert.equal(doc.getValue(), ["1", "2", "3"].join("\n"));
} ,
"test: set new line mode to 'auto' should detect the incoming nl type": function() {
var doc = new AceAjax.Document(["1", "2", "3"].join("\n"));
doc.setNewLineMode("auto");
assert.equal(doc.getValue(), ["1", "2", "3"].join("\n"));
var doc = new AceAjax.Document(["1", "2", "3"].join("\r\n"));
doc.setNewLineMode("auto");
assert.equal(doc.getValue(), ["1", "2", "3"].join("\r\n"));
doc.replace(new AceAjax.Range(0, 0, 2, 1), ["4", "5", "6"].join("\n"));
assert.equal(["4", "5", "6"].join("\n"), doc.getValue());
} ,
"test: set value": function() {
var doc = new AceAjax.Document("1");
assert.equal("1", doc.getValue());
doc.setValue(doc.getValue());
assert.equal("1", doc.getValue());
var doc = new AceAjax.Document("1\n2");
assert.equal("1\n2", doc.getValue());
doc.setValue(doc.getValue());
assert.equal("1\n2", doc.getValue());
}
};
@@ -1 +0,0 @@
-920
View File
@@ -1,920 +0,0 @@
/// <reference path="../ace.d.ts" />
var lang: any;
var assert: any;
function createFoldTestSession() {
var lines = [
"function foo(items) {",
" for (var i=0; i<items.length; i++) {",
" alert(items[i] + \"juhu\");",
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"));
session.setUndoManager(new AceAjax.UndoManager());
session.addFold("args...", new AceAjax.Range(0, 13, 0, 18));
session.addFold("foo...", new AceAjax.Range(1, 10, 2, 10));
session.addFold("bar...", new AceAjax.Range(2, 20, 2, 25));
return session;
}
function assertArray(a, b) {
assert.equal(a + "", b + "");
assert.ok(a.length == b.length);
for (var i = 0; i < a.length; i++) {
assert.equal(a[i], b[i]);
}
}
var exports = {
"test: find matching opening bracket in Text mode": function() {
var session = new AceAjax.EditSession(["(()(", "())))"]);
assert.position(session.findMatchingBracket({ row: 0, column: 3 }), 0, 1);
assert.position(session.findMatchingBracket({ row: 1, column: 2 }), 1, 0);
assert.position(session.findMatchingBracket({ row: 1, column: 3 }), 0, 3);
assert.position(session.findMatchingBracket({ row: 1, column: 4 }), 0, 0);
assert.equal(session.findMatchingBracket({ row: 1, column: 5 }), null);
} ,
"test: find matching closing bracket in Text mode": function() {
var session = new AceAjax.EditSession(["(()(", "())))"]);
assert.position(session.findMatchingBracket({ row: 1, column: 1 }), 1, 1);
assert.position(session.findMatchingBracket({ row: 1, column: 1 }), 1, 1);
assert.position(session.findMatchingBracket({ row: 0, column: 4 }), 1, 2);
assert.position(session.findMatchingBracket({ row: 0, column: 2 }), 0, 2);
assert.position(session.findMatchingBracket({ row: 0, column: 1 }), 1, 3);
assert.equal(session.findMatchingBracket({ row: 0, column: 0 }), null);
} ,
"test: find matching opening bracket in JavaScript mode": function() {
var lines = [
"function foo() {",
" var str = \"{ foo()\";",
" if (debug) {",
" // write str (a string) to the console",
" console.log(str);",
" }",
" str += \" bar() }\";",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), null);
assert.position(session.findMatchingBracket({ row: 0, column: 14 }), 0, 12);
assert.position(session.findMatchingBracket({ row: 7, column: 1 }), 0, 15);
assert.position(session.findMatchingBracket({ row: 6, column: 20 }), 1, 15);
assert.position(session.findMatchingBracket({ row: 1, column: 22 }), 1, 20);
assert.position(session.findMatchingBracket({ row: 3, column: 31 }), 3, 21);
assert.position(session.findMatchingBracket({ row: 4, column: 24 }), 4, 19);
assert.equal(session.findMatchingBracket({ row: 0, column: 1 }), null);
} ,
"test: find matching closing bracket in JavaScript mode": function() {
var lines = [
"function foo() {",
" var str = \"{ foo()\";",
" if (debug) {",
" // write str (a string) to the console",
" console.log(str);",
" }",
" str += \" bar() }\";",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), null);
assert.position(session.findMatchingBracket({ row: 0, column: 13 }), 0, 13);
assert.position(session.findMatchingBracket({ row: 0, column: 16 }), 7, 0);
assert.position(session.findMatchingBracket({ row: 1, column: 16 }), 6, 19);
assert.position(session.findMatchingBracket({ row: 1, column: 21 }), 1, 21);
assert.position(session.findMatchingBracket({ row: 3, column: 22 }), 3, 30);
assert.position(session.findMatchingBracket({ row: 4, column: 20 }), 4, 23);
} ,
"test: handle unbalanced brackets in JavaScript mode": function() {
var lines = [
"function foo() {",
" var str = \"{ foo()\";",
" if (debug) {",
" // write str a string) to the console",
" console.log(str);",
" ",
" str += \" bar() \";",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), null);
assert.equal(session.findMatchingBracket({ row: 0, column: 16 }), null);
assert.equal(session.findMatchingBracket({ row: 3, column: 30 }), null);
assert.equal(session.findMatchingBracket({ row: 1, column: 16 }), null);
} ,
"test: match different bracket types": function() {
var session = new AceAjax.EditSession(["({[", ")]}"]);
assert.position(session.findMatchingBracket({ row: 0, column: 1 }), 1, 0);
assert.position(session.findMatchingBracket({ row: 0, column: 2 }), 1, 2);
assert.position(session.findMatchingBracket({ row: 0, column: 3 }), 1, 1);
assert.position(session.findMatchingBracket({ row: 1, column: 1 }), 0, 0);
assert.position(session.findMatchingBracket({ row: 1, column: 2 }), 0, 2);
assert.position(session.findMatchingBracket({ row: 1, column: 3 }), 0, 1);
} ,
"test: move lines down": function() {
var session = new AceAjax.EditSession(["a1", "a2", "a3", "a4"]);
session.moveLinesDown(0, 1);
assert.equal(session.getValue(), ["a3", "a1", "a2", "a4"].join("\n"));
session.moveLinesDown(1, 2);
assert.equal(session.getValue(), ["a3", "a4", "a1", "a2"].join("\n"));
session.moveLinesDown(2, 3);
assert.equal(session.getValue(), ["a3", "a4", "a1", "a2"].join("\n"));
session.moveLinesDown(2, 2);
assert.equal(session.getValue(), ["a3", "a4", "a2", "a1"].join("\n"));
} ,
"test: move lines up": function() {
var session = new AceAjax.EditSession(["a1", "a2", "a3", "a4"]);
session.moveLinesUp(2, 3);
assert.equal(session.getValue(), ["a1", "a3", "a4", "a2"].join("\n"));
session.moveLinesUp(1, 2);
assert.equal(session.getValue(), ["a3", "a4", "a1", "a2"].join("\n"));
session.moveLinesUp(0, 1);
assert.equal(session.getValue(), ["a3", "a4", "a1", "a2"].join("\n"));
session.moveLinesUp(2, 2);
assert.equal(session.getValue(), ["a3", "a1", "a4", "a2"].join("\n"));
} ,
"test: duplicate lines": function() {
var session = new AceAjax.EditSession(["1", "2", "3", "4"]);
session.duplicateLines(1, 2);
assert.equal(session.getValue(), ["1", "2", "3", "2", "3", "4"].join("\n"));
} ,
"test: duplicate last line": function() {
var session = new AceAjax.EditSession(["1", "2", "3"]);
session.duplicateLines(2, 2);
assert.equal(session.getValue(), ["1", "2", "3", "3"].join("\n"));
} ,
"test: duplicate first line": function() {
var session = new AceAjax.EditSession(["1", "2", "3"]);
session.duplicateLines(0, 0);
assert.equal(session.getValue(), ["1", "1", "2", "3"].join("\n"));
} ,
"test: getScreenLastRowColumn": function() {
var session = new AceAjax.EditSession([
"juhu",
"12\t\t34",
"??a"
]);
assert.equal(session.getScreenLastRowColumn(0), 4);
assert.equal(session.getScreenLastRowColumn(1), 10);
assert.equal(session.getScreenLastRowColumn(2), 5);
} ,
"test: convert document to screen coordinates": function() {
var session = new AceAjax.EditSession("01234\t567890\t1234");
session.setTabSize(4);
assert.equal(session.documentToScreenColumn(0, 0), 0);
assert.equal(session.documentToScreenColumn(0, 4), 4);
assert.equal(session.documentToScreenColumn(0, 5), 5);
assert.equal(session.documentToScreenColumn(0, 6), 8);
assert.equal(session.documentToScreenColumn(0, 12), 14);
assert.equal(session.documentToScreenColumn(0, 13), 16);
session.setTabSize(2);
assert.equal(session.documentToScreenColumn(0, 0), 0);
assert.equal(session.documentToScreenColumn(0, 4), 4);
assert.equal(session.documentToScreenColumn(0, 5), 5);
assert.equal(session.documentToScreenColumn(0, 6), 6);
assert.equal(session.documentToScreenColumn(0, 7), 7);
assert.equal(session.documentToScreenColumn(0, 12), 12);
assert.equal(session.documentToScreenColumn(0, 13), 14);
} ,
"test: convert document to screen coordinates with leading tabs": function() {
var session = new AceAjax.EditSession("\t\t123");
session.setTabSize(4);
assert.equal(session.documentToScreenColumn(0, 0), 0);
assert.equal(session.documentToScreenColumn(0, 1), 4);
assert.equal(session.documentToScreenColumn(0, 2), 8);
assert.equal(session.documentToScreenColumn(0, 3), 9);
} ,
"test: documentToScreen without soft wrap": function() {
var session = new AceAjax.EditSession([
"juhu",
"12\t\t34",
"??a"
]);
assert.position(session.documentToScreenPosition(0, 3), 0, 3);
assert.position(session.documentToScreenPosition(1, 3), 1, 4);
assert.position(session.documentToScreenPosition(1, 4), 1, 8);
assert.position(session.documentToScreenPosition(2, 2), 2, 4);
} ,
"test: documentToScreen with soft wrap": function() {
var session = new AceAjax.EditSession(["foo bar foo bar"]);
session.setUseWrapMode(true);
session.setWrapLimitRange(12, 12);
session.adjustWrapLimit(80);
assert.position(session.documentToScreenPosition(0, 11), 0, 11);
assert.position(session.documentToScreenPosition(0, 12), 1, 0);
} ,
"test: documentToScreen with soft wrap and multibyte characters": function() {
var session = new AceAjax.EditSession(["??a"]);
session.setUseWrapMode(true);
session.setWrapLimitRange(2, 2);
session.adjustWrapLimit(80);
assert.position(session.documentToScreenPosition(0, 1), 1, 0);
assert.position(session.documentToScreenPosition(0, 2), 2, 0);
assert.position(session.documentToScreenPosition(0, 4), 2, 1);
} ,
"test: documentToScreen should clip position to the document boundaries": function() {
var session = new AceAjax.EditSession("foo bar\njuhu kinners");
assert.position(session.documentToScreenPosition(-1, 4), 0, 0);
assert.position(session.documentToScreenPosition(3, 0), 1, 12);
} ,
"test: convert screen to document coordinates": function() {
var session = new AceAjax.EditSession("01234\t567890\t1234");
session.setTabSize(4);
assert.equal(session.screenToDocumentColumn(0, 0), 0);
assert.equal(session.screenToDocumentColumn(0, 4), 4);
assert.equal(session.screenToDocumentColumn(0, 5), 5);
assert.equal(session.screenToDocumentColumn(0, 6), 5);
assert.equal(session.screenToDocumentColumn(0, 7), 5);
assert.equal(session.screenToDocumentColumn(0, 8), 6);
assert.equal(session.screenToDocumentColumn(0, 9), 7);
assert.equal(session.screenToDocumentColumn(0, 15), 12);
assert.equal(session.screenToDocumentColumn(0, 19), 16);
session.setTabSize(2);
assert.equal(session.screenToDocumentColumn(0, 0), 0);
assert.equal(session.screenToDocumentColumn(0, 4), 4);
assert.equal(session.screenToDocumentColumn(0, 5), 5);
assert.equal(session.screenToDocumentColumn(0, 6), 6);
assert.equal(session.screenToDocumentColumn(0, 12), 12);
assert.equal(session.screenToDocumentColumn(0, 13), 12);
assert.equal(session.screenToDocumentColumn(0, 14), 13);
} ,
"test: screenToDocument with soft wrap": function() {
var session = new AceAjax.EditSession(["foo bar foo bar"]);
session.setUseWrapMode(true);
session.setWrapLimitRange(12, 12);
session.adjustWrapLimit(80);
assert.position(session.screenToDocumentPosition(1, 0), 0, 12);
assert.position(session.screenToDocumentPosition(0, 11), 0, 11);
// Check if the position is clamped the right way.
assert.position(session.screenToDocumentPosition(0, 12), 0, 11);
assert.position(session.screenToDocumentPosition(0, 20), 0, 11);
} ,
"test: screenToDocument with soft wrap and multi byte characters": function() {
var session = new AceAjax.EditSession(["? a"]);
session.setUseWrapMode(true);
session.adjustWrapLimit(80);
assert.position(session.screenToDocumentPosition(0, 1), 0, 0);
assert.position(session.screenToDocumentPosition(0, 2), 0, 1);
assert.position(session.screenToDocumentPosition(0, 3), 0, 2);
assert.position(session.screenToDocumentPosition(0, 4), 0, 3);
assert.position(session.screenToDocumentPosition(0, 5), 0, 3);
} ,
"test: screenToDocument should clip position to the document boundaries": function() {
var session = new AceAjax.EditSession("foo bar\njuhu kinners");
assert.position(session.screenToDocumentPosition(-1, 4), 0, 0);
assert.position(session.screenToDocumentPosition(0, -1), 0, 0);
assert.position(session.screenToDocumentPosition(0, 30), 0, 7);
assert.position(session.screenToDocumentPosition(2, 4), 1, 12);
assert.position(session.screenToDocumentPosition(1, 30), 1, 12);
assert.position(session.screenToDocumentPosition(20, 50), 1, 12);
assert.position(session.screenToDocumentPosition(20, 5), 1, 12);
// and the same for folded rows
session.addFold("...", new AceAjax.Range(0, 1, 1, 3));
assert.position(session.screenToDocumentPosition(1, 2), 1, 12);
// for wrapped rows
session.setUseWrapMode(true);
session.setWrapLimitRange(5, 5);
assert.position(session.screenToDocumentPosition(4, 1), 1, 12);
} ,
"test: wrapLine split function": function() {
function computeAndAssert(line, assertEqual, wrapLimit?, tabSize?) {
wrapLimit = wrapLimit || 12;
tabSize = tabSize || 4;
line = lang.stringTrimRight(line);
var tokens = AceAjax.EditSession.prototype.$getDisplayTokens(line);
var splits = AceAjax.EditSession.prototype.$computeWrapSplits(tokens, wrapLimit, tabSize);
// console.log("String:", line, "Result:", splits, "Expected:", assertEqual);
assert.ok(splits.length == assertEqual.length);
for (var i = 0; i < splits.length; i++) {
assert.ok(splits[i] == assertEqual[i]);
}
}
// Basic splitting.
computeAndAssert("foo bar foo bar", [12]);
computeAndAssert("foo bar f bar", [12]);
computeAndAssert("foo bar f r", [14]);
computeAndAssert("foo bar foo bar foo bara foo", [12, 25]);
// Don't split if there is only whitespaces/tabs at the end of the line.
computeAndAssert("foo foo foo \t \t", []);
// If there is no space to split, force split.
computeAndAssert("foooooooooooooo", [12]);
computeAndAssert("fooooooooooooooooooooooooooo", [12, 24]);
computeAndAssert("foo bar fooooooooooobooooooo", [8, 20]);
// Basic splitting + tabs.
computeAndAssert("foo \t\tbar", [6]);
computeAndAssert("foo \t \tbar", [7]);
// Ignore spaces/tabs at beginning of split.
computeAndAssert("foo \t \t \t \t bar", [14]);
// Test wrapping for asian characters.
computeAndAssert("??", [1], 2);
computeAndAssert(" ??", [1, 2], 2);
computeAndAssert(" ?\t?", [1, 3], 2);
computeAndAssert(" ??\t?", [1, 4], 4);
// Test wrapping for punctuation.
computeAndAssert(" ab.c;ef++", [1, 3, 5, 7, 8], 2);
computeAndAssert(" a.b", [1, 2, 3], 1);
computeAndAssert("#>>", [1, 2], 1);
} ,
"test get longest line": function() {
var session = new AceAjax.EditSession(["12"]);
session.setTabSize(4);
assert.equal(session.getScreenWidth(), 2);
session.doc.insertNewLine({ row: 0, column: Infinity });
session.doc.insertLines(1, ["123"]);
assert.equal(session.getScreenWidth(), 3);
session.doc.insertNewLine({ row: 0, column: Infinity });
session.doc.insertLines(1, ["\t\t"]);
assert.equal(session.getScreenWidth(), 8);
session.setTabSize(2);
assert.equal(session.getScreenWidth(), 4);
} ,
"test issue 83": function() {
var session = new AceAjax.EditSession("");
var editor = new AceAjax.Editor(null, session);
var document = session.getDocument();
session.setUseWrapMode(true);
document.insertLines(0, ["a", "b"]);
document.insertLines(2, ["c", "d"]);
document.removeLines(1, 2);
} ,
"test wrapMode init has to create wrapData array": function() {
var session = new AceAjax.EditSession("foo bar\nfoo bar");
var editor = new AceAjax.Editor(null, session);
var document = session.getDocument();
session.setUseWrapMode(true);
session.setWrapLimitRange(3, 3);
session.adjustWrapLimit(80);
} ,
"test first line blank with wrap": function() {
var session = new AceAjax.EditSession("\nfoo");
session.setUseWrapMode(true);
assert.equal(session.doc.getValue(), ["", "foo"].join("\n"));
} ,
"test first line blank with wrap 2": function() {
var session = new AceAjax.EditSession("");
session.setUseWrapMode(true);
session.setValue("\nfoo");
assert.equal(session.doc.getValue(), ["", "foo"].join("\n"));
} ,
"test fold getFoldDisplayLine": function() {
var session = createFoldTestSession();
function assertDisplayLine(foldLine, str) {
var line = session.getLine(foldLine.end.row);
var displayLine =
session.getFoldDisplayLine(foldLine, foldLine.end.row, line.length);
assert.equal(displayLine, str);
}
} ,
"test foldLine idxToPosition": function() {
var session = createFoldTestSession();
function assertIdx2Pos(foldLineIdx, idx, row, column) {
var foldLine = null;
assert.position(foldLine.idxToPosition(idx), row, column);
}
// "function foo(items) {",
// " for (var i=0; i<items.length; i++) {",
// " alert(items[i] + \"juhu\");",
// " } // Real Tab.",
// "}"
assertIdx2Pos(0, 12, 0, 12);
assertIdx2Pos(0, 13, 0, 13);
assertIdx2Pos(0, 14, 0, 13);
assertIdx2Pos(0, 19, 0, 13);
assertIdx2Pos(0, 20, 0, 18);
assertIdx2Pos(1, 10, 1, 10);
assertIdx2Pos(1, 11, 1, 10);
assertIdx2Pos(1, 15, 1, 10);
assertIdx2Pos(1, 16, 2, 10);
assertIdx2Pos(1, 26, 2, 20);
assertIdx2Pos(1, 27, 2, 20);
assertIdx2Pos(1, 32, 2, 25);
} ,
"test fold documentToScreen": function() {
var session = createFoldTestSession();
function assertDoc2Screen(docRow, docCol, screenRow, screenCol) {
assert.position(
session.documentToScreenPosition(docRow, docCol),
screenRow, screenCol
);
}
// One fold ending in the same row.
assertDoc2Screen(0, 0, 0, 0);
assertDoc2Screen(0, 13, 0, 13);
assertDoc2Screen(0, 14, 0, 13);
assertDoc2Screen(0, 17, 0, 13);
assertDoc2Screen(0, 18, 0, 20);
// Fold ending on some other row.
assertDoc2Screen(1, 0, 1, 0);
assertDoc2Screen(1, 10, 1, 10);
assertDoc2Screen(1, 11, 1, 10);
assertDoc2Screen(1, 99, 1, 10);
assertDoc2Screen(2, 0, 1, 10);
assertDoc2Screen(2, 9, 1, 10);
assertDoc2Screen(2, 10, 1, 16);
assertDoc2Screen(2, 11, 1, 17);
// Fold in the same row with fold over more then one row in the same row.
assertDoc2Screen(2, 19, 1, 25);
assertDoc2Screen(2, 20, 1, 26);
assertDoc2Screen(2, 21, 1, 26);
assertDoc2Screen(2, 24, 1, 26);
assertDoc2Screen(2, 25, 1, 32);
assertDoc2Screen(2, 26, 1, 33);
assertDoc2Screen(2, 99, 1, 40);
// Test one position after the folds. Should be all like normal.
assertDoc2Screen(3, 0, 2, 0);
} ,
"test fold screenToDocument": function() {
var session = createFoldTestSession();
function assertScreen2Doc(docRow, docCol, screenRow, screenCol) {
assert.position(
session.screenToDocumentPosition(screenRow, screenCol),
docRow, docCol
);
}
// One fold ending in the same row.
assertScreen2Doc(0, 0, 0, 0);
assertScreen2Doc(0, 13, 0, 13);
assertScreen2Doc(0, 13, 0, 14);
assertScreen2Doc(0, 18, 0, 20);
assertScreen2Doc(0, 19, 0, 21);
// Fold ending on some other row.
assertScreen2Doc(1, 0, 1, 0);
assertScreen2Doc(1, 10, 1, 10);
assertScreen2Doc(1, 10, 1, 11);
assertScreen2Doc(1, 10, 1, 15);
assertScreen2Doc(2, 10, 1, 16);
assertScreen2Doc(2, 11, 1, 17);
// Fold in the same row with fold over more then one row in the same row.
assertScreen2Doc(2, 19, 1, 25);
assertScreen2Doc(2, 20, 1, 26);
assertScreen2Doc(2, 20, 1, 27);
assertScreen2Doc(2, 20, 1, 31);
assertScreen2Doc(2, 25, 1, 32);
assertScreen2Doc(2, 26, 1, 33);
assertScreen2Doc(2, 33, 1, 99);
// Test one position after the folds. Should be all like normal.
assertScreen2Doc(3, 0, 2, 0);
} ,
"test getFoldsInRange()": function() {
var session = createFoldTestSession();
var foldLines = null;
var folds = foldLines[0].folds.concat(foldLines[1].folds);
function test(startRow, startColumn, endColumn, endRow, folds) {
var r = new AceAjax.Range(startRow, startColumn, endColumn, endRow);
var retFolds = session.getFoldsInRange(r);
assert.ok(retFolds.length == folds.length);
for (var i = 0; i < retFolds.length; i++) {
assert.equal(retFolds[i].range + "", folds[i].range + "");
}
}
test(0, 0, 0, 13, []);
test(0, 0, 0, 14, [folds[0]]);
test(0, 0, 0, 18, [folds[0]]);
test(0, 0, 1, 10, [folds[0]]);
test(0, 0, 1, 11, [folds[0], folds[1]]);
test(0, 18, 1, 11, [folds[1]]);
test(2, 0, 2, 13, [folds[1]]);
test(2, 10, 2, 20, []);
test(2, 10, 2, 11, []);
test(2, 19, 2, 20, []);
} ,
"test fold one-line text insert": function() {
// These are mostly test for the FoldLine.addRemoveChars function.
var session = createFoldTestSession();
var undoManager = session.getUndoManager();
var foldLines = null;
function insert(row, column, text) {
session.insert({ row: row, column: column }, text);
}
var foldLine, fold, folds;
// First line.
foldLine = null;
fold = foldLine.folds[0];
insert(0, 0, "0");
assert.range(foldLine.range, 0, 14, 0, 19);
assert.range(fold.range, 0, 14, 0, 19);
insert(0, 14, "1");
assert.range(foldLine.range, 0, 15, 0, 20);
assert.range(fold.range, 0, 15, 0, 20);
insert(0, 20, "2");
assert.range(foldLine.range, 0, 15, 0, 20);
assert.range(fold.range, 0, 15, 0, 20);
// Second line.
foldLine = null;
folds = foldLine.folds;
insert(1, 0, "3");
assert.range(foldLine.range, 1, 11, 2, 25);
assert.range(folds[0].range, 1, 11, 2, 10);
assert.range(folds[1].range, 2, 20, 2, 25);
insert(1, 11, "4");
assert.range(foldLine.range, 1, 12, 2, 25);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 20, 2, 25);
insert(2, 10, "5");
assert.range(foldLine.range, 1, 12, 2, 26);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 21, 2, 26);
insert(2, 21, "6");
assert.range(foldLine.range, 1, 12, 2, 27);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 22, 2, 27);
insert(2, 27, "7");
assert.range(foldLine.range, 1, 12, 2, 27);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 22, 2, 27);
// UNDO = REMOVE
undoManager.undo(); // 6
assert.range(foldLine.range, 1, 12, 2, 27);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 22, 2, 27);
undoManager.undo(); // 5
assert.range(foldLine.range, 1, 12, 2, 26);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 21, 2, 26);
undoManager.undo(); // 4
assert.range(foldLine.range, 1, 12, 2, 25);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 20, 2, 25);
undoManager.undo(); // 3
assert.range(foldLine.range, 1, 11, 2, 25);
assert.range(folds[0].range, 1, 11, 2, 10);
assert.range(folds[1].range, 2, 20, 2, 25);
undoManager.undo(); // Beginning first line.
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 0, 15, 0, 20);
assert.range(foldLines[1].range, 1, 10, 2, 25);
foldLine = null;
fold = foldLine.folds[0];
undoManager.undo(); // 2
assert.range(foldLine.range, 0, 15, 0, 20);
assert.range(fold.range, 0, 15, 0, 20);
undoManager.undo(); // 1
assert.range(foldLine.range, 0, 14, 0, 19);
assert.range(fold.range, 0, 14, 0, 19);
undoManager.undo(); // 0
assert.range(foldLine.range, 0, 13, 0, 18);
assert.range(fold.range, 0, 13, 0, 18);
} ,
"test fold multi-line insert/remove": function() {
var session = createFoldTestSession(),
undoManager = session.getUndoManager(),
foldLines = null;
function insert(row, column, text) {
session.insert({ row: row, column: column }, text);
}
var foldLines = null, foldLine, fold, folds;
insert(0, 0, "\nfo0");
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 2, 10, 3, 25);
insert(2, 0, "\nba1");
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 3, 13, 4, 25);
insert(3, 10, "\nfo2");
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 4, 6, 5, 25);
insert(5, 10, "\nba3");
assert.equal(foldLines.length, 3);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 4, 6, 5, 10);
assert.range(foldLines[2].range, 6, 13, 6, 18);
insert(6, 18, "\nfo4");
assert.equal(foldLines.length, 3);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 4, 6, 5, 10);
assert.range(foldLines[2].range, 6, 13, 6, 18);
undoManager.undo(); // 3
assert.equal(foldLines.length, 3);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 4, 6, 5, 10);
assert.range(foldLines[2].range, 6, 13, 6, 18);
undoManager.undo(); // 2
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 4, 6, 5, 25);
undoManager.undo(); // 1
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 3, 13, 4, 25);
undoManager.undo(); // 0
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 2, 10, 3, 25);
undoManager.undo(); // Beginning
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 0, 13, 0, 18);
assert.range(foldLines[1].range, 1, 10, 2, 25);
// TODO: Add test for inseration inside of folds.
} ,
"test fold wrap data compution": function() {
function assertWrap(line0, line1, line2) {
line0 && assertArray(wrapData[0], line0);
line1 && assertArray(wrapData[1], line1);
line2 && assertArray(wrapData[2], line2);
}
function removeFoldAssertWrap(docRow, docColumn, line0, line1, line2) {
session.removeFold(session.getFoldAt(docRow, docColumn));
assertWrap(line0, line1, line2);
}
var lines = [
"foo bar foo bar",
"foo bar foo bar",
"foo bar foo bar"
];
var session = new AceAjax.EditSession(lines.join("\n"));
session.setUseWrapMode(true);
var wrapData = null;
// Do a simple assertion without folds to check basic functionallity.
assertWrap([8], [8], [8]);
// --- Do in line folding ---
// Adding a fold. The split position is inside of the fold. As placeholder
// are not splitable, the split should be before the split.
session.addFold("woot", new AceAjax.Range(0, 4, 0, 15));
assertWrap([4], [8], [8]);
// Remove the fold again which should reset the wrapData.
removeFoldAssertWrap(0, 4, [8], [8], [8]);
session.addFold("woot", new AceAjax.Range(0, 6, 0, 9));
assertWrap([6, 13], [8], [8]);
removeFoldAssertWrap(0, 6, [8], [8], [8]);
// The fold fits into the wrap limit - no split expected.
session.addFold("woot", new AceAjax.Range(0, 3, 0, 15));
assertWrap([], [8], [8]);
removeFoldAssertWrap(0, 4, [8], [8], [8]);
// Fold after split position should be all fine.
session.addFold("woot", new AceAjax.Range(0, 8, 0, 15));
assertWrap([8], [8], [8]);
removeFoldAssertWrap(0, 8, [8], [8], [8]);
// Fold's placeholder is far too long for wrapSplit.
session.addFold("woot0123456789", new AceAjax.Range(0, 8, 0, 15));
assertWrap([8], [8], [8]);
removeFoldAssertWrap(0, 8, [8], [8], [8]);
// Fold's placeholder is far too long for wrapSplit
// + content at the end of the line
session.addFold("woot0123456789", new AceAjax.Range(0, 6, 0, 8));
assertWrap([6, 20], [8], [8]);
removeFoldAssertWrap(0, 8, [8], [8], [8]);
session.addFold("woot0123456789", new AceAjax.Range(0, 6, 0, 8));
session.addFold("woot0123456789", new AceAjax.Range(0, 8, 0, 10));
assertWrap([6, 20, 34], [8], [8]);
session.removeFold(session.getFoldAt(0, 7));
removeFoldAssertWrap(0, 8, [8], [8], [8]);
session.addFold("woot0123456789", new AceAjax.Range(0, 7, 0, 9));
session.addFold("woot0123456789", new AceAjax.Range(0, 13, 0, 15));
assertWrap([7, 21, 25], [8], [8]);
session.removeFold(session.getFoldAt(0, 7));
removeFoldAssertWrap(0, 14, [8], [8], [8]);
// --- Do some multiline folding ---
// Add a fold over two lines. Note, that the wrapData[1] stays the
// same. This is an implementation detail and expected behavior.
session.addFold("woot", new AceAjax.Range(0, 8, 1, 15));
assertWrap([8], [8 /* See comments */], [8]);
removeFoldAssertWrap(0, 8, [8], [8], [8]);
session.addFold("woot", new AceAjax.Range(0, 9, 1, 11));
assertWrap([8, 14], [8 /* See comments */], [8]);
removeFoldAssertWrap(0, 9, [8], [8], [8]);
session.addFold("woot", new AceAjax.Range(0, 9, 1, 15));
assertWrap([8], [8 /* See comments */], [8]);
removeFoldAssertWrap(0, 9, [8], [8], [8]);
return session;
} ,
"test add fold": function() {
var session = createFoldTestSession();
var fold;
function tryAddFold(placeholder, range, shouldFail) {
var fail = false;
try {
fold = session.addFold(placeholder, range);
} catch (e) {
fail = true;
}
if (fail != shouldFail) {
throw "Expected to get an exception";
}
}
tryAddFold("foo", new AceAjax.Range(0, 13, 0, 17), false);
tryAddFold("foo", new AceAjax.Range(0, 14, 0, 18), true);
tryAddFold("foo", new AceAjax.Range(0, 13, 0, 18), false);
tryAddFold("f", new AceAjax.Range(0, 13, 0, 18), false);
tryAddFold("foo", new AceAjax.Range(0, 18, 0, 21), false);
session.removeFold(fold);
tryAddFold("foo", new AceAjax.Range(0, 18, 0, 22), false);
tryAddFold("foo", new AceAjax.Range(0, 18, 0, 19), true);
tryAddFold("foo", new AceAjax.Range(0, 22, 1, 10), false);
} ,
"test add subfolds": function() {
var session = createFoldTestSession();
var fold, oldFold;
var foldData = null;
oldFold = foldData[0].folds[0];
fold = session.addFold("fold0", new AceAjax.Range(0, 10, 0, 21));
assert.equal(foldData[0].folds.length, 1);
assert.equal(fold.subFolds.length, 1);
assert.equal(fold.subFolds[0], oldFold);
session.expandFold(fold);
assert.equal(foldData[0].folds.length, 1);
assert.equal(foldData[0].folds[0], oldFold);
assert.equal(fold.subFolds.length, 0);
fold = session.addFold("fold0", new AceAjax.Range(0, 13, 2, 10));
assert.equal(foldData.length, 1);
assert.equal(fold.subFolds.length, 2);
assert.equal(fold.subFolds[0], oldFold);
session.expandFold(fold);
assert.equal(foldData.length, 2);
assert.equal(foldData[0].folds.length, 1);
assert.equal(foldData[0].folds[0], oldFold);
assert.equal(fold.subFolds.length, 0);
session.unfold(null, true);
fold = session.addFold("fold0", new AceAjax.Range(0, 0, 0, 21));
session.addFold("fold0", new AceAjax.Range(0, 1, 0, 5));
session.addFold("fold0", new AceAjax.Range(0, 6, 0, 8));
assert.equal(fold.subFolds.length, 2);
} ,
"test row cache": function() {
var session = createFoldTestSession();
session.screenToDocumentPosition(2, 3);
session.screenToDocumentPosition(5, 3);
session.screenToDocumentPosition(0, 3);
var pos = session.screenToDocumentPosition(0, 0);
assert.equal(pos.row, 0);
session.screenToDocumentPosition(1, 0);
session.screenToDocumentPosition(1, 3);
session.screenToDocumentPosition(5, 3);
session = new AceAjax.EditSession(new Array(30).join("\n"));
session.documentToScreenPosition(2, 0);
session.documentToScreenPosition(2, 0);
}
};
@@ -1 +0,0 @@
-154
View File
@@ -1,154 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var exports = {
setUp: function(next) {
this.session1 = new AceAjax.EditSession(["abc", "def"]);
this.session2 = new AceAjax.EditSession(["ghi", "jkl"]);
var editor = new AceAjax.Editor(null);
next();
} ,
"test: change document": function() {
var editor = new AceAjax.Editor(null);
editor.setSession(this.session1);
assert.equal(editor.getSession(), this.session1);
editor.setSession(this.session2);
assert.equal(editor.getSession(), this.session2);
} ,
"test: only changes to the new document should have effect": function () {
var editor = new AceAjax.Editor(null);
var called = false;
editor.onDocumentChange = function () {
called = true;
};
editor.setSession(this.session1);
editor.setSession(this.session2);
this.session1.duplicateLines(0, 0);
assert.notOk(called);
this.session2.duplicateLines(0, 0);
assert.ok(called);
} ,
"test: should use cursor of new document": function () {
var editor = new AceAjax.Editor(null);
this.session1.getSelection().moveCursorTo(0, 1);
this.session2.getSelection().moveCursorTo(1, 0);
editor.setSession(this.session1);
assert.position(editor.getCursorPosition(), 0, 1);
editor.setSession(this.session2);
assert.position(editor.getCursorPosition(), 1, 0);
} ,
"test: only changing the cursor of the new doc should not have an effect": function () {
var editor = new AceAjax.Editor(null);
editor.onCursorChange = function () {
called = true;
};
editor.setSession(this.session1);
editor.setSession(this.session2);
assert.position(editor.getCursorPosition(), 0, 0);
var called = false;
this.session1.getSelection().moveCursorTo(0, 1);
assert.position(editor.getCursorPosition(), 0, 0);
assert.notOk(called);
this.session2.getSelection().moveCursorTo(1, 1);
assert.position(editor.getCursorPosition(), 1, 1);
assert.ok(called);
} ,
"test: should use selection of new document": function () {
var editor = new AceAjax.Editor(null);
this.session1.getSelection().selectTo(0, 1);
this.session2.getSelection().selectTo(1, 0);
editor.setSession(this.session1);
assert.position(editor.getSelection().getSelectionLead(), 0, 1);
editor.setSession(this.session2);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
} ,
"test: only changing the selection of the new doc should not have an effect": function () {
var editor = new AceAjax.Editor(null);
editor.onSelectionChange = function () {
called = true;
};
editor.setSession(this.session1);
editor.setSession(this.session2);
assert.position(editor.getSelection().getSelectionLead(), 0, 0);
var called = false;
this.session1.getSelection().selectTo(0, 1);
assert.position(editor.getSelection().getSelectionLead(), 0, 0);
assert.notOk(called);
this.session2.getSelection().selectTo(1, 1);
assert.position(editor.getSelection().getSelectionLead(), 1, 1);
assert.ok(called);
} ,
"test: should use mode of new document": function () {
var editor = new AceAjax.Editor(null);
editor.onChangeMode = function () {
called = true;
};
editor.setSession(this.session1);
editor.setSession(this.session2);
var called = false;
this.session1.setMode(new Text());
assert.notOk(called);
this.session2.setMode(null);
assert.ok(called);
} ,
"test: should use stop worker of old document": function (next) {
var editor = new AceAjax.Editor(null);
var self = this;
// 1. Open an editor and set the session to CssMode
self.editor.setSession(self.session1);
self.session1.setMode(null);
// 2. Add a line or two of valid CSS.
self.session1.setValue("DIV { color: red; }");
// 3. Clear the session value.
self.session1.setValue("");
// 4. Set the session to HtmlMode
self.session1.setMode(null);
// 5. Try to type valid HTML
self.session1.insert({ row: 0, column: 0 }, "<html></html>");
setTimeout(function () {
assert.equal(Object.keys(self.session1.getAnnotations()).length, 0);
next();
}, 600);
}
};
-1
View File
@@ -1 +0,0 @@
@@ -1,217 +0,0 @@
/// <reference path="../ace.d.ts" />
var lipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Mauris at arcu mi, eu lobortis mauris. Quisque ut libero eget " +
"diam congue vehicula. Quisque ut odio ut mi aliquam tincidunt. " +
"Duis lacinia aliquam lorem eget eleifend. Morbi eget felis mi. " +
"Duis quam ligula, consequat vitae convallis volutpat, blandit " +
"nec neque. Nulla facilisi. Etiam suscipit lorem ac justo " +
"sollicitudin tristique. Phasellus ut posuere nunc. Aliquam " +
"scelerisque mollis felis non gravida. Vestibulum lacus sem, " +
"posuere non bibendum id, luctus non dolor. Aenean id metus " +
"lorem, vel dapibus est. Donec gravida feugiat augue nec " +
"accumsan.Lorem ipsum dolor sit amet, consectetur adipiscing " +
"elit. Nulla vulputate, velit vitae tincidunt congue, nunc " +
"augue accumsan velit, eu consequat turpis lectus ac orci. " +
"Pellentesque ornare dolor feugiat dui auctor eu varius nulla " +
"fermentum. Sed aliquam odio at velit lacinia vel fermentum " +
"felis sodales. In dignissim magna eget nunc lobortis non " +
"fringilla nibh ullamcorper. Donec facilisis malesuada elit " +
"at egestas. Etiam bibendum, diam vitae tempor aliquet, dui " +
"libero vehicula odio, eget bibendum mauris velit eu lorem.\n" +
"consectetur";
function callHighlighterUpdate(session: AceAjax.IEditSession, firstRow: number, lastRow: number) {
var rangeCount = 0;
var mockMarkerLayer = { drawSingleLineMarker: function () { rangeCount++; } }
return rangeCount;
}
var assert: any;
var renderer: AceAjax.VirtualRenderer;
var exports = {
setUp: function(next) {
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(renderer, session);
var selection = session.getSelection();
next();
} ,
"test: highlight selected words by default": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(renderer, session);
assert.equal(editor.getHighlightSelectedWord(), true);
} ,
"test: highlight a word": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 9);
selection.selectWord();
var highlighter = null;
assert.ok(highlighter != null);
var range = selection.getRange();
assert.equal(session.getTextRange(range), "ipsum");
assert.equal(highlighter.cache.length, 0);
assert.equal(callHighlighterUpdate(session, 0, 0), 2);
} ,
"test: highlight a word and clear highlight": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 8);
selection.selectWord();
var range = selection.getRange();
assert.equal(session.getTextRange(range), "ipsum");
assert.equal(callHighlighterUpdate(session, 0, 0), 2);
session.highlight("");
assert.equal(callHighlighterUpdate(session, 0, 0), 0);
} ,
"test: highlight another word": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(renderer, session);
selection.moveCursorTo(0, 14);
selection.selectWord();
var range = selection.getRange();
assert.equal(session.getTextRange(range), "dolor");
assert.equal(callHighlighterUpdate(session, 0, 0), 4);
} ,
"test: no selection, no highlight": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(renderer, session);
selection.clearSelection();
assert.equal(callHighlighterUpdate(session, 0, 0), 0);
} ,
"test: select a word, no highlight": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(renderer, session);
selection.moveCursorTo(0, 14);
selection.selectWord();
editor.setHighlightSelectedWord(false);
var range = selection.getRange();
assert.equal(session.getTextRange(range), "dolor");
assert.equal(callHighlighterUpdate(session, 0, 0), 0);
} ,
"test: select a word with no matches": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(renderer, session);
editor.setHighlightSelectedWord(true);
var currentOptions = this.search.getOptions();
var newOptions = {
wrap: true,
wholeWord: true,
caseSensitive: true,
needle: "Mauris"
};
this.search.set(newOptions);
var match = this.search.find(session);
assert.notEqual(match, null, "found a match for 'Mauris'");
this.search.set(currentOptions);
selection.setSelectionRange(match);
assert.equal(session.getTextRange(match), "Mauris");
assert.equal(callHighlighterUpdate(session, 0, 0), 1);
} ,
"test: partial word selection 1": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(renderer, session);
selection.moveCursorTo(0, 14);
selection.selectWord();
selection.selectLeft();
var range = selection.getRange();
assert.equal(session.getTextRange(range), "dolo");
assert.equal(callHighlighterUpdate(session, 0, 0), 0);
} ,
"test: partial word selection 2": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(renderer, session);
selection.moveCursorTo(0, 13);
selection.selectWord();
selection.selectRight();
var range = selection.getRange();
assert.equal(session.getTextRange(range), "dolor ");
assert.equal(callHighlighterUpdate(session, 0, 0), 0);
} ,
"test: partial word selection 3": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(renderer, session);
selection.moveCursorTo(0, 14);
selection.selectWord();
selection.selectLeft();
selection.shiftSelection(1);
var range = selection.getRange();
assert.equal(session.getTextRange(range), "olor");
assert.equal(callHighlighterUpdate(session, 0, 0), 0);
} ,
"test: select last word": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(renderer, session);
selection.moveCursorTo(0, 1);
var currentOptions = this.search.getOptions();
var newOptions = {
wrap: true,
wholeWord: true,
caseSensitive: true,
backwards: true,
needle: "consectetur"
};
this.search.set(newOptions);
var match = this.search.find(session);
assert.notEqual(match, null, "found a match for 'consectetur'");
assert.position(match.start, 1, 0);
this.search.set(currentOptions);
selection.setSelectionRange(match);
assert.equal(session.getTextRange(match), "consectetur");
assert.equal(callHighlighterUpdate(session, 0, 1), 3);
}
};
-119
View File
@@ -1,119 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var renderer: AceAjax.VirtualRenderer;
var exports = {
createEditSession: function (rows, cols) {
var line = new Array(cols + 1).join("a");
var text = new Array(rows).join(line + "\n") + line;
return new AceAjax.EditSession(text);
},
"test: navigate to end of file should scroll the last line into view": function () {
var doc = this.createEditSession(200, 10);
var editor = new AceAjax.Editor(renderer, doc);
editor.navigateFileEnd();
var cursor = editor.getCursorPosition();
assert.ok(editor.getFirstVisibleRow() <= cursor.row);
assert.ok(editor.getLastVisibleRow() >= cursor.row);
},
"test: navigate to start of file should scroll the first row into view": function () {
var doc = this.createEditSession(200, 10);
var editor = new AceAjax.Editor(renderer, doc);
editor.moveCursorTo(editor.getLastVisibleRow() + 20);
editor.navigateFileStart();
assert.equal(editor.getFirstVisibleRow(), 0);
},
"test: goto hidden line should scroll the line into the middle of the viewport": function () {
var editor = new AceAjax.Editor(renderer, this.createEditSession(200, 5));
editor.navigateTo(0, 0);
editor.gotoLine(101);
assert.position(editor.getCursorPosition(), 100, 0);
assert.equal(editor.getFirstVisibleRow(), 89);
editor.navigateTo(100, 0);
editor.gotoLine(11);
assert.position(editor.getCursorPosition(), 10, 0);
assert.equal(editor.getFirstVisibleRow(), 0);
editor.navigateTo(100, 0);
editor.gotoLine(6);
assert.position(editor.getCursorPosition(), 5, 0);
assert.equal(0, editor.getFirstVisibleRow(), 0);
editor.navigateTo(100, 0);
editor.gotoLine(1);
assert.position(editor.getCursorPosition(), 0, 0);
assert.equal(editor.getFirstVisibleRow(), 0);
editor.navigateTo(0, 0);
editor.gotoLine(191);
assert.position(editor.getCursorPosition(), 190, 0);
assert.equal(editor.getFirstVisibleRow(), 179);
editor.navigateTo(0, 0);
editor.gotoLine(196);
assert.position(editor.getCursorPosition(), 195, 0);
assert.equal(editor.getFirstVisibleRow(), 180);
},
"test: goto visible line should only move the cursor and not scroll": function () {
var editor = new AceAjax.Editor(renderer, this.createEditSession(200, 5));
editor.navigateTo(0, 0);
editor.gotoLine(12);
assert.position(editor.getCursorPosition(), 11, 0);
assert.equal(editor.getFirstVisibleRow(), 0);
editor.navigateTo(30, 0);
editor.gotoLine(33);
assert.position(editor.getCursorPosition(), 32, 0);
assert.equal(editor.getFirstVisibleRow(), 30);
},
"test: navigate from the end of a long line down to a short line and back should maintain the curser column": function () {
var editor = new AceAjax.Editor(renderer, new AceAjax.EditSession(["123456", "1"]));
editor.navigateTo(0, 6);
assert.position(editor.getCursorPosition(), 0, 6);
editor.navigateDown();
assert.position(editor.getCursorPosition(), 1, 1);
editor.navigateUp();
assert.position(editor.getCursorPosition(), 0, 6);
},
"test: reset desired column on navigate left or right": function () {
var editor = new AceAjax.Editor(renderer, new AceAjax.EditSession(["123456", "12"]));
editor.navigateTo(0, 6);
assert.position(editor.getCursorPosition(), 0, 6);
editor.navigateDown();
assert.position(editor.getCursorPosition(), 1, 2);
editor.navigateLeft();
assert.position(editor.getCursorPosition(), 1, 1);
editor.navigateUp();
assert.position(editor.getCursorPosition(), 0, 1);
},
"test: typing text should update the desired column": function () {
var editor = new AceAjax.Editor(renderer, new AceAjax.EditSession(["1234", "1234567890"]));
editor.navigateTo(0, 3);
editor.insert("juhu");
editor.navigateDown();
assert.position(editor.getCursorPosition(), 1, 7);
}
};
@@ -1 +0,0 @@
-501
View File
@@ -1,501 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var renderer: AceAjax.VirtualRenderer;
var mode: any;
var exports = {
"test: delete line from the middle": function () {
var session = new AceAjax.EditSession(["a", "b", "c", "d"].join("\n"));
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.removeLines();
assert.equal(session.toString(), "a\nc\nd");
assert.position(editor.getCursorPosition(), 1, 0);
editor.removeLines();
assert.equal(session.toString(), "a\nd");
assert.position(editor.getCursorPosition(), 1, 0);
editor.removeLines();
assert.equal(session.toString(), "a");
assert.position(editor.getCursorPosition(), 0, 1);
editor.removeLines();
assert.equal(session.toString(), "");
assert.position(editor.getCursorPosition(), 0, 0);
},
"test: delete multiple selected lines": function () {
var session = new AceAjax.EditSession(["a", "b", "c", "d"].join("\n"));
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.removeLines();
assert.equal(session.toString(), "a\nd");
assert.position(editor.getCursorPosition(), 1, 0);
},
"test: delete first line": function () {
var session = new AceAjax.EditSession(["a", "b", "c"].join("\n"));
var editor = new AceAjax.Editor(renderer, session);
editor.removeLines();
assert.equal(session.toString(), "b\nc");
assert.position(editor.getCursorPosition(), 0, 0);
},
"test: delete last should also delete the new line of the previous line": function () {
var session = new AceAjax.EditSession(["a", "b", "c", ""].join("\n"));
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(3, 0);
editor.removeLines();
assert.equal(session.toString(), "a\nb\nc");
assert.position(editor.getCursorPosition(), 2, 1);
editor.removeLines();
assert.equal(session.toString(), "a\nb");
assert.position(editor.getCursorPosition(), 1, 1);
},
"test: indent block": function () {
var session = new AceAjax.EditSession(["a12345", "b12345", "c12345"].join("\n"));
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 3);
editor.getSelection().selectDown();
editor.indent();
assert.equal(["a12345", " b12345", " c12345"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 7);
var range = editor.getSelectionRange();
assert.position(range.start, 1, 7);
assert.position(range.end, 2, 7);
},
"test: indent selected lines": function () {
var session = new AceAjax.EditSession(["a12345", "b12345", "c12345"].join("\n"));
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.getSelection().selectDown();
editor.indent();
assert.equal(["a12345", " b12345", "c12345"].join("\n"), session.toString());
},
"test: no auto indent if cursor is before the {": function () {
var session = new AceAjax.EditSession("{",mode);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 0);
editor.onTextInput("\n");
assert.equal(["", "{"].join("\n"), session.toString());
},
"test: outdent block": function () {
var session = new AceAjax.EditSession([" a12345", " b12345", " c12345"].join("\n"));
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 5);
editor.getSelection().selectDown();
editor.getSelection().selectDown();
editor.blockOutdent();
assert.equal(session.toString(), [" a12345", "b12345", " c12345"].join("\n"));
assert.position(editor.getCursorPosition(), 2, 1);
var range = editor.getSelectionRange();
assert.position(range.start, 0, 1);
assert.position(range.end, 2, 1);
editor.blockOutdent();
assert.equal(session.toString(), ["a12345", "b12345", "c12345"].join("\n"));
var range = editor.getSelectionRange();
assert.position(range.start, 0, 0);
assert.position(range.end, 2, 0);
},
"test: outent without a selection should update cursor": function () {
var session = new AceAjax.EditSession(" 12");
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 3);
editor.blockOutdent(" ");
assert.equal(session.toString(), " 12");
assert.position(editor.getCursorPosition(), 0, 0);
},
"test: comment lines should perserve selection": function () {
var session = new AceAjax.EditSession([" abc", "cde"].join("\n"),mode);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 2);
editor.getSelection().selectDown();
editor.toggleCommentLines();
assert.equal(["// abc", "//cde"].join("\n"), session.toString());
var selection = editor.getSelectionRange();
assert.position(selection.start, 0, 4);
assert.position(selection.end, 1, 4);
},
"test: uncomment lines should perserve selection": function () {
var session = new AceAjax.EditSession(["// abc", "//cde"].join("\n"),mode);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 1);
editor.getSelection().selectDown();
editor.getSelection().selectRight();
editor.getSelection().selectRight();
editor.toggleCommentLines();
assert.equal([" abc", "cde"].join("\n"), session.toString());
assert.range(editor.getSelectionRange(), 0, 0, 1, 1);
},
"test: toggle comment lines twice should return the original text": function () {
var session = new AceAjax.EditSession([" abc", "cde", "fg"], mode);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 0);
editor.getSelection().selectDown();
editor.getSelection().selectDown();
editor.toggleCommentLines();
editor.toggleCommentLines();
assert.equal([" abc", "cde", "fg"].join("\n"), session.toString());
},
"test: comment lines - if the selection end is at the line start it should stay there": function () {
//select down
var session = new AceAjax.EditSession(["abc", "cde"].join("\n"),mode);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 0);
editor.getSelection().selectDown();
editor.toggleCommentLines();
assert.range(editor.getSelectionRange(), 0, 2, 1, 0);
// select up
var session = new AceAjax.EditSession(["abc", "cde"].join("\n"),mode);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.getSelection().selectUp();
editor.toggleCommentLines();
assert.range(editor.getSelectionRange(), 0, 2, 1, 0);
},
"test: move lines down should select moved lines": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(0, 1);
editor.getSelection().selectDown();
editor.moveLinesDown();
assert.equal(["33", "11", "22", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 1, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 0);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
editor.moveLinesDown();
assert.equal(["33", "44", "11", "22"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 2);
assert.position(editor.getSelection().getSelectionLead(), 2, 0);
// moving again should have no effect
editor.moveLinesDown();
assert.equal(["33", "44", "11", "22"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 2);
assert.position(editor.getSelection().getSelectionLead(), 2, 0);
},
"test: move lines up should select moved lines": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(2, 1);
editor.getSelection().selectDown();
editor.moveLinesUp();
assert.equal(session.toString(), ["11", "33", "44", "22"].join("\n"));
assert.position(editor.getCursorPosition(), 1, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 0);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
editor.moveLinesUp();
assert.equal(session.toString(), ["33", "44", "11", "22"].join("\n"));
assert.position(editor.getCursorPosition(), 0, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 2, 0);
assert.position(editor.getSelection().getSelectionLead(), 0, 0);
},
"test: move line without active selection should not move cursor relative to the moved line": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.clearSelection();
editor.moveLinesDown();
assert.equal(["11", "33", "22", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 1);
editor.clearSelection();
editor.moveLinesUp();
assert.equal(["11", "22", "33", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 1, 1);
},
"test: copy lines down should select lines and place cursor at the selection start": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.copyLinesDown();
assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 3, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 5, 0);
assert.position(editor.getSelection().getSelectionLead(), 3, 0);
},
"test: copy lines up should select lines and place cursor at the selection start": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.copyLinesUp();
assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 1, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 0);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
},
"test: input a tab with soft tab should convert it to spaces": function () {
var session = new AceAjax.EditSession("");
var editor = new AceAjax.Editor(renderer, session);
session.setTabSize(2);
session.setUseSoftTabs(true);
editor.onTextInput("\t");
assert.equal(session.toString(), " ");
session.setTabSize(5);
editor.onTextInput("\t");
assert.equal(session.toString(), " ");
},
"test: input tab without soft tabs should keep the tab character": function () {
var session = new AceAjax.EditSession("");
var editor = new AceAjax.Editor(renderer, session);
session.setUseSoftTabs(false);
editor.onTextInput("\t");
assert.equal(session.toString(), "\t");
},
"test: undo/redo for delete line": function () {
var session = new AceAjax.EditSession(["111", "222", "333"]);
var undoManager = new AceAjax.UndoManager();
session.setUndoManager(undoManager);
var initialText = session.toString();
var editor = new AceAjax.Editor(renderer, session);
editor.removeLines();
var step1 = session.toString();
assert.equal(step1, "222\n333");
editor.removeLines();
var step2 = session.toString();
assert.equal(step2, "333");
editor.removeLines();
var step3 = session.toString();
assert.equal(step3, "");
undoManager.undo();
assert.equal(session.toString(), step2);
undoManager.undo();
assert.equal(session.toString(), step1);
undoManager.undo();
assert.equal(session.toString(), initialText);
undoManager.undo();
assert.equal(session.toString(), initialText);
},
"test: remove left should remove character left of the cursor": function () {
var session = new AceAjax.EditSession(["123", "456"]);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.remove("left");
assert.equal(session.toString(), "123\n56");
},
"test: remove left should remove line break if cursor is at line start": function () {
var session = new AceAjax.EditSession(["123", "456"]);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.remove("left");
assert.equal(session.toString(), "123456");
},
"test: remove left should remove tabsize spaces if cursor is on a tab stop and preceeded by spaces": function () {
var session = new AceAjax.EditSession(["123", " 456"]);
session.setUseSoftTabs(true);
session.setTabSize(4);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 8);
editor.remove("left");
assert.equal(session.toString(), "123\n 456");
},
"test: transpose at line start should be a noop": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4567", "89"].join("\n"));
},
"test: transpose in line should swap the charaters before and after the cursor": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 2);
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4657", "89"].join("\n"));
},
"test: transpose at line end should swap the last two characters": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 4);
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4576", "89"].join("\n"));
},
"test: transpose with non empty selection should be a noop": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 1);
editor.getSelection().selectRight();
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4567", "89"].join("\n"));
},
"test: transpose should move the cursor behind the last swapped character": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 2);
editor.transposeLetters();
assert.position(editor.getCursorPosition(), 1, 3);
},
"test: remove to line end": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 2);
editor.removeToLineEnd();
assert.equal(session.getValue(), ["123", "45", "89"].join("\n"));
},
"test: remove to line end at line end should remove the new line": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 4);
editor.removeToLineEnd();
assert.position(editor.getCursorPosition(), 1, 4);
assert.equal(session.getValue(), ["123", "456789"].join("\n"));
},
"test: transform selection to uppercase": function () {
var session = new AceAjax.EditSession(["ajax", "dot", "org"]);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.getSelection().selectLineEnd();
editor.toUpperCase()
assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n"));
},
"test: transform word to uppercase": function () {
var session = new AceAjax.EditSession(["ajax", "dot", "org"]);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.toUpperCase()
assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n"));
assert.position(editor.getCursorPosition(), 1, 0);
},
"test: transform selection to lowercase": function () {
var session = new AceAjax.EditSession(["AJAX", "DOT", "ORG"]);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.getSelection().selectLineEnd();
editor.toLowerCase()
assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n"));
},
"test: transform word to lowercase": function () {
var session = new AceAjax.EditSession(["AJAX", "DOT", "ORG"]);
var editor = new AceAjax.Editor(renderer, session);
editor.moveCursorTo(1, 0);
editor.toLowerCase()
assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n"));
assert.position(editor.getCursorPosition(), 1, 0);
}
};
-114
View File
@@ -1,114 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var editor: any;
var renderer: any;
var exec = function (name?, times?, args?) {
do {
editor.commands.exec(name, editor, args);
} while (times-- > 1)
};
var testRanges = function (str) {
assert.equal(editor.selection.getAllRanges() + "", str + "");
}
var exports = {
name: "ACE multi_select.js",
"test: multiselect editing": function() {
var doc = new AceAjax.EditSession([
"w1.w2",
" wtt.w",
" wtt.w"
]);
editor = new AceAjax.Editor(renderer, doc);
editor.navigateFileEnd();
exec("selectMoreBefore", 3);
assert.ok(editor.inMultiSelectMode);
assert.equal(editor.selection.getAllRanges().length, 4);
var newLine = editor.session.getDocument().getNewLineCharacter();
var copyText = "wwww".split("").join(newLine);
assert.equal(editor.getCopyText(), copyText);
exec("insertstring", 1, "a");
exec("backspace", 2);
assert.equal(editor.session.getValue(), "w1.w2\ntt\ntt");
assert.equal(editor.selection.getAllRanges().length, 4);
exec("selectall");
assert.ok(!editor.inMultiSelectMode);
//assert.equal(editor.selection.getAllRanges().length, 1);
} ,
"test: multiselect navigation": function() {
var doc = new AceAjax.EditSession([
"w1.w2",
" wtt.w",
" wtt.we"
]);
editor = new AceAjax.Editor(renderer, doc);
editor.selectMoreLines(1);
testRanges("Range: [0/0] -> [0/0],Range: [1/0] -> [1/0]");
assert.ok(editor.inMultiSelectMode);
exec("golinedown");
exec("gotolineend");
testRanges("Range: [1/9] -> [1/9],Range: [2/10] -> [2/10]");
exec("selectwordleft");
testRanges("Range: [1/8] -> [1/9],Range: [2/8] -> [2/10]");
exec("golinedown", 2);
assert.ok(!editor.inMultiSelectMode);
} ,
"test: multiselect session change": function() {
var doc = new AceAjax.EditSession([
"w1.w2",
" wtt.w",
" wtt.w"
]);
editor = new AceAjax.Editor(renderer, doc);
editor.selectMoreLines(1)
testRanges("Range: [0/0] -> [0/0],Range: [1/0] -> [1/0]");
assert.ok(editor.inMultiSelectMode);
var doc2 = new AceAjax.EditSession(["w1"]);
editor.setSession(doc2);
assert.ok(!editor.inMultiSelectMode);
editor.setSession(doc);
assert.ok(editor.inMultiSelectMode);
} ,
"test: multiselect addRange": function() {
var doc = new AceAjax.EditSession([
"w1.w2",
" wtt.w",
" wtt.w"
]);
editor = new AceAjax.Editor(renderer, doc);
var selection = editor.selection;
var range1 = new AceAjax.Range(0, 2, 0, 4);
editor.selection.fromOrientedRange(range1);
var range2 = new AceAjax.Range(0, 3, 0, 4);
selection.addRange(range2);
assert.ok(!editor.inMultiSelectMode);
assert.ok(range2.isEqual(editor.selection.getRange()));
var range3 = new AceAjax.Range(0, 1, 0, 1);
selection.addRange(range3);
assert.ok(editor.inMultiSelectMode);
testRanges([range3, range2]);
var range4 = new AceAjax.Range(0, 0, 4, 0);
selection.addRange(range4);
assert.ok(!editor.inMultiSelectMode);
}
};
@@ -1 +0,0 @@
-109
View File
@@ -1,109 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var renderer: AceAjax.VirtualRenderer;
var mode: any;
var exports = {
"test: simple at the end appending of text": function () {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode);
var editor = new AceAjax.Editor(renderer, session);
new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
editor.moveCursorTo(0, 5);
editor.insert('b');
assert.equal(session.doc.getValue(), "var ab = 10;\nconsole.log(ab, ab);");
editor.insert('cd');
assert.equal(session.doc.getValue(), "var abcd = 10;\nconsole.log(abcd, abcd);");
editor.remove('left');
editor.remove('left');
editor.remove('left');
assert.equal(session.doc.getValue(), "var a = 10;\nconsole.log(a, a);");
},
"test: inserting text outside placeholder": function () {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);\n", mode);
var editor = new AceAjax.Editor(renderer, session);
new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
editor.moveCursorTo(2, 0);
editor.insert('b');
assert.equal(session.doc.getValue(), "var a = 10;\nconsole.log(a, a);\nb");
},
"test: insertion at the beginning": function (next) {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode);
var editor = new AceAjax.Editor(renderer, session);
var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
editor.moveCursorTo(0, 4);
editor.insert('$');
assert.equal(session.doc.getValue(), "var $a = 10;\nconsole.log($a, $a);");
editor.moveCursorTo(0, 4);
// Have to put this in a setTimeout because the anchor is only fixed later.
setTimeout(function () {
editor.insert('v');
assert.equal(session.doc.getValue(), "var v$a = 10;\nconsole.log(v$a, v$a);");
next();
}, 10);
},
"test: detaching placeholder": function () {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode);
var editor = new AceAjax.Editor(renderer, session);
var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
editor.moveCursorTo(0, 5);
editor.insert('b');
assert.equal(session.doc.getValue(), "var ab = 10;\nconsole.log(ab, ab);");
p.detach();
editor.insert('cd');
assert.equal(session.doc.getValue(), "var abcd = 10;\nconsole.log(ab, ab);");
},
"test: events": function () {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode);
var editor = new AceAjax.Editor(renderer, session);
var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
var entered = false;
var left = false;
p.on("cursorEnter", function () {
entered = true;
});
p.on("cursorLeave", function () {
left = true;
});
editor.moveCursorTo(0, 0);
editor.moveCursorTo(0, 4);
p.onCursorChange(); // Have to do this by hand because moveCursorTo doesn't trigger the event
assert.ok(entered);
editor.moveCursorTo(1, 0);
p.onCursorChange(); // Have to do this by hand because moveCursorTo doesn't trigger the event
assert.ok(left);
},
"test: cancel": function (next) {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", mode);
session.setUndoManager(new AceAjax.UndoManager());
var editor = new AceAjax.Editor(renderer, session);
var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
editor.moveCursorTo(0, 5);
editor.insert('b');
editor.insert('cd');
editor.remove('left');
assert.equal(session.doc.getValue(), "var abc = 10;\nconsole.log(abc, abc);");
// Wait a little for the changes to enter the undo stack
setTimeout(function () {
p.cancel();
assert.equal(session.doc.getValue(), "var a = 10;\nconsole.log(a, a);");
next();
}, 80);
}
};
@@ -1 +0,0 @@
-147
View File
@@ -1,147 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var exports = {
name: "ACE range.js",
"test: create range": function () {
var range = new AceAjax.Range(1, 2, 3, 4);
assert.equal(range.start.row, 1);
assert.equal(range.start.column, 2);
assert.equal(range.end.row, 3);
assert.equal(range.end.column, 4);
},
"test: create from points": function () {
var range = AceAjax.Range.fromPoints({ row: 1, column: 2 }, { row: 3, column: 4 });
assert.equal(range.start.row, 1);
assert.equal(range.start.column, 2);
assert.equal(range.end.row, 3);
assert.equal(range.end.column, 4);
},
"test: clip to rows": function () {
assert.range(new AceAjax.Range(0, 20, 100, 30).clipRows(10, 30), 10, 0, 31, 0);
assert.range(new AceAjax.Range(0, 20, 30, 10).clipRows(10, 30), 10, 0, 30, 10);
var range = new AceAjax.Range(0, 20, 3, 10);
var range = range.clipRows(10, 30);
assert.ok(range.isEmpty());
assert.range(range, 10, 0, 10, 0);
},
"test: isEmpty": function () {
var range = new AceAjax.Range(1, 2, 1, 2);
assert.ok(range.isEmpty());
var range = new AceAjax.Range(1, 2, 1, 6);
assert.notOk(range.isEmpty());
},
"test: is multi line": function () {
var range = new AceAjax.Range(1, 2, 1, 6);
assert.notOk(range.isMultiLine());
var range = new AceAjax.Range(1, 2, 2, 6);
assert.ok(range.isMultiLine());
},
"test: clone": function () {
var range = new AceAjax.Range(1, 2, 3, 4);
var clone = range.clone();
assert.position(clone.start, 1, 2);
assert.position(clone.end, 3, 4);
clone.start.column = 20;
assert.position(range.start, 1, 2);
clone.end.column = 20;
assert.position(range.end, 3, 4);
},
"test: contains for multi line ranges": function () {
var range = new AceAjax.Range(1, 10, 5, 20);
assert.ok(range.contains(1, 10));
assert.ok(range.contains(2, 0));
assert.ok(range.contains(3, 100));
assert.ok(range.contains(5, 19));
assert.ok(range.contains(5, 20));
assert.notOk(range.contains(1, 9));
assert.notOk(range.contains(0, 0));
assert.notOk(range.contains(5, 21));
},
"test: contains for single line ranges": function () {
var range = new AceAjax.Range(1, 10, 1, 20);
assert.ok(range.contains(1, 10));
assert.ok(range.contains(1, 15));
assert.ok(range.contains(1, 20));
assert.notOk(range.contains(0, 9));
assert.notOk(range.contains(2, 9));
assert.notOk(range.contains(1, 9));
assert.notOk(range.contains(1, 21));
},
"test: extend range": function () {
var range = new AceAjax.Range(2, 10, 2, 30);
var range = range.extend(2, 5);
assert.range(range, 2, 5, 2, 30);
var range = range.extend(2, 35);
assert.range(range, 2, 5, 2, 35);
var range = range.extend(2, 15);
assert.range(range, 2, 5, 2, 35);
var range = range.extend(1, 4);
assert.range(range, 1, 4, 2, 35);
var range = range.extend(6, 10);
assert.range(range, 1, 4, 6, 10);
},
"test: collapse rows": function () {
var range = new AceAjax.Range(0, 2, 1, 2);
assert.range(range.collapseRows(), 0, 0, 1, 0);
var range = new AceAjax.Range(2, 2, 3, 1);
assert.range(range.collapseRows(), 2, 0, 3, 0);
var range = new AceAjax.Range(2, 2, 3, 0);
assert.range(range.collapseRows(), 2, 0, 2, 0);
var range = new AceAjax.Range(2, 0, 2, 0);
assert.range(range.collapseRows(), 2, 0, 2, 0);
},
"test: to screen range": function () {
var session = new AceAjax.EditSession([
"juhu",
"12\t\t34",
"ぁぁa",
"\t\t34",
]);
var range = new AceAjax.Range(0, 0, 0, 3);
assert.range(range.toScreenRange(session), 0, 0, 0, 3);
var range = new AceAjax.Range(1, 1, 1, 3);
assert.range(range.toScreenRange(session), 1, 1, 1, 4);
var range = new AceAjax.Range(2, 1, 2, 2);
assert.range(range.toScreenRange(session), 2, 2, 2, 4);
var range = new AceAjax.Range(3, 0, 3, 4);
assert.range(range.toScreenRange(session), 3, 0, 3, 10);
}
};
-118
View File
@@ -1,118 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
function flatten(rangeList) {
var points = [];
rangeList.ranges.forEach(function (r) {
points.push(r.start.row, r.start.column, r.end.row, r.end.column)
})
return points;
}
function testRangeList(rangeList, points) {
assert.equal("" + flatten(rangeList), "" + points);
}
var exports = {
name: "ACE range_list.js",
"test: rangeList pointIndex": function() {
var rangeList = new AceAjax.RangeList();
rangeList.ranges = [
new AceAjax.Range(1, 2, 3, 4),
new AceAjax.Range(4, 2, 5, 4),
new AceAjax.Range(8, 8, 9, 9)
];
assert.equal(rangeList.pointIndex({ row: 0, column: 1 }), -1);
assert.equal(rangeList.pointIndex({ row: 1, column: 2 }), 0);
assert.equal(rangeList.pointIndex({ row: 1, column: 3 }), 0);
assert.equal(rangeList.pointIndex({ row: 3, column: 4 }), 0);
assert.equal(rangeList.pointIndex({ row: 4, column: 1 }), -2);
assert.equal(rangeList.pointIndex({ row: 5, column: 1 }), 1);
assert.equal(rangeList.pointIndex({ row: 8, column: 9 }), 2);
assert.equal(rangeList.pointIndex({ row: 18, column: 9 }), -4);
} ,
"test: rangeList add": function() {
var rangeList = new AceAjax.RangeList();
rangeList.addList([
new AceAjax.Range(9, 0, 9, 1),
new AceAjax.Range(1, 2, 3, 4),
new AceAjax.Range(8, 8, 9, 9),
new AceAjax.Range(4, 2, 5, 4),
new AceAjax.Range(3, 20, 3, 24),
new AceAjax.Range(6, 6, 7, 7)
]);
assert.equal(rangeList.ranges.length, 5);
rangeList.add(new AceAjax.Range(1, 2, 3, 5));
assert.range(rangeList.ranges[0], 1, 2, 3, 5);
assert.equal(rangeList.ranges.length, 5);
rangeList.add(new AceAjax.Range(7, 7, 7, 7));
assert.range(rangeList.ranges[3], 7, 7, 7, 7);
rangeList.add(new AceAjax.Range(7, 8, 7, 8));
assert.range(rangeList.ranges[4], 7, 8, 7, 8);
} ,
"test: rangeList add empty": function() {
var rangeList = new AceAjax.RangeList();
rangeList.addList([
new AceAjax.Range(7, 10, 7, 10),
new AceAjax.Range(9, 10, 9, 10),
new AceAjax.Range(8, 10, 8, 10)
]);
assert.equal(rangeList.ranges.length, 3);
rangeList.add(new AceAjax.Range(9, 10, 9, 10));
testRangeList(rangeList, [7, 10, 7, 10, 8, 10, 8, 10, 9, 10, 9, 10]);
} ,
"test: rangeList merge": function() {
var rangeList = new AceAjax.RangeList();
rangeList.addList([
new AceAjax.Range(1, 2, 3, 4),
new AceAjax.Range(4, 2, 5, 4),
new AceAjax.Range(6, 6, 7, 7),
new AceAjax.Range(8, 8, 9, 9)
]);
var removed = [];
assert.equal(rangeList.ranges.length, 4);
rangeList.ranges[1].end.row = 7;
removed = rangeList.merge();
assert.equal(removed.length, 1);
assert.range(rangeList.ranges[1], 4, 2, 7, 7);
assert.equal(rangeList.ranges.length, 3);
rangeList.ranges[0].end.row = 10;
removed = rangeList.merge();
assert.range(rangeList.ranges[0], 1, 2, 10, 4);
assert.equal(removed.length, 2);
assert.equal(rangeList.ranges.length, 1);
rangeList.ranges.push(new AceAjax.Range(10, 10, 10, 10));
rangeList.ranges.push(new AceAjax.Range(10, 10, 10, 10));
removed = rangeList.merge();
assert.equal(rangeList.ranges.length, 2);
} ,
"test: rangeList remove": function() {
var rangeList = new AceAjax.RangeList();
var list = [
new AceAjax.Range(1, 2, 3, 4),
new AceAjax.Range(4, 2, 5, 4),
new AceAjax.Range(6, 6, 7, 7),
new AceAjax.Range(8, 8, 9, 9)
];
rangeList.addList(list);
assert.equal(rangeList.ranges.length, 4);
rangeList.substractPoint({ row: 1, column: 2 });
assert.equal(rangeList.ranges.length, 3);
rangeList.substractPoint({ row: 6, column: 7 });
assert.equal(rangeList.ranges.length, 2);
}
};
@@ -1 +0,0 @@
-417
View File
@@ -1,417 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var exports = {
"test: configure the search object": function () {
var search = new AceAjax.Search();
search.set({
needle: "juhu"
});
},
"test: find simple text in document": function () {
var session = new AceAjax.EditSession(["juhu kinners 123", "456"]);
var search = new AceAjax.Search().set({
needle: "kinners"
});
var range = search.find(session);
assert.position(range.start, 0, 5);
assert.position(range.end, 0, 12);
},
"test: find simple text in next line": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
var search = new AceAjax.Search().set({
needle: "kinners"
});
var range = search.find(session);
assert.position(range.start, 1, 5);
assert.position(range.end, 1, 12);
},
"test: find text starting at cursor position": function () {
var session = new AceAjax.EditSession(["juhu kinners", "juhu kinners 123"]);
session.getSelection().moveCursorTo(0, 6);
var search = new AceAjax.Search().set({
needle: "kinners"
});
var range = search.find(session);
assert.position(range.start, 1, 5);
assert.position(range.end, 1, 12);
},
"test: wrap search is on by default": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
session.getSelection().moveCursorTo(2, 1);
var search = new AceAjax.Search().set({
needle: "kinners"
});
assert.notEqual(search.find(session), null);
},
"test: wrap search should wrap at file end": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
session.getSelection().moveCursorTo(2, 1);
var search = new AceAjax.Search().set({
needle: "kinners",
wrap: true
});
var range = search.find(session);
assert.position(range.start, 1, 5);
assert.position(range.end, 1, 12);
},
"test: wrap search should find needle even if it starts inside it": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
session.getSelection().moveCursorTo(6, 1);
var search = new AceAjax.Search().set({
needle: "kinners",
wrap: true
});
var range = search.find(session);
assert.position(range.start, 1, 5);
assert.position(range.end, 1, 12);
},
"test: wrap search with no match should return 'null'": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
session.getSelection().moveCursorTo(2, 1);
var search = new AceAjax.Search().set({
needle: "xyz",
wrap: true
});
assert.equal(search.find(session), null);
},
"test: case sensitive is by default off": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
var search = new AceAjax.Search().set({
needle: "JUHU"
});
assert.range(search.find(session), 1, 0, 1, 4);
},
"test: case sensitive search": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
var search = new AceAjax.Search().set({
needle: "KINNERS",
caseSensitive: true
});
var range = search.find(session);
assert.equal(range, null);
},
"test: whole word search should not match inside of words": function () {
var session = new AceAjax.EditSession(["juhukinners", "juhu kinners 123", "456"]);
var search = new AceAjax.Search().set({
needle: "kinners",
wholeWord: true
});
var range = search.find(session);
assert.position(range.start, 1, 5);
assert.position(range.end, 1, 12);
},
"test: find backwards": function () {
var session = new AceAjax.EditSession(["juhu juhu juhu juhu"]);
session.getSelection().moveCursorTo(0, 10);
var search = new AceAjax.Search().set({
needle: "juhu",
backwards: true
});
var range = search.find(session);
assert.position(range.start, 0, 5);
assert.position(range.end, 0, 9);
},
"test: find in selection": function () {
var session = new AceAjax.EditSession(["juhu", "juhu", "juhu", "juhu"]);
session.getSelection().setSelectionAnchor(1, 0);
session.getSelection().selectTo(3, 5);
var search = new AceAjax.Search().set({
needle: "juhu",
wrap: true,
range: session.getSelection().getRange()
});
var range = search.find(session);
assert.position(range.start, 1, 0);
assert.position(range.end, 1, 4);
search = new AceAjax.Search().set({
needle: "juhu",
wrap: true,
range: session.getSelection().getRange()
});
session.getSelection().setSelectionAnchor(0, 2);
session.getSelection().selectTo(3, 2);
var range = search.find(session);
assert.position(range.start, 1, 0);
assert.position(range.end, 1, 4);
},
"test: find backwards in selection": function () {
var session = new AceAjax.EditSession(["juhu", "juhu", "juhu", "juhu"]);
session.getSelection().setSelectionAnchor(0, 2);
session.getSelection().selectTo(3, 2);
var search = new AceAjax.Search().set({
needle: "juhu",
wrap: true,
backwards: true,
range: session.getSelection().getRange()
});
var range = search.find(session);
assert.position(range.start, 2, 0);
assert.position(range.end, 2, 4);
search = new AceAjax.Search().set({
needle: "juhu",
wrap: true,
range: session.getSelection().getRange()
});
session.getSelection().setSelectionAnchor(0, 2);
session.getSelection().selectTo(1, 2);
var range = search.find(session);
assert.position(range.start, 1, 0);
assert.position(range.end, 1, 4);
},
"test: edge case - match directly before the cursor": function () {
var session = new AceAjax.EditSession(["123", "123", "juhu"]);
var search = new AceAjax.Search().set({
needle: "juhu",
wrap: true
});
session.getSelection().moveCursorTo(2, 5);
var range = search.find(session);
assert.position(range.start, 2, 0);
assert.position(range.end, 2, 4);
},
"test: edge case - match backwards directly after the cursor": function () {
var session = new AceAjax.EditSession(["123", "123", "juhu"]);
var search = new AceAjax.Search().set({
needle: "juhu",
wrap: true,
backwards: true
});
session.getSelection().moveCursorTo(2, 0);
var range = search.find(session);
assert.position(range.start, 2, 0);
assert.position(range.end, 2, 4);
},
"test: find using a regular expression": function () {
var session = new AceAjax.EditSession(["abc123 123 cd", "abc"]);
var search = new AceAjax.Search().set({
needle: "\\d+",
regExp: true
});
var range = search.find(session);
assert.position(range.start, 0, 3);
assert.position(range.end, 0, 6);
},
"test: find using a regular expression and whole word": function () {
var session = new AceAjax.EditSession(["abc123 123 cd", "abc"]);
var search = new AceAjax.Search().set({
needle: "\\d+\\b",
regExp: true,
wholeWord: true
});
var range = search.find(session);
assert.position(range.start, 0, 7);
assert.position(range.end, 0, 10);
},
"test: use regular expressions with capture groups": function () {
var session = new AceAjax.EditSession([" ab: 12px", " <h1 abc"]);
var search = new AceAjax.Search().set({
needle: "(\\d+)",
regExp: true
});
var range = search.find(session);
assert.position(range.start, 0, 6);
assert.position(range.end, 0, 8);
},
"test: find all matches in selection": function () {
var session = new AceAjax.EditSession(["juhu", "juhu", "juhu", "juhu"]);
session.getSelection().setSelectionAnchor(0, 2);
session.getSelection().selectTo(3, 2);
var search = new AceAjax.Search().set({
needle: "uh",
wrap: true,
range: session.getSelection().getRange()
});
var ranges = search.findAll(session);
assert.equal(ranges.length, 2);
assert.position(ranges[0].start, 1, 1);
assert.position(ranges[0].end, 1, 3);
assert.position(ranges[1].start, 2, 1);
assert.position(ranges[1].end, 2, 3);
},
"test: find all multiline matches": function () {
var session = new AceAjax.EditSession(["juhu", "juhu", "juhu", "juhu"]);
var search = new AceAjax.Search().set({
needle: "hu\nju",
wrap: true
});
var ranges = search.findAll(session);
assert.equal(ranges.length, 3);
assert.position(ranges[0].start, 0, 2);
assert.position(ranges[0].end, 1, 2);
assert.position(ranges[1].start, 1, 2);
assert.position(ranges[1].end, 2, 2);
},
"test: replace() should return the replacement if the input matches the needle": function () {
var search = new AceAjax.Search().set({
needle: "juhu"
});
assert.equal(search.replace("juhu", "kinners"), "kinners");
assert.equal(search.replace("", "kinners"), null);
assert.equal(search.replace(" juhu", "kinners"), null);
// case sensitivity
assert.equal(search.replace("Juhu", "kinners"), "kinners");
search.set({ caseSensitive: true });
assert.equal(search.replace("Juhu", "kinners"), null);
// regexp replacement
},
"test: replace with a RegExp search": function () {
var search = new AceAjax.Search().set({
needle: "\\d+",
regExp: true
});
assert.equal(search.replace("123", "kinners"), "kinners");
assert.equal(search.replace("01234", "kinners"), "kinners");
assert.equal(search.replace("", "kinners"), null);
assert.equal(search.replace("a12", "kinners"), null);
assert.equal(search.replace("12a", "kinners"), null);
},
"test: replace with RegExp match and capture groups": function () {
var search = new AceAjax.Search().set({
needle: "ab(\\d\\d)",
regExp: true
});
assert.equal(search.replace("ab12", "cd$1"), "cd12");
assert.equal(search.replace("ab12", "-$&-"), "-ab12-");
assert.equal(search.replace("ab12", "$$"), "$");
},
"test: find all using regular expresion containing $": function () {
var session = new AceAjax.EditSession(["a", " b", "c ", "d"]);
var search = new AceAjax.Search().set({
needle: "[ ]+$",
regExp: true,
wrap: true
});
session.getSelection().moveCursorTo(1, 2);
var ranges = search.findAll(session);
assert.equal(ranges.length, 1);
assert.position(ranges[0].start, 2, 1);
assert.position(ranges[0].end, 2, 2);
},
"test: find all matches in a line": function () {
var session = new AceAjax.EditSession("foo bar foo baz foobar foo");
var search = new AceAjax.Search().set({
needle: "foo",
wrap: true,
wholeWord: true
});
session.getSelection().moveCursorTo(0, 4);
var ranges = search.findAll(session);
assert.equal(ranges.length, 3);
assert.position(ranges[0].start, 0, 0);
assert.position(ranges[0].end, 0, 3);
assert.position(ranges[1].start, 0, 8);
assert.position(ranges[1].end, 0, 11);
assert.position(ranges[2].start, 0, 23);
assert.position(ranges[2].end, 0, 26);
},
"test: find all matches in a line backwards": function () {
var session = new AceAjax.EditSession("foo bar foo baz foobar foo");
var search = new AceAjax.Search().set({
needle: "foo",
wrap: true,
wholeWord: true,
backwards: true
});
session.getSelection().moveCursorTo(0, 13);
var ranges = search.findAll(session);
assert.equal(ranges.length, 3);
assert.position(ranges[2].start, 0, 23);
assert.position(ranges[2].end, 0, 26);
assert.position(ranges[1].start, 0, 8);
assert.position(ranges[1].end, 0, 11);
assert.position(ranges[0].start, 0, 0);
assert.position(ranges[0].end, 0, 3);
},
};
-412
View File
@@ -1,412 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var exports = {
createSession: function (rows, cols) {
var line = new Array(cols + 1).join("a");
var text = new Array(rows).join(line + "\n") + line;
return new AceAjax.EditSession(text);
},
"test: move cursor to end of file should place the cursor on last row and column": function () {
var session = this.createSession(200, 10);
var selection = session.getSelection();
selection.moveCursorFileEnd();
assert.position(selection.getCursor(), 199, 10);
},
"test: moveCursor to start of file should place the cursor on the first row and column": function () {
var session = this.createSession(200, 10);
var selection = session.getSelection();
selection.moveCursorFileStart();
assert.position(selection.getCursor(), 0, 0);
},
"test: move selection lead to end of file": function () {
var session = this.createSession(200, 10);
var selection = session.getSelection();
selection.moveCursorTo(100, 5);
selection.selectFileEnd();
var range = selection.getRange();
assert.position(range.start, 100, 5);
assert.position(range.end, 199, 10);
},
"test: move selection lead to start of file": function () {
var session = this.createSession(200, 10);
var selection = session.getSelection();
selection.moveCursorTo(100, 5);
selection.selectFileStart();
var range = selection.getRange();
assert.position(range.start, 0, 0);
assert.position(range.end, 100, 5);
},
"test: move cursor word right": function () {
var session = new AceAjax.EditSession([
"ab",
" Juhu Kinners (abc, 12)",
" cde"
].join("\n"));
var selection = session.getSelection();
selection.moveCursorDown();
assert.position(selection.getCursor(), 1, 0);
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 1, 5);
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 1, 13);
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 1, 18);
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 1, 22);
// wrap line
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 2, 4);
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 2, 4);
},
"test: select word right if cursor in word": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 2);
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 0, 4);
},
"test: moveCursor word left": function () {
var session = new AceAjax.EditSession([
"ab",
" Juhu Kinners (abc, 12)",
" cde"
].join("\n"));
var selection = session.getSelection();
selection.moveCursorDown();
selection.moveCursorLineEnd();
assert.position(selection.getCursor(), 1, 23);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 1, 20);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 1, 15);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 1, 6);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 1, 1);
// wrap line
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 0);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 0);
},
"test: moveCursor word left with umlauts": function () {
var session = new AceAjax.EditSession(" Fuß Füße");
var selection = session.getSelection();
selection.moveCursorTo(0, 9)
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 5);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 1);
},
"test: select word left if cursor in word": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 8);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 5);
},
"test: select word right and select": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 0);
selection.selectWordRight();
var range = selection.getRange();
assert.position(range.start, 0, 0);
assert.position(range.end, 0, 4);
},
"test: select word left and select": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 3);
selection.selectWordLeft();
var range = selection.getRange();
assert.position(range.start, 0, 0);
assert.position(range.end, 0, 3);
},
"test: select word with cursor in word should select the word": function () {
var session = new AceAjax.EditSession("Juhu Kinners 123");
var selection = session.getSelection();
selection.moveCursorTo(0, 8);
selection.selectWord();
var range = selection.getRange();
assert.position(range.start, 0, 5);
assert.position(range.end, 0, 12);
},
"test: select word with cursor in word including right whitespace should select the word": function () {
var session = new AceAjax.EditSession("Juhu Kinners 123");
var selection = session.getSelection();
selection.moveCursorTo(0, 8);
selection.selectAWord();
var range = selection.getRange();
assert.position(range.start, 0, 5);
assert.position(range.end, 0, 18);
},
"test: select word with cursor betwen white space and word should select the word": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 4);
selection.selectWord();
var range = selection.getRange();
assert.position(range.start, 0, 0);
assert.position(range.end, 0, 4);
selection.moveCursorTo(0, 5);
selection.selectWord();
var range = selection.getRange();
assert.position(range.start, 0, 5);
assert.position(range.end, 0, 12);
},
"test: select word with cursor in white space should select white space": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 5);
selection.selectWord();
var range = selection.getRange();
assert.position(range.start, 0, 4);
assert.position(range.end, 0, 6);
},
"test: moving cursor should fire a 'changeCursor' event": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 5);
var called = false;
selection.addEventListener("changeCursor", function () {
called = true;
});
selection.moveCursorTo(0, 6);
assert.ok(called);
},
"test: calling setCursor with the same position should not fire an event": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 5);
var called = false;
selection.addEventListener("changeCursor", function () {
called = true;
});
selection.moveCursorTo(0, 5);
assert.notOk(called);
},
"test: moveWordright should move past || and [": function () {
var session = new AceAjax.EditSession("||foo[");
var selection = session.getSelection();
// Move behind ||foo
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 0, 5);
// Move behind [
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 0, 6);
},
"test: moveWordLeft should move past || and [": function () {
var session = new AceAjax.EditSession("||foo[");
var selection = session.getSelection();
selection.moveCursorTo(0, 6);
// Move behind [foo
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 2);
// Move behind ||
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 0);
},
"test: move cursor to line start should move cursor to end of the indentation first": function () {
var session = new AceAjax.EditSession("12\n Juhu\n12");
var selection = session.getSelection();
selection.moveCursorTo(1, 6);
selection.moveCursorLineStart();
assert.position(selection.getCursor(), 1, 4);
},
"test: move cursor to line start when the cursor is at the end of the indentation should move cursor to column 0": function () {
var session = new AceAjax.EditSession("12\n Juhu\n12");
var selection = session.getSelection();
selection.moveCursorTo(1, 4);
selection.moveCursorLineStart();
assert.position(selection.getCursor(), 1, 0);
},
"test: move cursor to line start when the cursor is at column 0 should move cursor to the end of the indentation": function () {
var session = new AceAjax.EditSession("12\n Juhu\n12");
var selection = session.getSelection();
selection.moveCursorTo(1, 0);
selection.moveCursorLineStart();
assert.position(selection.getCursor(), 1, 4);
},
// Eclipse style
"test: move cursor to line start when the cursor is before the initial indentation should move cursor to the end of the indentation": function () {
var session = new AceAjax.EditSession("12\n Juhu\n12");
var selection = session.getSelection();
selection.moveCursorTo(1, 2);
selection.moveCursorLineStart();
assert.position(selection.getCursor(), 1, 4);
},
"test go line up when in the middle of the first line should go to document start": function () {
var session = new AceAjax.EditSession("juhu kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 4);
selection.moveCursorUp();
assert.position(selection.getCursor(), 0, 0);
},
"test: (wrap) go line up when in the middle of the first line should go to document start": function () {
var session = new AceAjax.EditSession("juhu kinners");
session.setWrapLimitRange(5, 5);
session.adjustWrapLimit(80);
var selection = session.getSelection();
selection.moveCursorTo(0, 4);
selection.moveCursorUp();
assert.position(selection.getCursor(), 0, 0);
},
"test go line down when in the middle of the last line should go to document end": function () {
var session = new AceAjax.EditSession("juhu kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 4);
selection.moveCursorDown();
assert.position(selection.getCursor(), 0, 12);
},
"test (wrap) go line down when in the middle of the last line should go to document end": function () {
var session = new AceAjax.EditSession("juhu kinners");
session.setWrapLimitRange(8, 8);
session.adjustWrapLimit(80);
var selection = session.getSelection();
selection.moveCursorTo(0, 10);
selection.moveCursorDown();
assert.position(selection.getCursor(), 0, 12);
},
"test go line up twice and then once down when in the second should go back to the previous column": function () {
var session = new AceAjax.EditSession("juhu\nkinners");
var selection = session.getSelection();
selection.moveCursorTo(1, 4);
selection.moveCursorUp();
selection.moveCursorUp();
selection.moveCursorDown();
assert.position(selection.getCursor(), 1, 4);
},
"test (keyboard navigation) when curLine is not EOL and targetLine is all whitespace new column should be current column": function () {
var session = new AceAjax.EditSession("function (a) {\n\
\n\
}");
var selection = session.getSelection();
selection.moveCursorTo(2, 0);
selection.moveCursorUp();
assert.position(selection.getCursor(), 1, 0);
},
"test (keyboard navigation) when curLine is EOL and targetLine is shorter dan current column, new column should be targetLine's EOL": function () {
var session = new AceAjax.EditSession("function (a) {\n\
\n\
}");
var selection = session.getSelection();
selection.moveCursorTo(0, 14);
selection.moveCursorDown();
assert.position(selection.getCursor(), 1, 4);
}
};
@@ -1 +0,0 @@
-168
View File
@@ -1,168 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var mode: any;
var exports = {
"test: token iterator initialization in JavaScript document": function () {
var lines = [
"function foo(items) {",
" for (var i=0; i<items.length; i++) {",
" alert(items[i] + \"juhu\");",
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"),mode);
var iterator = new AceAjax.TokenIterator(session, 0, 0);
assert.equal(iterator.getCurrentToken().value, "function");
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 0);
iterator.stepForward();
assert.equal(iterator.getCurrentToken().value, " ");
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 8);
var iterator = new AceAjax.TokenIterator(session, 0, 4);
assert.equal(iterator.getCurrentToken().value, "function");
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 0);
iterator.stepForward();
assert.equal(iterator.getCurrentToken().value, " ");
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 8);
var iterator = new AceAjax.TokenIterator(session, 2, 18);
assert.equal(iterator.getCurrentToken().value, "items");
assert.equal(iterator.getCurrentTokenRow(), 2);
assert.equal(iterator.getCurrentTokenColumn(), 14);
iterator.stepForward();
assert.equal(iterator.getCurrentToken().value, "[");
assert.equal(iterator.getCurrentTokenRow(), 2);
assert.equal(iterator.getCurrentTokenColumn(), 19);
var iterator = new AceAjax.TokenIterator(session, 4, 0);
assert.equal(iterator.getCurrentToken().value, "}");
assert.equal(iterator.getCurrentTokenRow(), 4);
assert.equal(iterator.getCurrentTokenColumn(), 0);
iterator.stepBackward();
assert.equal(iterator.getCurrentToken().value, "// Real Tab.");
assert.equal(iterator.getCurrentTokenRow(), 3);
assert.equal(iterator.getCurrentTokenColumn(), 6);
var iterator = new AceAjax.TokenIterator(session, 5, 0);
assert.equal(iterator.getCurrentToken(), null);
},
"test: token iterator initialization in text document": function () {
var lines = [
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
"sed do eiusmod tempor incididunt ut labore et dolore magna",
"aliqua. Ut enim ad minim veniam, quis nostrud exercitation",
"ullamco laboris nisi ut aliquip ex ea commodo consequat."
];
var session = new AceAjax.EditSession(lines.join("\n"));
var iterator = new AceAjax.TokenIterator(session, 0, 0);
assert.equal(iterator.getCurrentToken().value, lines[0]);
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 0);
var iterator = new AceAjax.TokenIterator(session, 0, 4);
assert.equal(iterator.getCurrentToken().value, lines[0]);
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 0);
var iterator = new AceAjax.TokenIterator(session, 2, 18);
assert.equal(iterator.getCurrentToken().value, lines[2]);
assert.equal(iterator.getCurrentTokenRow(), 2);
assert.equal(iterator.getCurrentTokenColumn(), 0);
var iterator = new AceAjax.TokenIterator(session, 3, lines[3].length - 1);
assert.equal(iterator.getCurrentToken().value, lines[3]);
assert.equal(iterator.getCurrentTokenRow(), 3);
assert.equal(iterator.getCurrentTokenColumn(), 0);
var iterator = new AceAjax.TokenIterator(session, 4, 0);
assert.equal(iterator.getCurrentToken(), null);
},
"test: token iterator step forward in JavaScript document": function () {
var lines = [
"function foo(items) {",
" for (var i=0; i<items.length; i++) {",
" alert(items[i] + \"juhu\");",
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"),mode);
var tokens = [];
var len = session.getLength();
for (var i = 0; i < len; i++)
tokens = tokens.concat(session.getTokens(i));
var iterator = new AceAjax.TokenIterator(session, 0, 0);
for (var i = 1; i < tokens.length; i++)
assert.equal(iterator.stepForward(), tokens[i]);
assert.equal(iterator.stepForward(), null);
assert.equal(iterator.getCurrentToken(), null);
},
"test: token iterator step backward in JavaScript document": function () {
var lines = [
"function foo(items) {",
" for (var i=0; i<items.length; i++) {",
" alert(items[i] + \"juhu\");",
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"),mode);
var tokens = [];
var len = session.getLength();
for (var i = 0; i < len; i++)
tokens = tokens.concat(session.getTokens(i));
var iterator = new AceAjax.TokenIterator(session, 4, 0);
for (var i = tokens.length - 2; i >= 0; i--)
assert.equal(iterator.stepBackward(), tokens[i]);
assert.equal(iterator.stepBackward(), null);
assert.equal(iterator.getCurrentToken(), null);
},
"test: token iterator reports correct row and column": function () {
var lines = [
"function foo(items) {",
" for (var i=0; i<items.length; i++) {",
" alert(items[i] + \"juhu\");",
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"),mode);
var iterator = new AceAjax.TokenIterator(session, 0, 0);
iterator.stepForward();
iterator.stepForward();
assert.equal(iterator.getCurrentToken().value, "foo");
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 9);
iterator.stepForward();
iterator.stepForward();
iterator.stepForward();
iterator.stepForward();
iterator.stepForward();
iterator.stepForward();
iterator.stepForward();
assert.equal(iterator.getCurrentToken().value, "for");
assert.equal(iterator.getCurrentTokenRow(), 1);
assert.equal(iterator.getCurrentTokenColumn(), 4);
}
};
@@ -1 +0,0 @@
-41
View File
@@ -1,41 +0,0 @@
/// <reference path="../ace.d.ts" />
var assert: any;
var exports = {
"test: screen2text the column should be rounded to the next character edge": function () {
var el = document.createElement("div");
if (!el.getBoundingClientRect) {
console.log("Skipping test: This test only runs in the browser");
return;
}
el.style.left = "20px";
el.style.top = "30px";
el.style.width = "300px";
el.style.height = "100px";
document.body.appendChild(el);
var renderer = new AceAjax.VirtualRenderer(el);
renderer.setPadding(0);
renderer.setSession(new AceAjax.EditSession("1234"));
var r = renderer.scroller.getBoundingClientRect();
function testPixelToText(x, y, row, column) {
assert.position(renderer.screenToTextCoordinates(x + r.left, y + r.top), row, column);
}
renderer.characterWidth = 10;
renderer.lineHeight = 15;
testPixelToText(4, 0, 0, 0);
testPixelToText(5, 0, 0, 1);
testPixelToText(9, 0, 0, 1);
testPixelToText(10, 0, 0, 1);
testPixelToText(14, 0, 0, 1);
testPixelToText(15, 0, 0, 2);
document.body.removeChild(el);
}
// change tab size after setDocument (for text layer)
};
@@ -1 +0,0 @@
-16
View File
@@ -1,16 +0,0 @@
/// <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
@@ -1,16 +0,0 @@
/// <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
@@ -1,65 +0,0 @@
/// <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
@@ -1,150 +0,0 @@
// 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-1.4.9.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
@@ -1,30 +0,0 @@
/// <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', {ranges: 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;
-68
View File
@@ -1,68 +0,0 @@
// 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;
function getLineInfo(input: string, offset: number): ESTree.Position;
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
}
-5
View File
@@ -1,5 +0,0 @@
/// <reference path="add2home.d.ts" />
addToHome.show(false);
addToHome.close();
addToHome.reset();
-15
View File
@@ -1,15 +0,0 @@
// Type definitions for add2home v2.0.5
// Project: http://cubiq.org/add-to-home-screen
// Definitions by: James Wilkins <http://www.codeplex.com/site/users/view/jamesnw>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var addToHome: {
/** Shows the popup.
* @param {boolean} overrideChecks Override all the compatibility checks and always show the popup.
*/
show: (overrideChecks: boolean) => void;
/** Closes the popup. */
close: () => void;
/** Reset the local and session storages so the popup will show again (for automatic mode - has no affect if manually opening the popup). */
reset: () => void;
};
-299
View File
@@ -1,299 +0,0 @@
// Type definitions for adm-zip v0.4.4
// Project: https://github.com/cthackers/adm-zip
// Definitions by: John Vilk <https://github.com/jvilk>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "adm-zip" {
class AdmZip {
/**
* Create a new, empty archive.
*/
constructor();
/**
* Read an existing archive.
*/
constructor(fileName: string);
/**
* Extracts the given entry from the archive and returns the content as a
* Buffer object.
* @param entry String with the full path of the entry
* @return Buffer or Null in case of error
*/
readFile(entry: string): Buffer;
/**
* Extracts the given entry from the archive and returns the content as a
* Buffer object.
* @param entry ZipEntry object
* @return Buffer or Null in case of error
*/
readFile(entry: AdmZip.IZipEntry): Buffer;
/**
* Asynchronous readFile
* @param entry String with the full path of the entry
* @param callback Called with a Buffer or Null in case of error
*/
readFileAsync(entry: string, callback: (data: Buffer, err: string) => any): void;
/**
* Asynchronous readFile
* @param entry ZipEntry object
* @param callback Called with a Buffer or Null in case of error
* @return Buffer or Null in case of error
*/
readFileAsync(entry: AdmZip.IZipEntry, callback: (data: Buffer, err: string) => any): void;
/**
* Extracts the given entry from the archive and returns the content as
* plain text in the given encoding
* @param entry String with the full path of the entry
* @param encoding Optional. If no encoding is specified utf8 is used
* @return String
*/
readAsText(fileName: string, encoding?: string): string;
/**
* Extracts the given entry from the archive and returns the content as
* plain text in the given encoding
* @param entry ZipEntry object
* @param encoding Optional. If no encoding is specified utf8 is used
* @return String
*/
readAsText(fileName: AdmZip.IZipEntry, encoding?: string): string;
/**
* Asynchronous readAsText
* @param entry String with the full path of the entry
* @param callback Called with the resulting string.
* @param encoding Optional. If no encoding is specified utf8 is used
*/
readAsTextAsync(fileName: string, callback: (data: string) => any, encoding?: string): void;
/**
* Asynchronous readAsText
* @param entry ZipEntry object
* @param callback Called with the resulting string.
* @param encoding Optional. If no encoding is specified utf8 is used
*/
readAsTextAsync(fileName: AdmZip.IZipEntry, callback: (data: string) => any, encoding?: string): void;
/**
* Remove the entry from the file or the entry and all its nested directories
* and files if the given entry is a directory
* @param entry String with the full path of the entry
*/
deleteFile(entry: string): void;
/**
* Remove the entry from the file or the entry and all its nested directories
* and files if the given entry is a directory
* @param entry A ZipEntry object.
*/
deleteFile(entry: AdmZip.IZipEntry): void;
/**
* Adds a comment to the zip. The zip must be rewritten after
* adding the comment.
* @param comment Content of the comment.
*/
addZipComment(comment: string): void;
/**
* Returns the zip comment
* @return The zip comment.
*/
getZipComment(): string;
/**
* Adds a comment to a specified zipEntry. The zip must be rewritten after
* adding the comment.
* The comment cannot exceed 65535 characters in length.
* @param entry String with the full path of the entry
* @param comment The comment to add to the entry.
*/
addZipEntryComment(entry: string, comment: string): void;
/**
* Adds a comment to a specified zipEntry. The zip must be rewritten after
* adding the comment.
* The comment cannot exceed 65535 characters in length.
* @param entry ZipEntry object.
* @param comment The comment to add to the entry.
*/
addZipEntryComment(entry: AdmZip.IZipEntry, comment: string): void;
/**
* Returns the comment of the specified entry.
* @param entry String with the full path of the entry.
* @return String The comment of the specified entry.
*/
getZipEntryComment(entry: string): string;
/**
* Returns the comment of the specified entry
* @param entry ZipEntry object.
* @return String The comment of the specified entry.
*/
getZipEntryComment(entry: AdmZip.IZipEntry): string;
/**
* Updates the content of an existing entry inside the archive. The zip
* must be rewritten after updating the content
* @param entry String with the full path of the entry.
* @param content The entry's new contents.
*/
updateFile(entry: string, content: Buffer): void;
/**
* Updates the content of an existing entry inside the archive. The zip
* must be rewritten after updating the content
* @param entry ZipEntry object.
* @param content The entry's new contents.
*/
updateFile(entry: AdmZip.IZipEntry, content: Buffer): void;
/**
* Adds a file from the disk to the archive.
* @param localPath Path to a file on disk.
* @param zipPath Path to a directory in the archive. Defaults to the empty
* string.
*/
addLocalFile(localPath: string, zipPath?: string): void;
/**
* Adds a local directory and all its nested files and directories to the
* archive.
* @param localPath Path to a folder on disk.
* @param zipPath Path to a folder in the archive. Defaults to an empty
* string.
*/
addLocalFolder(localPath: string, zipPath?: string): void;
/**
* Allows you to create a entry (file or directory) in the zip file.
* If you want to create a directory the entryName must end in / and a null
* buffer should be provided.
* @param entryName Entry path
* @param content Content to add to the entry; must be a 0-length buffer
* for a directory.
* @param comment Comment to add to the entry.
* @param attr Attribute to add to the entry.
*/
addFile(entryName: string, data: Buffer, comment?: string, attr?: number): void;
/**
* Returns an array of ZipEntry objects representing the files and folders
* inside the archive
*/
getEntries(): AdmZip.IZipEntry[];
/**
* Returns a ZipEntry object representing the file or folder specified by
* ``name``.
* @param name Name of the file or folder to retrieve.
* @return ZipEntry The entry corresponding to the name.
*/
getEntry(name: string): AdmZip.IZipEntry;
/**
* Extracts the given entry to the given targetPath.
* If the entry is a directory inside the archive, the entire directory and
* its subdirectories will be extracted.
* @param entry String with the full path of the entry
* @param targetPath Target folder where to write the file
* @param maintainEntryPath If maintainEntryPath is true and the entry is
* inside a folder, the entry folder will be created in targetPath as
* well. Default is TRUE
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
*
* @return Boolean
*/
extractEntryTo(entryPath: string, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean;
/**
* Extracts the given entry to the given targetPath.
* If the entry is a directory inside the archive, the entire directory and
* its subdirectories will be extracted.
* @param entry ZipEntry object
* @param targetPath Target folder where to write the file
* @param maintainEntryPath If maintainEntryPath is true and the entry is
* inside a folder, the entry folder will be created in targetPath as
* well. Default is TRUE
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
* @return Boolean
*/
extractEntryTo(entryPath: AdmZip.IZipEntry, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean;
/**
* Extracts the entire archive to the given location
* @param targetPath Target location
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
*/
extractAllTo(targetPath: string, overwrite?: boolean): void;
/**
* Writes the newly created zip file to disk at the specified location or
* if a zip was opened and no ``targetFileName`` is provided, it will
* overwrite the opened zip
* @param targetFileName
*/
writeZip(targetPath?: string): void;
/**
* Returns the content of the entire zip file as a Buffer object
* @return Buffer
*/
toBuffer(): Buffer;
}
module AdmZip {
/**
* The ZipEntry is more than a structure representing the entry inside the
* zip file. Beside the normal attributes and headers a entry can have, the
* class contains a reference to the part of the file where the compressed
* data resides and decompresses it when requested. It also compresses the
* data and creates the headers required to write in the zip file.
*/
interface IZipEntry {
/**
* Represents the full name and path of the file
*/
entryName: string;
rawEntryName: Buffer;
/**
* Extra data associated with this entry.
*/
extra: Buffer;
/**
* Entry comment.
*/
comment: string;
name: string;
/**
* Read-Only property that indicates the type of the entry.
*/
isDirectory: boolean;
/**
* Get the header associated with this ZipEntry.
*/
header: Buffer;
/**
* Retrieve the compressed data for this entry. Note that this may trigger
* compression if any properties were modified.
*/
getCompressedData(): Buffer;
/**
* Asynchronously retrieve the compressed data for this entry. Note that
* this may trigger compression if any properties were modified.
*/
getCompressedDataAsync(callback: (data: Buffer) => void): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: string): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: Buffer): void;
/**
* Get the decompressed data associated with this entry.
*/
getData(): Buffer;
/**
* Asynchronously get the decompressed data associated with this entry.
*/
getDataAsync(callback: (data: Buffer) => void): void;
/**
* Returns the CEN Entry Header to be written to the output zip file, plus
* the extra data and the entry comment.
*/
packHeader(): Buffer;
/**
* Returns a nicely formatted string with the most important properties of
* the ZipEntry.
*/
toString(): string;
}
}
export = AdmZip;
}
-137
View File
@@ -1,137 +0,0 @@
/// <reference path="ag-grid" />
checkGridOptions(<ag.grid.GridOptions>{});
checkColDef(<ag.grid.ColDef>{});
function checkGridOptions(gridOptions: ag.grid.GridOptions): void {
gridOptions.virtualPaging = true;
gridOptions.toolPanelSuppressPivot = true;
gridOptions.toolPanelSuppressValues = true;
gridOptions.rowsAlreadyGrouped = true;
gridOptions.suppressRowClickSelection = true;
gridOptions.suppressCellSelection = true;
gridOptions.sortingOrder = ['asc','desc'];
gridOptions.suppressMultiSort = true;
gridOptions.suppressHorizontalScroll = true;
gridOptions.unSortIcon = true;
gridOptions.rowHeight = 0;
gridOptions.rowBuffer = 0;
gridOptions.enableColResize = true;
gridOptions.enableCellExpressions = true;
gridOptions.enableSorting = true;
gridOptions.enableServerSideSorting = true;
gridOptions.enableFilter = true;
gridOptions.enableServerSideFilter = true;
gridOptions.colWidth = 0;
gridOptions.suppressMenuHide = true;
gridOptions.singleClickEdit = true;
gridOptions.debug = true;
gridOptions.icons = {};
gridOptions.angularCompileRows = true;
gridOptions.angularCompileFilters = true;
gridOptions.angularCompileHeaders = true;
gridOptions.localeText = {};
gridOptions.localeTextFunc = function() {}
gridOptions.suppressScrollLag = true;
gridOptions.groupSuppressAutoColumn = true;
gridOptions.groupSelectsChildren = true;
gridOptions.groupHidePivotColumns = true;
gridOptions.groupIncludeFooter = true;
gridOptions.groupUseEntireRow = true;
gridOptions.groupSuppressRow = true;
gridOptions.groupSuppressBlankHeader = true;
gridOptions.forPrint = true;
gridOptions.groupColumnDef = {};
gridOptions.context = {};
gridOptions.rowStyle = {color: 'red'};
gridOptions.rowClass = 'green';
gridOptions.groupDefaultExpanded = false;
gridOptions.slaveGrids = [];
gridOptions.rowSelection = 'single';
gridOptions.rowDeselection = true;
gridOptions.rowData = [];
gridOptions.floatingTopRowData = [];
gridOptions.floatingBottomRowData = [];
gridOptions.showToolPanel = true;
gridOptions.groupKeys = ['a','b']
gridOptions.groupAggFields = ['a','b']
gridOptions.columnDefs = [];
gridOptions.datasource = {};
gridOptions.pinnedColumnCount = 0;
gridOptions.groupHeaders = true;
gridOptions.headerHeight = 0;
gridOptions.groupRowInnerRenderer = function(params) {};
gridOptions.groupRowRenderer = {};
gridOptions.isScrollLag = function() {return true;}
gridOptions.isExternalFilterPresent = function() { return true; };
gridOptions.doesExternalFilterPass = function(node: ag.grid.RowNode) { return false; };
gridOptions.getRowStyle = function() {};
gridOptions.getRowClass = function() {};
gridOptions.headerCellRenderer = function() {};
gridOptions.groupAggFunction = function(nodes: any[]) {};
gridOptions.onReady = function(api: any) {};
gridOptions.onModelUpdated = function() {};
gridOptions.onCellClicked = function(params) {};
gridOptions.onCellDoubleClicked = function(params) {};
gridOptions.onCellContextMenu = function(params) {};
gridOptions.onCellValueChanged = function(params) {};
gridOptions.onCellFocused = function(params) {};
gridOptions.onRowSelected = function(params) {};
gridOptions.onSelectionChanged = function() {};
gridOptions.onBeforeFilterChanged = function() {};
gridOptions.onAfterFilterChanged = function() {};
gridOptions.onFilterModified = function() {};
gridOptions.onBeforeSortChanged = function() {};
gridOptions.onAfterSortChanged = function() {};
gridOptions.onVirtualRowRemoved = function(params) {};
gridOptions.onRowClicked = function(params) {};
gridOptions.api = null;
gridOptions.columnApi = null;
}
function checkColDef(colDef: ag.grid.ColDef): void {
colDef.sort = 'test';
colDef.sortedAt = 0;
colDef.sortingOrder = ['asc','desc'];
colDef.headerName = 'test';
colDef.field = 'test';
colDef.headerValueGetter = 'test';
colDef.colId = 'test';
colDef.hide = true;
colDef.headerTooltip = 'test';
colDef.valueGetter = 'test';
colDef.headerCellRenderer = {};
colDef.headerClass = 'test';
colDef.width = 0;
colDef.minWidth = 0;
colDef.maxWidth = 0;
colDef.cellClass = 'test';
colDef.cellStyle = {color: 'test'};
colDef.cellRenderer = function() {};
colDef.floatingCellRenderer = function() {};
colDef.aggFunc = 'test';
colDef.comparator = function() {};
colDef.checkboxSelection = true;
colDef.suppressMenu = true;
colDef.suppressSorting = true;
colDef.unSortIcon = true;
colDef.suppressSizeToFit = true;
colDef.suppressResize = true;
colDef.headerGroup = 'test';
colDef.headerGroupShow = 'test';
colDef.editable = true;
colDef.newValueHandler = function() {};
colDef.volatile = true;
colDef.template = 'test';
colDef.templateUrl = 'test';
colDef.filter = 'test';
colDef.filterParams = {};
colDef.onCellValueChanged = function() {};
colDef.onCellClicked = function() {};
colDef.onCellDoubleClicked = function() {};
colDef.onCellContextMenu = function() {};
colDef.cellClassRules = {};
}
File diff suppressed because it is too large Load Diff
-1991
View File
File diff suppressed because it is too large Load Diff
-124
View File
@@ -1,124 +0,0 @@
// Type definitions for alertify 0.3.11
// Project: http://fabien-d.github.io/alertify.js/
// Definitions by: John Jeffery <http://github.com/jjeffery>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var alertify: alertify.IAlertifyStatic;
declare module alertify {
interface IAlertifyStatic {
/**
* Create an alert dialog box
* @param message The message passed from the callee
* @param fn Callback function
* @param cssClass Class(es) to append to dialog box
* @return alertify (ie this)
* @since 0.0.1
*/
alert(message: string, fn?: Function, cssClass?: string): IAlertifyStatic;
/**
* Create a confirm dialog box
* @param message The message passed from the callee
* @param fn Callback function
* @param cssClass Class(es) to append to dialog box
* @return alertify (ie this)
* @since 0.0.1
*/
confirm(message: string, fn?: Function, cssClass?: string): IAlertifyStatic;
/**
* Extend the log method to create custom methods
* @param type Custom method name
* @return function for logging
* @since 0.0.1
*/
extend(type: string): (message: string, wait?: number) => IAlertifyStatic;
/**
* Initialize Alertify and create the 2 main elements.
* Initialization will happen automatically on the first
* use of alert, confirm, prompt or log.
* @since 0.0.1
*/
init(): void;
/**
* Show a new log message box
* @param message The message passed from the callee
* @param type Optional type of log message
* @param wait Optional time (in ms) to wait before auto-hiding
* @return alertify (ie this)
* @since 0.0.1
*/
log(message: string, type?: string, wait?: number): IAlertifyStatic;
/**
* Create a prompt dialog box
* @param message The message passed from the callee
* @param fn Callback function
* @param placeholder Default value for prompt input
* @param cssClass Class(es) to append to dialog
* @return alertify (ie this)
* @since 0.0.1
*/
prompt(message: string, fn?: Function, placeholder?: string, cssClass?: string): IAlertifyStatic;
/**
* Shorthand for log messages
* @param message The message passed from the callee
* @return alertify (ie this)
* @since 0.0.1
*/
success(message: string): IAlertifyStatic;
/**
* Shorthand for log messages
* @param message The message passed from the callee
* @return alertify (ie this)
* @since 0.0.1
*/
error(message: string): IAlertifyStatic;
/**
* Used to set alertify properties
* @param Properties
* @since 0.2.11
*/
set(args: IProperties): void;
/**
* The labels used for dialog buttons
*/
labels: ILabels;
/**
* Attaches alertify.error to window.onerror method
* @since 0.3.8
*/
debug(): void;
}
/**
* Properties for alertify.set function
*/
interface IProperties {
/** Default value for milliseconds display of log messages */
delay?: number;
/** Default values for display of labels */
labels?: ILabels;
/** Default button for focus */
buttonFocus?: string;
/** Should buttons be displayed in reverse order */
buttonReverse?: boolean;
}
/** Labels for altertify.set function */
interface ILabels {
ok?: string;
cancel?: string;
}
}
-167
View File
@@ -1,167 +0,0 @@
// 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;
}
-27
View File
@@ -1,27 +0,0 @@
// Type definitions for amazon-product-api
// Project: https://github.com/t3chnoboy/amazon-product-api
// Definitions by: Matti Lehtinen <https://github.com/MattiLehtinen/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../es6-promise/es6-promise.d.ts"/>
declare module "amazon-product-api" {
interface ICredentials {
awsId: string,
awsSecret: string,
awsTag: string
}
interface IAmazonProductQueryCallback {
(err: string, results: Object[]): void;
}
interface IAmazonProductClient {
itemSearch(query: any, callback?: IAmazonProductQueryCallback) : Promise<Object[]>;
itemLookup(query: any, callback?: IAmazonProductQueryCallback) : Promise<Object[]>;
browseNodeLookup(query: any, callback?: IAmazonProductQueryCallback) : Promise<Object[]>;
}
export function createClient(credentials:ICredentials) : IAmazonProductClient;
}
-2558
View File
File diff suppressed because it is too large Load Diff
-1
View File
@@ -1 +0,0 @@
-265
View File
@@ -1,265 +0,0 @@
/// <reference path="amplify-deferred.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
// Copied examples directly from AmplifyJs site
// Subscribe and publish with no data
amplify.subscribe("nodataexample", function () {
alert("nodataexample topic published!");
});
// Subscribe and publish with data
amplify.publish("nodataexample");
amplify.subscribe("dataexample", function (data) {
alert(data.foo); // bar
});
amplify.publish("dataexample", { foo: "bar" });
amplify.subscribe("dataexample2", function (param1, param2) {
alert(param1 + param2); // barbaz
});
//...
amplify.publish("dataexample2", "bar", "baz");
// Subscribe and publish with context and data
amplify.subscribe("datacontextexample", $("p:first"), function (data) {
this.text(data.exampleText); // first p element would have "foo bar baz" as text
});
amplify.publish("datacontextexample", { exampleText: "foo bar baz" });
// Subscribe to a topic with high priority
amplify.subscribe("priorityexample", function (data) {
alert(data.foo);
});
amplify.subscribe("priorityexample", function (data) {
if (data.foo === "oops") {
return false;
}
}, 1);
// Store data with amplify storage picking the default storage technology:
amplify.publish("priorityexample", { foo: "bar" });
amplify.publish("priorityexample", { foo: "oops" });
amplify.store("storeExample1", { foo: "bar" });
amplify.store("storeExample2", "baz");
// retrieve the data later via the key
var myStoredValue = amplify.store("storeExample1"),
myStoredValue2 = amplify.store("storeExample2"),
myStoredValues = amplify.store();
myStoredValue.foo; // bar
myStoredValue2; // baz
myStoredValues.storeExample1.foo; // bar
myStoredValues.storeExample2; // baz
// Store data explicitly with session storage
amplify.store.sessionStorage("explicitExample", { foo2: "baz" });
// retrieve the data later via the key
var myStoredValue2 = amplify.store.sessionStorage("explicitExample");
myStoredValue2.foo2; // baz
// REQUEST
// Set up and use a request utilizing Ajax
amplify.request.define("ajaxExample1", "ajax", {
url: "/myApiUrl",
dataType: "json",
type: "GET"
});
// later in code
amplify.request("ajaxExample1", function (data) {
data.foo; // bar
});
// Set up and use a request utilizing Ajax and Caching
amplify.request.define("ajaxExample2", "ajax", {
url: "/myApiUrl",
dataType: "json",
type: "GET",
cache: "persist"
});
// later in code
amplify.request("ajaxExample2", function (data) {
data.foo; // bar
});
// a second call will result in pulling from the cache
amplify.request("ajaxExample2", function (data) {
data.baz; // qux
})
// Set up and use a RESTful request utilizing Ajax
amplify.request.define("ajaxRESTFulExample", "ajax", {
url: "/myRestFulApi/{type}/{id}",
type: "GET"
})
// later in code
amplify.request("ajaxRESTFulExample",
{
type: "foo",
id: "bar"
},
function (data) {
// /myRESTFulApi/foo/bar was the URL used
data.foo; // bar
}
);
// POST data with Ajax
amplify.request.define("ajaxPostExample", "ajax", {
url: "/myRestFulApi",
type: "POST"
})
// later in code
amplify.request("ajaxPostExample",
{
type: "foo",
id: "bar"
},
function (data) {
data.foo; // bar
}
);
// Using data maps
// When searching Twitter, the key for the search phrase is q.If we want a more descriptive name, such as term, we can use a data map:
amplify.request.define("twitter-search", "ajax", {
url: "http://search.twitter.com/search.json",
dataType: "jsonp",
dataMap: {
term: "q"
}
});
amplify.request("twitter-search", { term: "amplifyjs" });
// Similarly, we can create a request that searches for mentions, by accepting a username:
amplify.request.define("twitter-mentions", "ajax", {
url: "http://search.twitter.com/search.json",
dataType: "jsonp",
dataMap: function (data) {
return {
q: "@" + data.user
};
}
});
amplify.request("twitter-mentions", { user: "amplifyjs" });
// Setting up and using decoders
//Example:
var appEnvelopeDecoder: amplifyDecoder = function (data, status, xhr, success, error) {
if (data.status === "success") {
success(data.data);
} else if (data.status === "fail" || data.status === "error") {
error(data.message, data.status);
} else {
error(data.message, "fatal");
}
};
//a new decoder can be added to the amplifyDecoders interface
interface amplifyDecoders {
appEnvelope: amplifyDecoder;
}
amplify.request.decoders.appEnvelope = appEnvelopeDecoder;
//but you can also just add it via an index
amplify.request.decoders['appEnvelopeStr'] = appEnvelopeDecoder;
amplify.request.define("decoderExample", "ajax", {
url: "/myAjaxUrl",
type: "POST",
decoder: "appEnvelope"
});
amplify.request({
resourceId: "decoderExample",
success: function (data) {
data.foo; // bar
},
error: function (message, level) {
alert("always handle errors with alerts.");
}
});
// POST with caching and single - use decoder
// Example:
amplify.request.define("decoderSingleExample", "ajax", {
url: "/myAjaxUrl",
type: "POST",
decoder: function (data, status, xhr, success, error) {
if (data.status === "success") {
success(data.data);
} else if (data.status === "fail" || data.status === "error") {
error(data.message, data.status);
} else {
error(data.message, "fatal");
}
}
});
amplify.request({
resourceId: "decoderSingleExample",
success: function (data) {
data.foo; // bar
},
error: function (message, level) {
alert("always handle errors with alerts.");
}
});
// Handling Status
// Status in Success and Error Callbacks
// amplify.request comes with built in support for status.The status parameter appears in the default success or error callbacks when using an ajax definition.
amplify.request.define("statusExample1", "ajax", {
//...
});
amplify.request({
resourceId: "statusExample1",
success: function (data, status) {
},
error: function (data, status) {
}
});
amplify.request({
resourceId: "statusExample1"
}).done(function (data, status) {
}).fail(function (data, status) {
}).always(function (data, status) { });
@@ -1 +0,0 @@
-182
View File
@@ -1,182 +0,0 @@
// Type definitions for AmplifyJs 1.1.0 using JQuery Deferred
// Project: http://amplifyjs.com/
// Definitions by: Jonas Eriksson <https://github.com/joeriks/>, Laurentiu Stamate <https://github.com/laurentiustamate94>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface amplifyRequestSettings {
resourceId: string;
data?: any;
success?: (...args: any[]) => void;
error?: (...args: any[]) => void;
}
interface amplifyDecoder {
(
data?: any,
status?: string,
xhr?: JQueryXHR,
success?: (...args: any[]) => void,
error?: (...args: any[]) => void
): void
}
interface amplifyDecoders {
[decoderName: string]: amplifyDecoder;
jsSend: amplifyDecoder;
}
interface amplifyAjaxSettings extends JQueryAjaxSettings {
cache?: any;
dataMap?: {} | ((data: any) => {});
decoder?: any /* string or amplifyDecoder */;
}
interface amplifyRequest {
/***
* Request a resource.
* resourceId: Identifier string for the resource.
* data: A set of key/value pairs of data to be sent to the resource.
* callback: A function to invoke if the resource is retrieved successfully.
*/
(resourceId: string, hash?: any, callback?: Function): JQueryPromise<any>;
/***
* Request a resource.
* settings: A set of key/value pairs of settings for the request.
* resourceId: Identifier string for the resource.
* data (optional): Data associated with the request.
* success (optional): Function to invoke on success.
* error (optional): Function to invoke on error.
*/
(settings: amplifyRequestSettings): JQueryPromise<any>;
/***
* Define a resource.
* resourceId: Identifier string for the resource.
* requestType: The type of data retrieval method from the server. See the request types sections for more information.
* settings: A set of key/value pairs that relate to the server communication technology. The following settings are available:
* Any settings found in jQuery.ajax().
* cache: See the cache section for more details.
* decoder: See the decoder section for more details.
*/
define(resourceId: string, requestType: string, settings?: amplifyAjaxSettings): void;
/***
* Define a custom request.
* resourceId: Identifier string for the resource.
* resource: Function to handle requests. Receives a hash with the following properties:
* resourceId: Identifier string for the resource.
* data: Data provided by the user.
* success: Callback to invoke on success.
* error: Callback to invoke on error.
*/
define(resourceId: string, resource: (settings: amplifyRequestSettings) => void): void;
decoders: amplifyDecoders;
cache: any;
}
interface amplifySubscribe {
/***
* Subscribe to a message.
* topic: Name of the message to subscribe to.
* callback: Function to invoke when the message is published.
*/
(topic: string, callback: Function): void;
/***
* Subscribe to a message.
* topic: Name of the message to subscribe to.
* context: What this will be when the callback is invoked.
* callback: Function to invoke when the message is published.
* [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10.
*/
(topic: string, context: any, callback: Function, priority?: number): void;
/***
* Subscribe to a message.
* topic: Name of the message to subscribe to.
* callback: Function to invoke when the message is published.
* [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10.
*/
(topic: string, callback: Function, priority?: number): void;
}
interface amplifyStorageTypeStore {
/***
* Stores a value for a given key using the default storage type.
*
* key: Identifier for the value being stored.
* value: The value to store. The value can be anything that can be serialized as JSON.
* [options]: A set of key/value pairs that relate to settings for storing the value.
*/
(key: string, value: any, options?: any): void;
/***
* Gets a stored value based on the key.
*/
(key: string): any;
/***
* Gets a hash of all stored values.
*/
(): any;
}
interface amplifyStore extends amplifyStorageTypeStore {
/***
* IE 8+, Firefox 3.5+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+
*/
localStorage: amplifyStorageTypeStore;
/***
* IE 8+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+
*/
sessionStorage: amplifyStorageTypeStore;
/***
* Firefox 2+
*/
globalStorage: amplifyStorageTypeStore;
/***
* IE 5 - 7
*/
userData: amplifyStorageTypeStore;
/***
* An in-memory store is provided as a fallback if none of the other storage types are available.
*/
memory: amplifyStorageTypeStore;
}
interface amplifyStatic {
subscribe: amplifySubscribe;
/***
* Remove a subscription.
* topic: The topic being unsubscribed from.
* callback: The callback that was originally subscribed.
*/
unsubscribe(topic: string, callback: Function): void;
/***
* Publish a message.
* topic: The name of the message to publish.
* Any additional parameters will be passed to the subscriptions.
* amplify.publish returns a boolean indicating whether any subscriptions returned false. The return value is true if none of the subscriptions returned false, and false otherwise. Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked.
*/
publish(topic: string, ...args: any[]): boolean;
store: amplifyStore;
request: amplifyRequest;
}
declare var amplify: amplifyStatic;
-259
View File
@@ -1,259 +0,0 @@
/// <reference path="amplifyjs.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
// Copied examples directly from AmplifyJs site
// Subscribe and publish with no data
amplify.subscribe("nodataexample", function () {
alert("nodataexample topic published!");
});
// Subscribe and publish with data
amplify.publish("nodataexample");
amplify.subscribe("dataexample", function (data) {
alert(data.foo); // bar
});
amplify.publish("dataexample", { foo: "bar" });
amplify.subscribe("dataexample2", function (param1, param2) {
alert(param1 + param2); // barbaz
});
//...
amplify.publish("dataexample2", "bar", "baz");
// Subscribe and publish with context and data
amplify.subscribe("datacontextexample", $("p:first"), function (data) {
this.text(data.exampleText); // first p element would have "foo bar baz" as text
});
amplify.publish("datacontextexample", { exampleText: "foo bar baz" });
// Subscribe to a topic with high priority
amplify.subscribe("priorityexample", function (data) {
alert(data.foo);
});
amplify.subscribe("priorityexample", function (data) {
if (data.foo === "oops") {
return false;
}
}, 1);
// Store data with amplify storage picking the default storage technology:
amplify.publish("priorityexample", { foo: "bar" });
amplify.publish("priorityexample", { foo: "oops" });
amplify.store("storeExample1", { foo: "bar" });
amplify.store("storeExample2", "baz");
// retrieve the data later via the key
var myStoredValue = amplify.store("storeExample1"),
myStoredValue2 = amplify.store("storeExample2"),
myStoredValues = amplify.store();
myStoredValue.foo; // bar
myStoredValue2; // baz
myStoredValues.storeExample1.foo; // bar
myStoredValues.storeExample2; // baz
// Store data explicitly with session storage
amplify.store.sessionStorage("explicitExample", { foo2: "baz" });
// retrieve the data later via the key
var myStoredValue2 = amplify.store.sessionStorage("explicitExample");
myStoredValue2.foo2; // baz
// REQUEST
// Set up and use a request utilizing Ajax
amplify.request.define("ajaxExample1", "ajax", {
url: "/myApiUrl",
dataType: "json",
type: "GET"
});
// later in code
amplify.request("ajaxExample1", function (data) {
data.foo; // bar
});
// Set up and use a request utilizing Ajax and Caching
amplify.request.define("ajaxExample2", "ajax", {
url: "/myApiUrl",
dataType: "json",
type: "GET",
cache: "persist"
});
// later in code
amplify.request("ajaxExample2", function (data) {
data.foo; // bar
});
// a second call will result in pulling from the cache
amplify.request("ajaxExample2", function (data) {
data.baz; // qux
})
// Set up and use a RESTful request utilizing Ajax
amplify.request.define("ajaxRESTFulExample", "ajax", {
url: "/myRestFulApi/{type}/{id}",
type: "GET"
})
// later in code
amplify.request("ajaxRESTFulExample",
{
type: "foo",
id: "bar"
},
function (data) {
// /myRESTFulApi/foo/bar was the URL used
data.foo; // bar
}
);
// POST data with Ajax
amplify.request.define("ajaxPostExample", "ajax", {
url: "/myRestFulApi",
type: "POST"
})
// later in code
amplify.request("ajaxPostExample",
{
type: "foo",
id: "bar"
},
function (data) {
data.foo; // bar
}
);
// Using data maps
// When searching Twitter, the key for the search phrase is q.If we want a more descriptive name, such as term, we can use a data map:
amplify.request.define("twitter-search", "ajax", {
url: "http://search.twitter.com/search.json",
dataType: "jsonp",
dataMap: {
term: "q"
}
});
amplify.request("twitter-search", { term: "amplifyjs" } );
// Similarly, we can create a request that searches for mentions, by accepting a username:
amplify.request.define("twitter-mentions", "ajax", {
url: "http://search.twitter.com/search.json",
dataType: "jsonp",
dataMap: function (data) {
return {
q: "@" + data.user
};
}
});
amplify.request("twitter-mentions", { user: "amplifyjs" });
// Setting up and using decoders
//Example:
var appEnvelopeDecoder: amplifyDecoder = function (data, status, xhr, success, error) {
if (data.status === "success") {
success(data.data);
} else if (data.status === "fail" || data.status === "error") {
error(data.message, data.status);
} else {
error(data.message, "fatal");
}
};
//a new decoder can be added to the amplifyDecoders interface
interface amplifyDecoders {
appEnvelope: amplifyDecoder;
}
amplify.request.decoders.appEnvelope = appEnvelopeDecoder;
//but you can also just add it via an index
amplify.request.decoders['appEnvelopeStr'] = appEnvelopeDecoder;
amplify.request.define("decoderExample", "ajax", {
url: "/myAjaxUrl",
type: "POST",
decoder: "appEnvelope"
});
amplify.request({
resourceId: "decoderExample",
success: function (data) {
data.foo; // bar
},
error: function (message, level) {
alert("always handle errors with alerts.");
}
});
// POST with caching and single - use decoder
// Example:
amplify.request.define("decoderSingleExample", "ajax", {
url: "/myAjaxUrl",
type: "POST",
decoder: function (data, status, xhr, success, error) {
if (data.status === "success") {
success(data.data);
} else if (data.status === "fail" || data.status === "error") {
error(data.message, data.status);
} else {
error(data.message, "fatal");
}
}
});
amplify.request({
resourceId: "decoderSingleExample",
success: function (data) {
data.foo; // bar
},
error: function (message, level) {
alert("always handle errors with alerts.");
}
});
// Handling Status
// Status in Success and Error Callbacks
// amplify.request comes with built in support for status.The status parameter appears in the default success or error callbacks when using an ajax definition.
amplify.request.define("statusExample1", "ajax", {
//...
});
amplify.request({
resourceId: "statusExample1",
success: function (data, status) {
},
error: function (data, status) {
}
});
-1
View File
@@ -1 +0,0 @@
-182
View File
@@ -1,182 +0,0 @@
// Type definitions for AmplifyJs 1.1.0
// Project: http://amplifyjs.com/
// Definitions by: Jonas Eriksson <https://github.com/joeriks/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface amplifyRequestSettings {
resourceId: string;
data?: any;
success?: (...args: any[]) => void;
error?: (...args: any[]) => void;
}
interface amplifyDecoder {
(
data?: any,
status?: string,
xhr?: JQueryXHR,
success?: (...args: any[]) => void,
error?: (...args: any[]) => void
): void
}
interface amplifyDecoders {
[decoderName: string]: amplifyDecoder;
jsSend: amplifyDecoder;
}
interface amplifyAjaxSettings extends JQueryAjaxSettings {
cache?: any;
dataMap?: {} | ((data: any) => {});
decoder?: any /* string or amplifyDecoder */;
}
interface amplifyRequest {
/***
* Request a resource.
* resourceId: Identifier string for the resource.
* data: A set of key/value pairs of data to be sent to the resource.
* callback: A function to invoke if the resource is retrieved successfully.
*/
(resourceId: string, hash?: any, callback?: Function): void;
/***
* Request a resource.
* settings: A set of key/value pairs of settings for the request.
* resourceId: Identifier string for the resource.
* data (optional): Data associated with the request.
* success (optional): Function to invoke on success.
* error (optional): Function to invoke on error.
*/
(settings: amplifyRequestSettings): any;
/***
* Define a resource.
* resourceId: Identifier string for the resource.
* requestType: The type of data retrieval method from the server. See the request types sections for more information.
* settings: A set of key/value pairs that relate to the server communication technology. The following settings are available:
* Any settings found in jQuery.ajax().
* cache: See the cache section for more details.
* decoder: See the decoder section for more details.
*/
define(resourceId: string, requestType: string, settings?: amplifyAjaxSettings): void;
/***
* Define a custom request.
* resourceId: Identifier string for the resource.
* resource: Function to handle requests. Receives a hash with the following properties:
* resourceId: Identifier string for the resource.
* data: Data provided by the user.
* success: Callback to invoke on success.
* error: Callback to invoke on error.
*/
define(resourceId: string, resource: (settings: amplifyRequestSettings) => void): void;
decoders: amplifyDecoders;
cache: any;
}
interface amplifySubscribe {
/***
* Subscribe to a message.
* topic: Name of the message to subscribe to.
* callback: Function to invoke when the message is published.
*/
(topic: string, callback: Function): void;
/***
* Subscribe to a message.
* topic: Name of the message to subscribe to.
* context: What this will be when the callback is invoked.
* callback: Function to invoke when the message is published.
* [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10.
*/
(topic: string, context: any, callback: Function, priority?: number): void;
/***
* Subscribe to a message.
* topic: Name of the message to subscribe to.
* callback: Function to invoke when the message is published.
* [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10.
*/
(topic: string, callback: Function, priority?: number): void;
}
interface amplifyStorageTypeStore {
/***
* Stores a value for a given key using the default storage type.
*
* key: Identifier for the value being stored.
* value: The value to store. The value can be anything that can be serialized as JSON.
* [options]: A set of key/value pairs that relate to settings for storing the value.
*/
(key: string, value: any, options?: any): void;
/***
* Gets a stored value based on the key.
*/
(key: string): any;
/***
* Gets a hash of all stored values.
*/
(): any;
}
interface amplifyStore extends amplifyStorageTypeStore{
/***
* IE 8+, Firefox 3.5+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+
*/
localStorage: amplifyStorageTypeStore;
/***
* IE 8+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+
*/
sessionStorage: amplifyStorageTypeStore;
/***
* Firefox 2+
*/
globalStorage: amplifyStorageTypeStore;
/***
* IE 5 - 7
*/
userData: amplifyStorageTypeStore;
/***
* An in-memory store is provided as a fallback if none of the other storage types are available.
*/
memory: amplifyStorageTypeStore;
}
interface amplifyStatic {
subscribe: amplifySubscribe;
/***
* Remove a subscription.
* topic: The topic being unsubscribed from.
* callback: The callback that was originally subscribed.
*/
unsubscribe(topic: string, callback: Function): void;
/***
* Publish a message.
* topic: The name of the message to publish.
* Any additional parameters will be passed to the subscriptions.
* amplify.publish returns a boolean indicating whether any subscriptions returned false. The return value is true if none of the subscriptions returned false, and false otherwise. Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked.
*/
publish(topic: string, ...args: any[]): boolean;
store: amplifyStore;
request: amplifyRequest;
}
declare var amplify: amplifyStatic;
declare module "amplify" { export =amplify; }
-72
View File
@@ -1,72 +0,0 @@
// Type definitions for amqp-rpc v0.0.8
// Project: https://github.com/demchenkoe/node-amqp-rpc/
// Definitions by: Wonshik Kim <https://github.com/wokim/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "amqp-rpc" {
export interface Options {
connection?: any;
url?: string;
exchangeInstance?: any;
exchange?: string;
exchange_options?: {
exclusive?: boolean;
autoDelete?: boolean;
};
ipml_options?: {
defaultExchangeName?: string;
}
conn_options?: any;
}
export interface CallOptions {
correlationId?: string;
autoDeleteCallback?: any;
}
export interface HandlerOptions {
queueName?: string;
durable?: boolean;
exclusive?: boolean;
autoDelete?: boolean;
}
export interface BroadcastOptions {
ttl?: number;
onResponse?: any;
context?: any;
onComplete?: any;
}
export interface CommandInfo {
cmd?: string;
exchange?: string;
contentType?: string;
size?: number;
}
export interface Callback {
(...args: any[]): void;
}
export interface CallbackWithError {
(err: any, ...args: any[]): void;
}
export function factory(opt?: Options): amqpRPC;
export class amqpRPC {
constructor(opt?: Options);
generateQueueName(type: string): string;
disconnect(): void;
call<T>(cmd: string, params: T, cb?: Callback, context?: any, options?: CallOptions): string;
on<T>(cmd: string, cb: (param?: T, cb?: Callback, info?: CommandInfo) => void, context?: any, options?: HandlerOptions): boolean;
off(cmd: string): boolean;
callBroadcast<T>(cmd: string, params: T, options?: BroadcastOptions): void;
onBroadcast<T>(cmd: string, cb?: (params?: T, cb?: CallbackWithError) => void, context?: any, options?: any): boolean;
offBroadcast(cmd: string): boolean;
}
}
-67
View File
@@ -1,67 +0,0 @@
/// <reference path="amqplib.d.ts" />
// promise api tests
import amqp = require("amqplib");
var msg = "Hello World";
// test promise api
amqp.connect("amqp://localhost")
.then(connection => {
return connection.createChannel()
.tap(channel => channel.checkQueue("myQueue"))
.then(channel => channel.sendToQueue("myQueue", new Buffer(msg)))
.ensure(() => connection.close());
});
amqp.connect("amqp://localhost")
.then(connection => {
return connection.createChannel()
.tap(channel => channel.checkQueue("myQueue"))
.then(channel => channel.consume("myQueue", newMsg => console.log("New Message: " + newMsg.content.toString())))
.ensure(() => connection.close());
});
// test promise api properties
var amqpMessage: amqp.Message;
amqpMessage.properties.contentType = "application/json";
var amqpAssertExchangeOptions: amqp.Options.AssertExchange;
var anqpAssertExchangeReplies: amqp.Replies.AssertExchange;
// callback api tests
import amqpcb = require("amqplib/callback_api");
amqpcb.connect("amqp://localhost", (err, connection) => {
if(!err) {
connection.createChannel((err, channel) => {
if (!err) {
channel.assertQueue("myQueue", {}, (err, ok) => {
if(!err) {
channel.sendToQueue("myQueue", new Buffer(msg));
}
});
}
});
}
});
amqpcb.connect("amqp://localhost", (err, connection) => {
if(!err) {
connection.createChannel((err, channel) => {
if (!err) {
channel.assertQueue("myQueue", {}, (err, ok) => {
if(!err) {
channel.consume("myQueue", newMsg => console.log("New Message: " + newMsg.content.toString()));
}
});
}
});
}
});
// test callback api properties
var amqpcbMessage: amqpcb.Message;
amqpcbMessage.properties.contentType = "application/json";
var amqpcbAssertExchangeOptions: amqpcb.Options.AssertExchange;
var anqpcbAssertExchangeReplies: amqpcb.Replies.AssertExchange;
-218
View File
@@ -1,218 +0,0 @@
// Type definitions for amqplib 0.3.x
// Project: https://github.com/squaremo/amqp.node
// Definitions by: Michael Nahkies <https://github.com/mnahkies>, Ab Reitsma <https://github.com/abreits>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../when/when.d.ts" />
/// <reference path="../node/node.d.ts" />
declare module "amqplib/properties" {
module Replies {
interface Empty {
}
interface AssertQueue {
queue: string;
messageCount: number;
consumerCount: number;
}
interface PurgeQueue {
messageCount: number;
}
interface DeleteQueue {
messageCount: number;
}
interface AssertExchange {
exchange: string;
}
interface Consume {
consumerTag: string;
}
}
module Options {
interface AssertQueue {
exclusive?: boolean;
durable?: boolean;
autoDelete?: boolean;
arguments?: any;
messageTtl?: number;
expires?: number;
deadLetterExchange?: string;
maxLength?: number;
}
interface DeleteQueue {
ifUnused?: boolean;
ifEmpty?: boolean;
}
interface AssertExchange {
durable?: boolean;
internal?: boolean;
autoDelete?: boolean;
alternateExchange?: string;
arguments?: any;
}
interface DeleteExchange {
ifUnused?: boolean;
}
interface Publish {
expiration?: string;
userId?: string;
CC?: string | string[];
mandatory?: boolean;
persistent?: boolean;
deliveryMode?: boolean | number;
BCC?: string | string[];
contentType?: string;
contentEncoding?: string;
headers?: any;
priority?: number;
correlationId?: string;
replyTo?: string;
messageId?: string;
timestamp?: number;
type?: string;
appId?: string;
}
interface Consume {
consumerTag?: string;
noLocal?: boolean;
noAck?: boolean;
exclusive?: boolean;
priority?: number;
arguments?: any;
}
interface Get {
noAck?: boolean;
}
}
interface Message {
content: Buffer;
fields: any;
properties: any;
}
}
declare module "amqplib" {
import events = require("events");
import when = require("when");
import shared = require("amqplib/properties")
export import Replies = shared.Replies;
export import Options = shared.Options;
export import Message = shared.Message;
interface Connection extends events.EventEmitter {
close(): when.Promise<void>;
createChannel(): when.Promise<Channel>;
createConfirmChannel(): when.Promise<Channel>;
}
interface Channel extends events.EventEmitter {
close(): when.Promise<void>;
assertQueue(queue: string, options?: Options.AssertQueue): when.Promise<Replies.AssertQueue>;
checkQueue(queue: string): when.Promise<Replies.AssertQueue>;
deleteQueue(queue: string, options?: Options.DeleteQueue): when.Promise<Replies.DeleteQueue>;
purgeQueue(queue: string): when.Promise<Replies.PurgeQueue>;
bindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
unbindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
assertExchange(exchange: string, type: string, options?: Options.AssertExchange): when.Promise<Replies.AssertExchange>;
checkExchange(exchange: string): when.Promise<Replies.Empty>;
deleteExchange(exchange: string, options?: Options.DeleteExchange): when.Promise<Replies.Empty>;
bindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
unbindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): when.Promise<Replies.Consume>;
cancel(consumerTag: string): when.Promise<Replies.Empty>;
get(queue: string, options?: Options.Get): when.Promise<Message | boolean>;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
nack(message: Message, allUpTo?: boolean, requeue?: boolean): void;
nackAll(requeue?: boolean): void;
reject(message: Message, requeue?: boolean): void;
prefetch(count: number, global?: boolean): when.Promise<Replies.Empty>;
recover(): when.Promise<Replies.Empty>;
}
function connect(url: string, socketOptions?: any): when.Promise<Connection>;
}
declare module "amqplib/callback_api" {
import events = require("events");
import shared = require("amqplib/properties")
export import Replies = shared.Replies;
export import Options = shared.Options;
export import Message = shared.Message;
interface Connection extends events.EventEmitter {
close(callback?: (err: any) => void): void;
createChannel(callback: (err: any, channel: Channel) => void): void;
createConfirmChannel(callback: (err: any, confirmChannel: ConfirmChannel) => void): void;
}
interface Channel extends events.EventEmitter {
close(callback: (err: any) => void): void;
assertQueue(queue?: string, options?: Options.AssertQueue, callback?: (err:any, ok: Replies.AssertQueue) => void): void;
checkQueue(queue: string, callback?: (err: any, ok: Replies.AssertQueue) => void): void;
deleteQueue(queue: string, options?: Options.DeleteQueue, callback?: (err:any, ok: Replies.DeleteQueue) => void): void;
purgeQueue(queue: string, callback?: (err:any, ok: Replies.PurgeQueue) => void): void;
bindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
unbindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
assertExchange(exchange: string, type: string, options?: Options.AssertExchange, callback?: (err: any, ok: Replies.AssertExchange) => void): void;
checkExchange(exchange: string, callback?: (err: any, ok: Replies.Empty) => void): void;
deleteExchange(exchange: string, options?: Options.DeleteExchange, callback?: (err: any, ok: Replies.Empty) => void): void;
bindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
unbindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume, callback?: (err: any, ok: Replies.Consume) => void): void;
cancel(consumerTag: string, callback?: (err: any, ok: Replies.Empty) => void): void;
get(queue: string, options?: Options.Get, callback?: (err: any, ok: Message | boolean) => void): void;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
nack(message: Message, allUpTo?: boolean, requeue?: boolean): void;
nackAll(requeue?: boolean): void;
reject(message: Message, requeue?: boolean): void;
prefetch(count: number, global?: boolean): void;
recover(callback?: (err: any, ok: Replies.Empty) => void): void;
}
interface ConfirmChannel extends Channel {
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean;
waitForConfirms(callback?: (err: any) => void): void;
}
function connect(callback: (err: any, connection: Connection) => void): void;
function connect(url: string, callback: (err: any, connection: Connection) => void): void;
function connect(url: string, socketOptions: any, callback: (err: any, connection: Connection) => void): void;
}
-91
View File
@@ -1,91 +0,0 @@
/// <reference path="./analytics-node.d.ts" />
var analytics: AnalyticsNode.Analytics;
import Analytics = require("analytics-node");
function testConfig(): void {
analytics = new Analytics('YOUR_WRITE_KEY', {
flushAt: 20,
flushAfter: 10000
});
}
function testIdentify(): void {
analytics.identify({
userId: '019mr8mf4r',
traits: {
name: 'Michael Bolton',
email: 'mbolton@initech.com',
plan: 'Enterprise',
friends: 42
}
});
}
function testTrack(): void {
analytics.track({
userId: '019mr8mf4r',
event: 'Purchased an Item',
properties: {
revenue: 39.95,
shippingMethod: '2-day'
}
});
}
function testPage(): void {
analytics.page({
userId: '019mr8mf4r',
category: 'Docs',
name: 'Node.js Library',
properties: {
url: 'https://segment.com/docs/libraries/node',
path: '/docs/libraries/node/',
title: 'Node.js Library - Segment',
referrer: 'https://github.com/segmentio/analytics-node'
}
});
}
function testAlias(): void {
// the anonymous user does actions ...
analytics.track({ userId: 'anonymous_user', event: 'Anonymous Event' })
// the anonymous user signs up and is aliased
analytics.alias({ previousId: 'anonymous_user', userId: 'identified@gmail.com' })
// the identified user is identified
analytics.identify({ userId: 'identified@gmail.com', traits: { plan: 'Free' } })
// the identified user does actions ...
analytics.track({ userId: 'identified@gmail.com', event: 'Identified Action' })
}
function testGroup(): void {
analytics.group({
userId: '019mr8mf4r',
groupId: '56',
traits: {
name: 'Initech',
description: 'Accounting Software'
}
});
}
function testIntegrations(): void {
analytics.track({
event: 'Upgraded Membershipt',
userId: '97234974',
integrations: {
'All': false,
'Vero': true,
'Google Analytics': false
}
});
}
function testFlush(): void {
analytics.flush();
analytics.flush(function(err, batch) {
if (err) { alert("Oh nos!"); }
else { console.log(batch.batch[0].type); }
});
}
-83
View File
@@ -1,83 +0,0 @@
// Type definitions for Segment's analytics.js for Node.js
// Project: https://segment.com/docs/libraries/node/
// Definitions by: Andrew Fong <https://github.com/fongandrew>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module AnalyticsNode {
interface Integrations {
[index: string]: boolean;
}
export class Analytics {
constructor(writeKey: string, opts?: {
flushAt?: number,
flushAfter?: number
});
/* The identify method lets you tie a user to their actions and record
traits about them. */
identify(message: {
userId: string | number;
traits?: Object;
timestamp?: Date;
context?: Object;
integrations?: Integrations;
}): Analytics;
/* The track method lets you record the actions your users perform. */
track(message: {
userId: string | number;
event: string;
properties?: Object;
timestamp?: Date;
context?: Object;
integrations?: Integrations;
}): Analytics;
/* The page method lets you record page views on your website, along with
optional extra information about the page being viewed. */
page(message: {
userId: string | number;
category?: string;
name?: string;
properties?: Object;
timestamp?: Date;
context?: Object;
integrations?: Integrations;
}): Analytics;
/* alias is how you associate one identity with another. */
alias(message: {
previousId: string | number;
userId: string | number;
integrations?: Integrations;
}): Analytics;
/* Group calls can be used to associate individual users with shared
accounts or companies. */
group(message: {
userId: string | number;
groupId: string | number;
traits?: Object;
context?: Object;
timestamp?: Date;
anonymous_id?: string | number;
integrations?: Integrations;
}): Analytics;
/* Flush batched calls to make sure nothing is left in the queue */
flush(fn?: (err: Error, batch: {
batch: Array<{
type: string;
}>;
messageId: string;
sentAt: Date;
timestamp: Date;
}) => void): Analytics;
}
}
declare module "analytics-node" {
export = AnalyticsNode.Analytics;
}
-106
View File
@@ -1,106 +0,0 @@
// Type definitions for AngularAgility
// Project: https://github.com/AngularAgility/AngularAgility
// Definitions by: Roland Zwaga <https://github.com/rolandzwaga>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path='../angularjs/angular.d.ts' />
declare module aa {
export interface ILabelStrategies {
[strategyName: string]: (element:ng.IAugmentedJQueryStatic, labelText:string, isRequired:boolean)=>void;
}
export interface IFieldGroupStrategies {
[strategyName: string]: (element:ng.IAugmentedJQueryStatic)=>void;
}
export interface IValMsgPlacementStrategies {
[strategyName: string]: (formFieldElement:ng.IAugmentedJQueryStatic, formName:string, formFieldName:string)=>void;
}
export interface IValidIconStrategy {
validIcon:string;
invalidIcon:string;
getContainer(element:ng.IAugmentedJQueryStatic):void;
}
export interface ISpinnerClickStrategies {
[strategyName: string]: (element:ng.IAugmentedJQueryStatic)=>void;
}
export interface IOnNavigateAwayStrategies {
[strategyName: string]: (rootFormScope:ng.IScope, rootForm:ng.IAugmentedJQueryStatic, $injector:ng.auto.IInjectorService)=>void;
}
export interface IValidationMessages {
[validationKey: string]: string;
}
export interface IGlobalSettings {
[settingName: string]: any;
}
export interface IFormExtensionsProvider extends ng.IServiceProvider {
defaultLabelStrategy:string;
defaultFieldGroupStrategy:string;
defaultValMsgPlacementStrategy:string;
validIconStrategy:IValidIconStrategy;
defaultSpinnerClickStrategy:string;
defaultNotifyTarget:string;
defaultOnNavigateAwayStrategy:string;
validationMessages:IValidationMessages;
valMsgForTemplate:string;
confirmResetStrategy:()=>boolean;
globalSettings:IGlobalSettings;
labelStrategies:ILabelStrategies;
fieldGroupStrategies:IFieldGroupStrategies;
valMsgPlacementStrategies:IValMsgPlacementStrategies;
spinnerClickStrategies:ISpinnerClickStrategies;
onNavigateAwayStrategies:IOnNavigateAwayStrategies;
}
export interface INotifyPredicate {
(message:string, options:any, notifier:any):any;
}
export interface INotifyDefaults {
success: INotifyPredicate;
info: INotifyPredicate;
warning: INotifyPredicate;
danger: INotifyPredicate;
error: INotifyPredicate;
}
export interface INotifyConfig {
name:string;
template?:string;
templateName?:string;
options:INotifyOptions;
namedDefaults:INotifyDefaults;
}
export interface INotifyOptions {
cssClasses?:string;
messageType:string;
allowHtml:boolean;
message:string;
}
export interface INotifyConfigProvider extends ng.IServiceProvider {
notifyConfigs:any;
defaultTargetContainerName:string;
defaultNotifyConfig:string;
addOrUpdateNotifyConfig(name:string, opts:INotifyConfig):void;
optionsTransformer(options:INotifyOptions, $sce:ng.ISCEService):void;
}
export interface IExternalFormValidationConfig {
validations:any;
ignore?:any;
globals?:any;
resolve?:any;
resolveFn?:(modelValue:string)=>string;
}
}
@@ -1,51 +0,0 @@
// Type definitions for angular-bootstrap-lightbox
// Project: https://github.com/compact/angular-bootstrap-lightbox
// Definitions by: Roland Zwaga <https://github.com/rolandzwaga>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module angular.bootstrap.lightbox {
export interface ILightboxImageInfo {
url: string;
width: number;
height: number;
thumbUrl?: string;
caption?: string;
}
export interface IImageDimensionLimits {
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
}
export interface IImageDimensionParameter {
windowWidth:number;
windowHeight:number;
imageWidth:number;
imageHeight:number;
}
export interface IModalDimensionsParameter {
windowWidth:number;
windowHeight:number;
imageDisplayWidth:number;
imageDisplayHeight:number;
}
export interface IModalDimensions {
width:number;
height:number;
}
export interface ILightbox {
openModal(images:ILightboxImageInfo[], index:number):void;
}
export interface ILightBoxProvider {
templateUrl:string;
calculateImageDimensionLimits:(dimensions:IImageDimensionParameter)=>IImageDimensionLimits;
calculateModalDimensions:(dimensions:IModalDimensionsParameter)=>IModalDimensions;
}
}
-82
View File
@@ -1,82 +0,0 @@
// Type definitions for Angular Dialog Service 5.2.8
// Project: https://github.com/m-e-conroy/angular-dialog-service
// Definitions by: William Comartin <https://github.com/wcomartin>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts"/>
/// <reference path="../angular-ui-bootstrap/angular-ui-bootstrap.d.ts"/>
declare module angular.dialogservice {
interface IDialogOptions {
/**
* Set to false to disable animations on new modal/backdrop. Does not toggle animations for modals/backdrops that are already displayed.
*
* @default false
*/
animation?: boolean;
/**
* controls the presence of a backdrop
* Allowed values:
* - true (default)
* - false (no backdrop)
* - 'static' backdrop is present but modal window is not closed when clicking outside of the modal window
*
* @default true
*/
backdrop?: boolean | string;
/**
* indicates whether the dialog should be closable by hitting the ESC key
*
* @default true
*/
keyboard?: boolean;
/**
* additional CSS class(es) to be added to a modal backdrop template
*
* @default 'dialogs-backdrop-default'
*/
backdropClass?: string;
/**
* additional CSS class(es) to be added to a modal window template
*
* @default 'dialogs-default'
*/
windowClass?: string;
/**
* Optional suffix of modal window class. The value used is appended to the `modal-` class, i.e. a value of `sm` gives `modal-sm`.
*
* @default 'lg'
*/
size?: string;
}
interface IDialogService {
/**
* Opens a new error modal instance.
*/
error(header: string, msg: string, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance
/**
* Opens a new wait modal instance.
*/
wait(header: string, msg: string, progress: number, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance
/**
* Opens a new notify modal instance.
*/
notify(header: string, msg: string, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance
/**
* Opens a new confirm modal instance.
*/
confirm(header: string, msg: string, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance
/**
* Opens a new custom modal instance.
*/
create(url: string, ctrlr: string, data: any, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance
}
}
-26
View File
@@ -1,26 +0,0 @@
// 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-dynamic-locale" {
import ng = angular.dynamicLocale;
export = ng;
}
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;
}
}
-8
View File
@@ -1,8 +0,0 @@
// 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="../ng-file-upload/ng-file-upload.d.ts" />
// THIS FILE WILL REMOVE IF angular-file-upload.d.ts incoming.
-621
View File
@@ -1,621 +0,0 @@
// Type definitions for angular-formly 7.2.3
// Project: https://github.com/formly-js/angular-formly
// Definitions by: Scott Hatcher <https://github.com/scatcher>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module 'AngularFormly' {
export = AngularFormly;
}
declare module 'angular-formly' {
var angularFormlyDefaultExport: string;
export = angularFormlyDefaultExport;
}
declare module AngularFormly {
interface IFieldArray extends Array<IFieldConfigurationObject | IFieldGroup> {
}
interface IFieldGroup {
data?: Object;
className?: string;
elementAttributes?: string;
fieldGroup?: IFieldArray;
form?: Object;
hide?: boolean;
hideExpression?: string | IExpressionFunction;
key?: string | number;
model?: string | Object;
options?: IFormOptionsAPI;
templateOptions?: ITemplateOptions;
wrapper?: string | string[];
}
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 IExpressionFunction {
($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[];
}
interface ISelectOption {
name: string;
value?: string;
group?: string;
}
/**
* 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;
// types for select/radio fields
options?: Array<ISelectOption>;
groupProp?: string; // default: group
valueProp?: string; // default: value
labelProp?: string; // default: name
}
/**
* see http://docs.angular-formly.com/docs/field-configuration-object#validators-object
*/
interface IValidator {
expression: string | IExpressionFunction;
message?: string | IExpressionFunction;
}
/**
* 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 | IExpressionFunction | 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 | IExpressionFunction | 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 | IExpressionFunction;
/**
* 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;
[key: string]: any;
};
/**
* This allows you to place attributes with string values on the ng-model element.
* Easy to use alternative to ngModelAttrs option.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#ngmodelelattrs-object
*/
ngModelElAttrs?: {
[key: string]: string;
};
/**
* 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]: IExpressionFunction | 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 | IExpressionFunction | 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 IFormlyConfigExtras {
disableNgModelAttrsManipulator: boolean;
apiCheckInstance: any;
ngModelAttrsManipulatorPreferUnbound: boolean;
removeChromeAutoComplete: boolean;
defaultHideDirective: string;
errorExistsAndShouldBeVisibleExpression: any;
getFieldId: Function;
fieldTransform: Function;
explicitAsync: boolean;
}
interface IFormlyConfig {
disableWarnings: boolean;
extras: IFormlyConfigExtras;
setType(typeOptions: ITypeOptions): void;
setWrapper(wrapperOptions: IWrapperOptions): void;
templateManipulators: ITemplateManipulators;
}
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: IFieldArray;
//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 };
}
}

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