Merge pull request #1 from DefinitelyTyped/master

Update from master
This commit is contained in:
Alexander Christie
2018-03-20 15:23:40 +00:00
committed by GitHub
29717 changed files with 3031213 additions and 1911462 deletions

View File

@@ -1,9 +1,9 @@
root = true
[*]
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
[{*.json,*.yml}]
indent_style = space
indent_size = 2

20
.gitattributes vendored
View File

@@ -1,22 +1,2 @@
# Auto detect text files and perform LF normalization
* 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

4118
.github/CODEOWNERS vendored Normal file

File diff suppressed because it is too large Load Diff

9
.github/ISSUE_TEMPLATE.md vendored Normal file
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
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
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 provide its own types, and you can not add them.
- [ ] 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`.

17
.gitignore vendored
View File

@@ -9,11 +9,9 @@
*.cs
*.sln
*.csproj
*.txt
*.map
*.swp
.DS_Store
npm-debug.log
_Resharper.DefinitelyTyped
bin
@@ -26,13 +24,28 @@ Properties
# 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

View File

@@ -1,6 +1,6 @@
language: node_js
node_js:
- 4
- 8
sudo: false

View File

@@ -1,52 +0,0 @@
/// <reference path="3d-bin-packing.d.ts" />
import packer = require("3d-bin-packing");
import samchon = require("samchon-framework");
function main(): void
{
///////////////////////////
// CONSTRUCT OBJECTS
///////////////////////////
let wrapperArray: bws.packer.WrapperArray = new packer.WrapperArray();
let instanceArray: bws.packer.InstanceArray = new packer.InstanceArray();
// Wrappers
wrapperArray.push
(
new packer.Wrapper("Large", 1000, 40, 40, 15, 0),
new packer.Wrapper("Medium", 700, 20, 20, 10, 0),
new packer.Wrapper("Small", 500, 15, 15, 8, 0)
);
///////
// Each Instance is repeated #15
///////
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Eraser", 1, 2, 5));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Book", 15, 30, 3));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Drink", 3, 3, 10));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Umbrella", 5, 5, 20));
// Wrappers also can be packed into another Wrapper.
instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Notebook-Box", 2000, 30, 40, 4, 2));
instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Tablet-Box", 2500, 20, 28, 2, 0));
///////////////////////////
// BEGINS PACKING
///////////////////////////
// CONSTRUCT PACKER
let my_packer: bws.packer.Packer = new packer.Packer(wrapperArray, instanceArray);
///////
// PACK (OPTIMIZE)
let result: bws.packer.WrapperArray = my_packer.optimize();
///////
///////////////////////////
// TRACE PACKING RESULT
///////////////////////////
let xml: samchon.library.XML = result.toXML();
console.log(xml.toString());
}
main();

File diff suppressed because it is too large Load Diff

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.

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +0,0 @@
/// <reference path="CybozuLabs-md5.d.ts" />
var hash: string;
hash = CybozuLabs.MD5.calc("abc");
hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_ASCII);
hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_UTF16);
var version: string;
version = CybozuLabs.MD5.VERSION;

View File

@@ -1,21 +0,0 @@
/// <reference path="FileSaver.d.ts" />
import {saveAs as importedSaveAs} from "file-saver";
function testImportedSaveAs() {
var data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
var filename: string = 'hello world.txt';
var disableAutoBOM = true;
importedSaveAs(data, filename, disableAutoBOM);
}
/**
* @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);
}

View File

@@ -1,38 +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/DefinitelyTyped/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;
declare module "file-saver" {
var fileSaver: { saveAs: typeof saveAs };
export = fileSaver
}

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");
}

View File

@@ -1,29 +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/DefinitelyTyped/DefinitelyTyped
interface HeadroomOptions {
offset?: number;
tolerance?: any;
classes?: {
initial?: string;
notBottom?:string;
notTop?: string;
pinned?: string;
top?: string;
unpinned?: 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;
}

View File

@@ -1,61 +0,0 @@
/// <reference path="HubSpot-pace.d.ts" />
pace.start({
document: false
});
pace.start();
pace.restart();
pace.stop();
var paceOptions: HubSpotPaceInterfaces.PaceOptions;
paceOptions = {
// Disable the 'elements' source
elements: false,
// Only show the progress on regular and ajax-y page navigation,
// not every request
restartOnRequestAfter: false
}
paceOptions = {
ajax: false, // disabled
document: false, // disabled
eventLag: false, // disabled
elements: {
selectors: ['.my-page']
}
};
paceOptions = {
elements: {
selectors: ['.timeline,.timeline-error', '.user-profile,.profile-error']
}
}
paceOptions = {
restartOnPushState: false
}
paceOptions = {
restartOnRequestAfter: false
}
pace.options = {
restartOnRequestAfter: false
}
pace.ignore(function(){
});
pace.track(function(){
});
pace.options = {
ajax: {
ignoreURLs: ['some-substring', /some-regexp/]
}
};

View File

@@ -1,5 +0,0 @@
- [ ] I tried using the latest `xxxx/xxxx.d.ts` file in this repo 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).
- [ ] I want to talk about `xxxx/xxxx.d.ts`.
- The authors of that type definition are cc/ @....

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('{', ',', '}');

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/DefinitelyTyped/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;
}

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/DefinitelyTyped/DefinitelyTyped
/// <reference path="../threejs/three.d.ts" />
declare namespace 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 namespace 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 namespace 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 namespace 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 namespace 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 namespace 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 namespace CSG {
class Polygon2D extends CAG {
constructor(points: Vector2D[]);
}
}

View File

@@ -1,16 +0,0 @@
Please fill in this template.
- [ ] Prefer to make your PR against the `types-2.0` branch.
- [ ] The package does not provide its own types, and you can not add them.
- [ ] Test the change in your own code.
- [ ] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped#make-a-pull-request).
- [ ] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped#common-mistakes).
If adding a new definition:
- [ ] If this is for an NPM package, match the name. If not, do not conflict with the name of an NPM package.
- [ ] Run `tsc` without errors.
- [ ] Include the required [files](https://github.com/DefinitelyTyped/DefinitelyTyped#create-a-new-package) and header.
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.

View File

@@ -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) => {});

335
README.es.md Normal file
View File

@@ -0,0 +1,335 @@
# 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.
* 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)

284
README.md
View File

@@ -1,4 +1,4 @@
# 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)
@@ -6,12 +6,12 @@
Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date.
*[You can also read this README in Spanish!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md)*
## What are declaration files?
See the [TypeScript handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
## How do I get them?
### npm
@@ -38,7 +38,7 @@ or just look for any ".d.ts" files in the package and manually include them with
These can be used by TypeScript 1.0.
* [Typings](https://github.com/typings/typings)
* [NuGet](http://nuget.org/Tpackages?q=DefinitelyTyped)
* ~~[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).
@@ -52,42 +52,52 @@ DefinitelyTyped only works because of contributions by users like you!
Before you share your improvement with the world, use it yourself.
#### Test editing an exiting package
#### Test editing an existing package
To add new features you can use [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html).
You can also directly edit the types in `node_modules/@types/foo/index.d.ts`,
or copy them from there and paste inside of `declarations.d.ts` and follow the steps below.
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.
#### Test a new package
* Add a new file `declarations.d.ts` to your project.
* Add it to the compilation, through `"includes"` or `"files"` in your [tsconfig](http://www.typescriptlang.org/docs/handbook/tsconfig-json.html),
or through a `/// <reference path="" />` declaration in your code.
* Inside `declarations.d.ts`, write `declare module "foo" { }`, then write the module declaration inside.
* Test that your code works.
* *Then*, once you've tested your definitions, make a PR contributing the definition.
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.
Then inside your repository:
* `git checkout types-2.0`
New work should generally be done on the `types-2.0` branch.
If you want your changes to be available to `typings` users, then you may edit `master` instead.
First, [fork](https://guides.github.com/activities/forking/) this repository, install [node](https://nodejs.org/), and run `npm install`.
#### Edit an existing package
* `cd my-package-to-edit`
* `cd types/my-package-to-edit`
* Make changes. Remember to edit tests.
* You may also want to add yourself to "Definitions by" section of the package header.
* `npm install -g typescript@2.0` and run `tsc`.
- 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.
@@ -95,7 +105,7 @@ 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, or can make a pull request to the library, [bundle](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) types instead of publishing to DefinitelyTyped.
If you are the library author, or can make a pull request to the library, [bundle types](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) 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.
@@ -108,124 +118,214 @@ Your package should have this structure:
| 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. |
`index.d.ts` should start with a header looking like:
Generate these by running `npm install -g dts-gen` and `dts-gen --dt --name my-package-name --template module`.
See all options at [dts-gen](https://github.com/Microsoft/dts-gen).
```ts
// Type definitions for foo 1.2
// Project: https://github.com/baz/foo
// Definitions by: My Self <https://github.com/me>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
```
The `Project` link does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.
`tsconfig.json` should look like this:
```json
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"foo-tests.ts"
]
}
```
These should be identical accross projects except that `foo-tests` will be replaced with the name of your test file,
and you may also add the `"jsx"` compiler option if your library needs it.
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/types-2.0/base64-js).
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. Also, always use semicolons, and use egyptian braces.
* `interface X {}`: An empty interface is essentially the `{}` type: it places no constraints on an object.
* `interface IFoo {}`: Don't add `I` to the front of an interface name.
* 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(); }
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.
* `namespace foo {}`:
Do not add a namespace just so that the `import * as foo` syntax will work.
If it is commonJs module with a single export, you should use the `import foo = require("foo")` syntax.
See more explanation [here](https://stackoverflow.com/questions/39415661/why-cant-i-import-a-class-or-function-with-import-as-x-from-y).
* `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.
Make a PR doing the following:
* Delete the directory.
* Add a new entry to `notNeededPackages.json`.
- `libraryName`: Descriptive name of the library, e.g. "Angular 2" instead of "angular2". (May be identical to "typingsPackageName".)
- `typingsPackageName`: This is the name of the directory you just deleted.
- `sourceRepoURL`: This should point to the repository that contains the typings.
- `asOfVersion`: A stub will be published to `@types/foo` with this version. Should be higher than any currently published version.
* 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" }`.
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 `types-2.0` branch is automatically published to the `@types` scope on NPM thanks to [types-publisher](https://github.com/Microsoft/types-publisher).
This usually happens within an hour of changes being merged.
The `master` branch is automatically published to the `@types` scope on NPM thanks to [types-publisher](https://github.com/Microsoft/types-publisher).
Changes to the `master` branch are also manually merged into the `types-2.0` branch, but this takes longer.
#### 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 referenceing is an ambient module (uses `declare module`, or just declares globals), use `<reference types="" />`.
#### What do I do about older versions of typings?
Currently we don't support this, though it is [planned](https://github.com/Microsoft/types-publisher/issues/3).
If you're adding a new major version of a library, you can copy `index.d.ts` to `foo-v2.3.d.ts` and edit `index.d.ts` to be the new version.
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/types-2.0/pikaday/package.json).
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.
#### I notice some `tsconfig.json` are missing `"noImplicitAny": true` or `"strictNullChecks": true`.
#### 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.
#### Definitions in types-2.0 seem written differently than in master.
If you're targeting types-2.0, write it like the types-2.0 definitions.
If you're targeting master, we may change it to the new style when merging from master to types-2.0.
#### 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 default imports work in your environment, 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

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) => {
});

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/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts"/>
declare namespace 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;
}

View File

@@ -1,5 +0,0 @@
/// <reference path="./abs.d.ts" />
import Abs from 'abs';
const x: string = Abs('/foo');

14
abs/abs.d.ts vendored
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;
}

View File

@@ -1,5 +0,0 @@
/// <reference path="./absolute.d.ts" />
import absolute from 'absolute';
const x: boolean = absolute('/home/foo');

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;
}

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/DefinitelyTyped/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;
}

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/DefinitelyTyped/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;
}

2983
ace/ace.d.ts vendored

File diff suppressed because it is too large Load Diff

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" />

View File

@@ -1 +0,0 @@

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));
}
};

View File

@@ -1 +0,0 @@

View File

@@ -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"])
}
};

View File

@@ -1,454 +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.on("blur", (e) => e);
editor.on("change", (e) => e);
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);

View File

@@ -1 +0,0 @@

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());
}
};

View File

@@ -1 +0,0 @@

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);
}
};

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);
}
};

View File

@@ -1 +0,0 @@

View File

@@ -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);
}
};

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);
}
};

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);
}
};

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);
}
};

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);
}
};

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);
}
};

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);
}
};

View File

@@ -1 +0,0 @@

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);
},
};

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);
}
};

View File

@@ -1 +0,0 @@

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);
}
};

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)
};

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']);

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']);

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
acl/acl.d.ts vendored
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/DefinitelyTyped/DefinitelyTyped
/// <reference path="../bluebird/bluebird-2.0.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.IncomingMessage, 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 = _;
}

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
acorn/acorn.d.ts vendored
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/DefinitelyTyped/DefinitelyTyped
/// <reference path="../estree/estree.d.ts" />
declare namespace 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
}

View File

@@ -1,46 +0,0 @@
/// <reference path="adal-angular.d.ts" />
// Code samples from:
// - https://github.com/AzureAD/azure-activedirectory-library-for-js
// - https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp
// Variable provided by AngularJS
var $httpProvider: angular.IHttpProvider = null;
var adalAuthenticationServiceProvider: adal.AdalAuthenticationServiceProvider = null;
var adalAuthenticationService: adal.AdalAuthenticationService = null;
var endpoints = {
"https://yourhost/api": "b6a68585-5287-45b2-ba82-383ba1f60932",
};
adalAuthenticationServiceProvider.init({
tenant: "52d4b072-9470-49fb-8721-bc3a1c9912a1",
clientId: "e9a5a8b6-8af7-4719-9821-0deef255f68e",
endpoints: endpoints
},
$httpProvider
);
adalAuthenticationServiceProvider.init({
clientId: "e9a5a8b6-8af7-4719-9821-0deef255f68e"
},
$httpProvider
);
adalAuthenticationServiceProvider.init(
{
clientId: 'cb68f72f...',
cacheLocation: 'localStorage'
},
$httpProvider // pass http provider to inject request interceptor to attach tokens
);
adalAuthenticationServiceProvider.init({
tenant: 'Enter your tenant name here e.g. contoso.onmicrosoft.com',
clientId: 'Enter your client ID here e.g. e9a5a8b6-8af7-4719-9821-0deef255f68e',
extraQueryParameter: 'nux=1'
},
$httpProvider
);
adalAuthenticationService.login();
adalAuthenticationService.logOut();

View File

@@ -1,40 +0,0 @@
// Type definitions for ADAL.JS 1.0.8
// Project: https://github.com/AzureAD/azure-activedirectory-library-for-js
// Definitions by: mmaitre314 <https://github.com/mmaitre314>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="adal.d.ts" />
/// <reference path="../angularjs/angular.d.ts" />
declare namespace adal {
interface AdalAuthenticationServiceProvider {
init(configOptions: Config, httpProvider: angular.IHttpProvider): void;
}
interface UserInfo {
isAuthenticated: boolean,
userName: string,
loginError: string,
profile: any
}
interface AdalAuthenticationService {
config: Config;
userInfo: UserInfo,
login(): void;
loginInProgress(): boolean;
logOut(): void;
getCachedToken(resource: string): string;
acquireToken(resource: string): angular.IPromise<string>;
getUser(): angular.IPromise<User>;
getResourceForEndpoint(endpoint: string): string,
clearCache(): void;
clearCacheForResource(resource: string): void;
info(message: string): void;
verbose(message: string): void;
}
}

View File

@@ -1,25 +0,0 @@
/// <reference path="adal.d.ts" />
var endpoints = {
"https://yourhost/api": "b6a68585-5287-45b2-ba82-383ba1f60932",
};
var config : adal.Config = {
tenant: "52d4b072-9470-49fb-8721-bc3a1c9912a1", // Optional by default, it sends common
clientId: "e9a5a8b6-8af7-4719-9821-0deef255f68e", // Required
endpoints: endpoints // If you need to send CORS api requests.
};
var auth = new AuthenticationContext(config);
Logging.log = (message: string) => {
console.log(message);
}
Logging.level = 4;
auth.info("Logging message");
var userName: string = auth.getCachedUser().userName;
var postLogoutRedirectUrl = auth.config.postLogoutRedirectUri;
var isValidRequest = auth.getRequestInfo('hash').valid;

169
adal-angular/adal.d.ts vendored
View File

@@ -1,169 +0,0 @@
// Type definitions for ADAL.JS 1.0.8
// Project: https://github.com/AzureAD/azure-activedirectory-library-for-js
// Definitions by: mmaitre314 <https://github.com/mmaitre314>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare var AuthenticationContext: adal.AuthenticationContextStatic;
declare var Logging: adal.Logging;
declare module 'adal' {
export = { AuthenticationContext, Logging };
}
declare namespace adal {
interface Config {
tenant?: string;
clientId: string;
redirectUri?: string;
cacheLocation?: string;
displayCall?: (urlNavigate: string) => any;
correlationId?: string;
loginResource?: string;
resource?: string;
endpoints?: any; // If you need to send CORS api requests.
extraQueryParameter?: string;
postLogoutRedirectUri?: string; // redirect url after succesful logout operation
}
interface User {
userName: string;
profile: any;
}
interface RequestInfo {
valid: boolean;
parameters: any;
stateMatch: boolean;
stateResponse: string;
requestType: string;
}
interface Logging {
log: (message: string) => void;
level: LoggingLevel;
}
enum LoggingLevel {
ERROR = 0,
WARNING = 1,
INFO = 2,
VERBOSE = 3
}
interface AuthenticationContextStatic {
new (config: Config): AuthenticationContext;
}
interface AuthenticationContext {
instance: string;
config: Config;
/**
* Gets initial Idtoken for the app backend
* Saves the resulting Idtoken in localStorage.
*/
login(): void;
/**
* Indicates whether login is in progress now or not.
*/
loginInProgress(): boolean;
/**
* Gets token for the specified resource from local storage cache
* @param {string} resource A URI that identifies the resource for which the token is valid.
* @returns {string} token if exists and not expired or null
*/
getCachedToken(resource: string): string;
/**
* Retrieves and parse idToken from localstorage
* @returns {User} user object
*/
getCachedUser(): User;
registerCallback(expectedState: string, resource: string, callback: (message: string, token: string) => any): void;
/**
* Acquire token from cache if not expired and available. Acquires token from iframe if expired.
* @param {string} resource ResourceUri identifying the target resource
* @param {requestCallback} callback
*/
acquireToken(resource: string, callback: (message: string, token: string) => any): void;
/**
* Redirect the Browser to Azure AD Authorization endpoint
* @param {string} urlNavigate The authorization request url
*/
promptUser(urlNavigate: string): void;
/**
* Clear cache items.
*/
clearCache(): void;
/**
* Clear cache items for a resource.
*/
clearCacheForResource(resource: string): void;
/**
* Logout user will redirect page to logout endpoint.
* After logout, it will redirect to post_logout page if provided.
*/
logOut(): void;
/**
* Gets a user profile
* @param {requestCallback} callback - The callback that handles the response.
*/
getUser(callback: (message: string, user?: User) => any): void;
/**
* Checks if hash contains access token or id token or error_description
* @param {string} hash - Hash passed from redirect page
* @returns {Boolean}
*/
isCallback(hash: string): boolean;
/**
* Gets login error
* @returns {string} error message related to login
*/
getLoginError(): string;
/**
* Gets requestInfo from given hash.
* @returns {RequestInfo} for appropriate hash.
*/
getRequestInfo(hash: string): RequestInfo;
/**
* Saves token from hash that is received from redirect.
*/
saveTokenFromHash(requestInfo: RequestInfo): void;
/**
* Gets resource for given endpoint if mapping is provided with config.
* @param {string} endpoint - API endpoint
* @returns {string} resource for this API endpoint
*/
getResourceForEndpoint(endpoint: string): string;
/**
* Handles redirection after login operation.
* Gets access token from url and saves token to the (local/session) storage
* or saves error in case unsuccessful login.
*/
handleWindowCallback(): void;
log(level: number, message: string, error: any): void;
error(message: string, error: any): void;
warn(message: string): void;
info(message: string): void;
verbose(message: string): void;
}
}

View File

@@ -1,5 +0,0 @@
/// <reference path="add2home.d.ts" />
addToHome.show(false);
addToHome.close();
addToHome.reset();

307
adm-zip/adm-zip.d.ts vendored
View File

@@ -1,307 +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>, Abner Oliveira <https://github.com/abner>
// Definitions: https://github.com/DefinitelyTyped/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;
/**
* 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
* @param callback The callback function will be called afeter extraction
*/
extractAllToAsync(targetPath: string, overwrite: boolean, callback: (error: Error) => void): 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;
}
namespace 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;
}

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
ag-grid/ag-grid.d.ts vendored

File diff suppressed because it is too large Load Diff

451
agenda/agenda.d.ts vendored
View File

@@ -1,451 +0,0 @@
// Type definitions for Agenda v0.8.9
// Project: https://github.com/rschmukler/agenda
// Definitions by: Meir Gottlieb <https://github.com/meirgottlieb>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path='../node/node.d.ts' />
/// <reference path='../mongodb/mongodb.d.ts' />
declare module "agenda" {
import {EventEmitter} from "events";
import {Db, Collection, ObjectID} from "mongodb";
interface Callback {
(err?: Error): void;
}
interface ResultCallback<T> {
(err?: Error, result?: T): void;
}
class Agenda extends EventEmitter {
/**
* Constructs a new Agenda object.
* @param config Optional configuration to initialize the Agenda.
* @param cb Optional callback called with the MongoDB colleciton.
*/
constructor(config?: Agenda.AgendaConfiguration, cb?: ResultCallback<Collection>);
/**
* Connect to the specified MongoDB server and database.
*/
database(url: string, collection?: string, options?: any, cb?: ResultCallback<Collection>): Agenda;
/**
* Initialize agenda with an existing MongoDB connection.
*/
mongo(db: Db, collection?: string, cb?: ResultCallback<Collection>): Agenda;
/**
* Sets the agenda name.
*/
name(value: string): Agenda;
/**
* Sets the interval with which the queue is checked. A number in milliseconds or a frequency string.
*/
processEvery(interval: string | number): Agenda;
/**
* Takes a number which specifies the max number of jobs that can be running at any given moment. By default it
* is 20.
* @param value The value to set.
*/
maxConcurrency(value: number): Agenda;
/**
* Takes a number which specifies the default number of a specific job that can be running at any given moment.
* By default it is 5.
* @param value The value to set.
*/
defaultConcurrency(value: number): Agenda;
/**
* Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is
* 0 for no max.
* @param value The value to set.
*/
lockLimit(value: number): Agenda;
/**
* Takes a number which specifies the default number of a specific job that can be locked at any given moment.
* By default it is 0 for no max.
* @param value The value to set.
*/
defaultLockLimit(value: number): Agenda;
/**
* Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This
* can be overridden by specifying the lockLifetime option to a defined job.
* @param value The value to set.
*/
defaultLockLifetime(value: number): Agenda;
/**
* Returns an instance of a jobName with data. This does NOT save the job in the database. See below to learn
* how to manually work with jobs.
* @param name The name of the job.
* @param data Data to associated with the job.
*/
create(name: string, data?: any): Agenda.Job;
/**
* Find all Jobs matching `query` and pass same back in cb().
* @param query
* @param cb
*/
jobs(query: any, cb: ResultCallback<Agenda.Job[]>): void;
/**
* Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want
* to remove old jobs.
* @param cb Called with the number of jobs removed.
*/
purge(cb?: ResultCallback<number>): void;
/**
* Defines a job with the name of jobName. When a job of job name gets run, it will be passed to fn(job, done).
* To maintain asynchronous behavior, you must call done() when you are processing the job. If your function is
* synchronous, you may omit done from the signature.
* @param name The name of the jobs.
* @param options The options for the job.
* @param handler The handler to execute.
*/
define(name: string, handler: (job?: Agenda.Job, done?: (err?: Error) => void) => void): void;
define(name: string, options: Agenda.JobOptions, handler: (job?: Agenda.Job, done?: (err?: Error) => void) => void): void;
/**
* Runs job name at the given interval. Optionally, data and options can be passed in.
* @param interval Can be a human-readable format String, a cron format String, or a Number.
* @param names The name or names of the job(s) to run.
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
* @param options An optional argument that will be passed to job.repeatEvery.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
every(interval: number | string, names: string, data?: any, options?: any, cb?: ResultCallback<Agenda.Job>): Agenda.Job;
every(interval: number | string, names: string[], data?: any, options?: any, cb?: ResultCallback<Agenda.Job[]>): Agenda.Job[];
/**
* Schedules a job to run name once at a given time.
* @param when A Date or a String such as tomorrow at 5pm.
* @param names The name or names of the job(s) to run.
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
schedule(when: Date | string, names: string, data?: any, cb?: ResultCallback<Agenda.Job>): Agenda.Job;
schedule(when: Date | string, names: string[], data?: any, cb?: ResultCallback<Agenda.Job[]>): Agenda.Job[];
/**
* Schedules a job to run name once immediately.
* @param name The name of the job to run.
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
now(name: string, data?: any, cb?: ResultCallback<Agenda.Job>): Agenda.Job;
/**
* Cancels any jobs matching the passed mongodb-native query, and removes them from the database.
* @param query Mongodb native query.
* @param cb Called with the number of jobs removed.
*/
cancel(query: any, cb?: ResultCallback<number>): void;
/**
* Starts the job queue processing, checking processEvery time to see if there are new jobs.
*/
start(): void;
/**
* Stops the job queue processing. Unlocks currently running jobs.
* @param cb Called after the job processing queue shuts down and unlocks all jobs.
*/
stop(cb: Callback): void;
}
namespace Agenda {
/**
* Agenda Configuration.
*/
interface AgendaConfiguration {
/**
* Sets the interval with which the queue is checked. A number in milliseconds or a frequency string.
*/
processEvery?: string | number;
/**
* Takes a number which specifies the default number of a specific job that can be running at any given moment.
* By default it is 5.
*/
defaultConcurrency?: number;
/**
* Takes a number which specifies the max number of jobs that can be running at any given moment. By default it
* is 20.
*/
maxConcurrency?: number;
/**
* Takes a number which specifies the default number of a specific job that can be locked at any given moment.
* By default it is 0 for no max.
*/
defaultLockLimit?: number;
/**
* Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is
* 0 for no max.
*/
lockLimit?: number;
/**
* Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This
* can be overridden by specifying the lockLifetime option to a defined job.
*/
defaultLockLifetime?: number;
/**
* Specifies that Agenda should be initialized using and existing MongoDB connection.
*/
mongo?: {
/**
* The MongoDB database connection to use.
*/
db: Db;
/**
* The name of the collection to use.
*/
collection?: string;
}
/**
* Specifies that Agenda should connect to MongoDB.
*/
db?: {
/**
* The connection URL.
*/
address: string;
/**
* The name of the collection to use.
*/
collection?: string;
/**
* Connection options to pass to MongoDB.
*/
options?: any;
}
}
/**
* The database record associated with a job.
*/
interface JobAttributes {
/**
* The record identity.
*/
_id: ObjectID;
/**
* The name of the job.
*/
name: string;
/**
* The type of the job (single|normal).
*/
type: string;
/**
* The job details.
*/
data: { [name: string]: any };
/**
* The priority of the job.
*/
priority: number;
/**
* How often the job is repeated using a human-readable or cron format.
*/
repeatInterval: string | number;
/**
* The timezone that conforms to [moment-timezone](http://momentjs.com/timezone/).
*/
repeatTimezone: string;
/**
* Date/time the job was las modified.
*/
lastModifiedBy: string;
/**
* Date/time the job will run next.
*/
nextRunAt: Date;
/**
* Date/time the job was locked.
*/
lockedAt: Date;
/**
* Date/time the job was last run.
*/
lastRunAt: Date;
/**
* Date/time the job last finished running.
*/
lastFinishedAt: Date;
/**
* The reason the job failed.
*/
failReason: string;
/**
* The number of times the job has failed.
*/
failCount: number;
/**
* The date/time the job last failed.
*/
failedAt: Date;
/**
* Job's state
*/
disabled: boolean
}
/**
* A scheduled job.
*/
interface Job {
/**
* The database record associated with the job.
*/
attrs: JobAttributes;
/**
* Specifies an interval on which the job should repeat.
* @param interval A human-readable format String, a cron format String, or a Number.
* @param options An optional argument that can include a timezone field. The timezone should be a string as
* accepted by moment-timezone and is considered when using an interval in the cron string format.
*/
repeatEvery(interval: string | number, options?: { timezone?: string }): Job
/**
* Specifies a time when the job should repeat. [Possible values](https://github.com/matthewmueller/date#examples).
* @param time
*/
repeatAt(time: string): Job
/**
* Disables the job.
*/
disable(): Job;
/**
* Enables the job.
*/
enable(): Job;
/**
* Ensure that only one instance of this job exists with the specified properties
* @param value The properties associated with the job that must be unqiue.
* @param opts
*/
unique(value: any, opts?: { insertOnly?: boolean }): Job;
/**
* Specifies the next time at which the job should run.
* @param time The next time at which the job should run.
*/
schedule(time: string | Date): Job;
/**
* Specifies the priority weighting of the job.
* @param value The priority of the job (lowest|low|normal|high|highest|number).
*/
priority(value: string | number): Job;
/**
* Sets job.attrs.failedAt to now, and sets job.attrs.failReason to reason.
* @param reason A message or Error object that indicates why the job failed.
*/
fail(reason: string | Error): Job;
/**
* Runs the given job and calls callback(err, job) upon completion. Normally you never need to call this manually
* @param cb Called when the job is completed.
*/
run(cb?: ResultCallback<Job>): Job;
/**
* Returns true if the job is running; otherwise, returns false.
*/
isRunning(): boolean;
/**
* Saves the job into the database.
* @param cb Called when the job is saved.
*/
save(cb?: ResultCallback<Job>): Job;
/**
* Removes the job from the database and cancels the job.
* @param cb Called after the job has beeb removed from the database.
*/
remove(cb?: Callback): void;
/**
* Resets the lock on the job. Useful to indicate that the job hasn't timed out when you have very long running
* jobs.
* @param cb Called after the job has been saved to the database.
*/
touch(cb?: Callback): void;
/**
* Calculates next time the job should run
*/
computeNextRunAt(): Job;
}
interface JobOptions {
/**
* Maximum number of that job that can be running at once (per instance of agenda)
*/
concurrency?: number;
/**
* Maximum number of that job that can be locked at once (per instance of agenda)
*/
lockLimit?: number;
/**
* Interval in ms of how long the job stays locked for (see multiple job processors for more info). A job will
* automatically unlock if done() is called.
*/
lockLifetime?: number;
/**
* (lowest|low|normal|high|highest|number) specifies the priority of the job. Higher priority jobs will run
* first.
*/
priority?: string | number;
}
}
export = Agenda;
}

View File

@@ -1,74 +0,0 @@
/// <reference path="ajv.d.ts" />
import * as Ajv from 'ajv';
var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
var validate = ajv.compile({});
var valid = validate({});
if (!valid) console.log(validate.errors);
var valid = ajv.validate({}, {});
if (!valid) console.log(ajv.errors);
ajv.addSchema({}, 'mySchema');
var valid = ajv.validate('mySchema', {});
if (!valid) console.log(ajv.errorsText());
ajv.addKeyword('range', {
type: 'number', compile: function (sch, parentSchema) {
var min: any = sch[0];
var max: any = sch[1];
return parentSchema.exclusiveRange === true
? function (data) { return data > min && data < max; }
: function (data) { return data >= min && data <= max; }
}
});
var schema = { "range": [2, 4], "exclusiveRange": true };
var validate = ajv.compile(schema);
console.log(validate(2.01)); // true
console.log(validate(3.99)); // true
console.log(validate(2)); // false
console.log(validate(4)); // false
declare var request: any;
function loadSchema(uri: any, callback: any) {
request.json(uri, function (err: any, res: any, body: any) {
if (err || res.statusCode >= 400)
callback(err || new Error('Loading error: ' + res.statusCode));
else
callback(null, body);
});
}
var ajv = new Ajv({ loadSchema: loadSchema });
ajv.compileAsync(schema, function (err, validate) {
if (err) return;
var valid = validate({});
});
declare var knex: any;
function checkIdExists(schema: any, data: any) {
return knex(schema.table)
.select('id')
.where('id', data)
.then(function (rows: any) {
return true;
});
}
var validate = ajv.compile(schema);
(validate({ userId: 1, postId: 19 }) as PromiseLike<boolean>)
.then(function (valid) {
// "valid" is always true here
console.log('Data is valid');
}, function (err) {
if (!(err instanceof Ajv.ValidationError)) throw err;
// data is invalid
console.log('Validation errors:', err.errors);
});
var ajv = new Ajv({ /* async: 'es7', */ transpile: 'nodent' });
var validate = ajv.compile(schema); // transpiled es7 async function
(validate({}) as PromiseLike<any>).then(() => { }, () => { });

112
ajv/ajv.d.ts vendored
View File

@@ -1,112 +0,0 @@
// Type definitions for ajv
// Project: https://github.com/epoberezkin/ajv
// Definitions by: York Yao <https://github.com/plantain-00/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "ajv" {
class Ajv {
/**
* Create Ajv instance.
*/
constructor(options?: Ajv.AjvOptions);
/**
* Generate validating function and cache the compiled schema for future use.
*/
compile(schema: any): Ajv.AjvValidate;
/**
* Asyncronous version of compile method that loads missing remote schemas using asynchronous function in options.loadSchema.
*/
compileAsync(schema: any, callback: (error: Error, validate: Ajv.AjvValidate) => void): void;
/**
* Validate data using passed schema (it will be compiled and cached).
*/
validate(schema: any, data: any): boolean | PromiseLike<boolean>;
errors: Ajv.ValidationError[];
/**
* Add schema(s) to validator instance.
*/
addSchema(schema: any, key: string): void;
/**
* Adds meta schema(s) that can be used to validate other schemas.
* That function should be used instead of addSchema because there may be instance options that would compile a meta schema incorrectly (at the moment it is removeAdditional option).
*/
addMetaSchema(schema: any, key: string): void;
/**
* Validates schema.
* This method should be used to validate schemas rather than validate due to the inconsistency of uri format in JSON-Schema standard.
*/
validateSchema(schema: any): Boolean;
/**
* Retrieve compiled schema previously added with addSchema by the key passed to addSchema or by its full reference (id).
* Returned validating function has schema property with the reference to the original schema.
*/
getSchema(key: string): Ajv.AjvValidate;
/**
* Remove added/cached schema.
* Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references.
*/
removeSchema(schema: any): void;
/**
* Add custom format to validate strings. It can also be used to replace pre-defined formats for Ajv instance.
*/
addFormat(name: string, format: any): void;
/**
* Add custom validation keyword to Ajv instance.
*/
addKeyword(keyword: string, definition: Ajv.AjxKeywordDefinition): void;
errorsText(): any;
static ValidationError: Function;
}
namespace Ajv {
type AjvOptions = {
v5?: boolean;
allErrors?: boolean;
verbose?: boolean;
jsonPointers?: boolean;
uniqueItems?: boolean;
unicode?: boolean;
format?: string;
formats?: any;
schemas?: any;
missingRefs?: boolean;
loadSchema?(uri: string, callback: (error: Error, body: any) => void): void;
removeAdditional?: boolean;
useDefaults?: boolean;
coerceTypes?: boolean;
async?: any;
transpile?: string;
meta?: boolean;
validateSchema?: boolean;
addUsedSchema?: boolean;
inlineRefs?: boolean;
passContext?: boolean;
loopRequired?: number;
ownProperties?: boolean;
multipleOfPrecision?: boolean;
errorDataPath?: string,
messages?: boolean;
beautify?: boolean;
cache?: any;
}
type AjvValidate = ((data: any) => boolean | PromiseLike<boolean>) & {
errors: ValidationError[];
}
type AjxKeywordDefinition = {
async?: boolean;
type: string;
compile?: (schema: any, parentsSchema: any) => ((data: any) => boolean | PromiseLike<boolean>);
validate?: (schema: any, data: any) => boolean;
}
type ValidationError = {
keyword: string;
dataPath: string;
schemaPath: string;
params: any;
message: string;
schema: any;
parentSchema: any;
data: any;
}
}
export = Ajv;
}

124
alertify/alertify.d.ts vendored
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/DefinitelyTyped/DefinitelyTyped
declare var alertify: alertify.IAlertifyStatic;
declare namespace 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;
}
}

View File

@@ -1,25 +0,0 @@
/// <reference path="../node/node.d.ts"/>
/// <reference path="./alexa-sdk.d.ts" />
import * as Alexa from "alexa-sdk";
exports.handler = function(event: Alexa.RequestBody, context: Alexa.Context, callback: Function) {
let alexa = Alexa.handler(event, context);
alexa.registerHandlers(handlers);
alexa.execute();
};
let handlers: Alexa.Handlers = {
'LaunchRequest': function () {
var self: Alexa.Handler = this;
self.emit('SayHello');
},
'HelloWorldIntent': function () {
var self: Alexa.Handler = this;
self.emit('SayHello');
},
'SayHello': function () {
var self: Alexa.Handler = this;
self.emit(':tell', 'Hello World!');
}
};

View File

@@ -1,132 +0,0 @@
// Type definitions for Alexa SDK for Node.js v1.0.3
// Project: https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs
// Definitions by: Pete Beegle <https://github.com/petebeegle>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'alexa-sdk' {
export function handler(event: RequestBody, context: Context, callback?: Function): AlexaObject;
export function CreateStateHandler(state: string, obj: any): any;
export var StateString: string;
interface AlexaObject {
_event: any;
_context: any;
_callback: any;
state: any;
appId: any;
response: any;
dynamoDBTableName: any;
saveBeforeResponse: boolean;
registerHandlers: (...handlers: Handlers[]) => any;
execute: () => void;
}
interface Handlers {
[intent: string]: () => void;
}
interface Handler {
on: any;
emit(event: string, ...args: any[]): boolean;
emitWithState: any;
state: any;
handler: any;
event: RequestBody;
attributes: any;
context: any;
name: any;
isOverriden: any;
}
interface Context {
callbackWaitsForEmptyEventLoop: boolean;
logGroupName: string;
logStreamName: string;
functionName: string;
memoryLimitInMB: string;
functionVersion: string;
invokeid: string;
awsRequestId: string;
}
interface RequestBody {
version: string;
session: Session;
request: LaunchRequest | IntentRequest | SessionEndedRequest;
}
interface Session {
new: boolean;
sessionId: string;
attributes: any;
application: SessionApplication;
user: SessionUser;
}
interface SessionApplication {
applicationId: string;
}
interface SessionUser {
userId: string;
accessToken: string;
}
interface LaunchRequest extends IRequest {}
interface IntentRequest extends IRequest {
intent: Intent;
}
interface Intent {
name: string;
slots: any;
}
interface SessionEndedRequest extends IRequest{
reason: string;
}
interface IRequest {
type: "LaunchRequest" | "IntentRequest" | "SessionEndedRequest";
requestId: string;
timeStamp: string;
}
interface ResponseBody {
version: string;
sessionAttributes?: any;
response: Response;
}
interface Response {
outputSpeech?: OutputSpeech;
card?: Card;
reprompt?: Reprompt;
shouldEndSession: boolean;
}
interface OutputSpeech {
type: "PlainText" | "SSML";
text?: string;
ssml?: string;
}
interface Card {
type: "Simple" | "Standard" | "LinkAccount";
title?: string;
content?: string;
text?: string;
image?: Image;
}
interface Image {
smallImageUrl: string;
largeImageUrl: string;
}
interface Reprompt {
outputSpeech: OutputSpeech;
}
}

View File

@@ -1,136 +0,0 @@
/// <reference path="../node/node.d.ts" />
///<reference path="./algoliasearch-client-js.d.ts"/>
var algoliasearch = require('algoliasearch');
var _clientOptions: ClientOptions = {
timeout : 12,
protocol: "",
httpAgent: ""
};
var _synonymOption: SynonymOption = {
forwardToSlaves: false,
replaceExistingSynonyms: false
};
var _algoliaUserKeyOptions : AlgoliaUserKeyOptions = {
validity: 0,
maxQueriesPerIPPerHour: 0,
indexes: [""],
queryParameters: { attributesToRetrieve: ["algolia"] },
description: ""
};
var _searchSynonymOptions : SearchSynonymOptions = {
query: "",
page: 0,
type: "",
hitsPerPage: 0
};
var _algoliaSecuredApiOptions: AlgoliaSecuredApiOptions = {
filters: "",
validUntil: 0,
restrictIndices: "",
userToken: ""
};
var _algoliaIndexSettings : AlgoliaIndexSettings = {
attributesToIndex: [""],
attributesforFaceting: [""],
unretrievableAttributes: [""],
attributesToRetrieve: [""],
ranking: [""],
customRanking: [""],
slaves: [""],
maxValuesPerFacet: '',
attributesToHighlight: [""],
attributesToSnippet: [""],
highlightPreTag: '',
highlightPostTag: '',
snippetEllipsisText: '',
restrictHighlightAndSnippetArrays: false,
hitsPerPage: 0,
minWordSizefor1Typo: 0,
minWordSizefor2Typos: 0,
typoTolerance: false,
allowTyposOnNumericTokens: false,
ignorePlurals: false,
disableTypoToleranceOnAttributes: '',
separatorsToIndex: '',
queryType: '',
removeWordsIfNoResults: '',
advancedSyntax: false,
optionalWords: [""],
removeStopWords: [""],
disablePrefixOnAttributes: [""],
disableExactOnAttributes: [""],
exactOnSingleWordQuery: '',
alternativesAsExact: false,
attributeForDistinct: "",
distinct: false,
numericAttributesToIndex: [""],
allowCompressionOfIntegerArray: false,
altCorrections: [{}],
minProximity: 0,
placeholders: ''
};
var _algoliaQueryParameters : AlgoliaQueryParameters = {
query: '',
filters: '',
attributesToRetrieve: [""],
restrictSearchableAttributes: [""],
facets: '',
maxValuesPerFacet: '',
attributesToHighlight: [''],
attributesToSnippet: [''],
highlightPreTag: '',
highlightPostTag: '',
snippetEllipsisText: '',
restrictHighlightAndSnippetArrays: false,
hitsPerPage: 0,
page: 0,
offset: 0,
length: 0,
minWordSizefor1Typo: 0,
minWordSizefor2Typos: 0,
typoTolerance: false,
allowTyposOnNumericTokens: false,
ignorePlurals: false,
disableTypoToleranceOnAttributes: '',
aroundLatLng: '',
aroundLatLngViaIP: '',
aroundRadius: '',
aroundPrecision: 0,
minimumAroundRadius: 0,
insideBoundingBox: '',
queryType: '',
insidePolygon: '',
removeWordsIfNoResults: '',
advancedSyntax: false,
optionalWords: [''],
removeStopWords: [''],
disableExactOnAttributes: [''],
exactOnSingleWordQuery: '',
alternativesAsExact: true,
distinct: 0,
getRankingInfo: false,
numericAttributesToIndex: [''],
numericFilters: [''],
tagFilters: '',
facetFilters: '',
analytics: false,
analyticsTags: [''],
synonyms: true,
replaceSynonymsInHighlight: false,
minProximity: 0
};
var index: AlgoliaIndex = algoliasearch('', '').initIndex('');
var search = index.search({query: ""});
index.search({query: ""}, function(err, res){});

File diff suppressed because it is too large Load Diff

166
alt/alt.d.ts vendored
View File

@@ -1,166 +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/DefinitelyTyped/DefinitelyTyped
///<reference path="../react/react.d.ts"/>
declare namespace 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, ...args: any[]):any;
remote(state:any, ...args: 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;
}

View File

@@ -1,25 +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/DefinitelyTyped/DefinitelyTyped
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;
}

2588
amcharts/AmCharts.d.ts vendored

File diff suppressed because it is too large Load Diff

View File

@@ -1 +0,0 @@

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) { });

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/DefinitelyTyped/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;

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) {
}
});

View File

@@ -1 +0,0 @@

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/DefinitelyTyped/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; }

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