From 45eac85afbafe770f07e322a2647e5100c7b3042 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Tue, 23 Oct 2012 22:57:53 +0300 Subject: [PATCH 001/107] Handlebars.js definitions and tests added --- Definitions/handlebars-1.0.d.ts | 21 +++++++++ README.md | 7 +-- Tests/handlebars-tests.ts | 77 +++++++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 3 deletions(-) create mode 100644 Definitions/handlebars-1.0.d.ts create mode 100644 Tests/handlebars-tests.ts diff --git a/Definitions/handlebars-1.0.d.ts b/Definitions/handlebars-1.0.d.ts new file mode 100644 index 000000000..87b3c7caa --- /dev/null +++ b/Definitions/handlebars-1.0.d.ts @@ -0,0 +1,21 @@ +// Type definitions for Handlebars 1.0 +// Project: http://handlebarsjs.com/ +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface HandlebarsStatic { + registerHelper(name: string, fn: Function, inverse?: bool): void; + registerPartial(name: string, str): void; + K(); + createFrame(object); + + Exception(message: string): void; + SafeString(str: string): void; + + parse(string: string); + print(ast); + logger; + log(level, str): void; + compile(environment, options?, context?, asObject?); +} + +declare var Handlebars: HandlebarsStatic; \ No newline at end of file diff --git a/README.md b/README.md index c281acfa4..87e7101c6 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,10 @@ Complete * [async](https://github.com/caolan/async) * [Backbone.js](http://backbonejs.org/) * [Bootstrap](http://twitter.github.com/bootstrap/) +* [ember.js](http://emberjs.com/) * [Express](http://expressjs.com/) (from TypeScript samples) * [Fancybox](http://fancybox.net/) +* [Handlebars](http://handlebarsjs.com/) * [History.js](https://github.com/balupton/History.js/) * [Humane.js](http://wavded.github.com/humane-js/) (by [jmvrbanac](https://github.com/jmvrbanac)) * [Impress.js](https://github.com/bartaz/impress.js) @@ -31,13 +33,12 @@ Complete Next ---- -* ember.js -* Facebook SDK * Knockout.Mapping +* Angular.js +* Facebook SDK * jQuery.Validate * jQuery Mobile * google.visualization -* Angular.js * Meteor * PhoneGap * Isotope diff --git a/Tests/handlebars-tests.ts b/Tests/handlebars-tests.ts new file mode 100644 index 000000000..be78d887d --- /dev/null +++ b/Tests/handlebars-tests.ts @@ -0,0 +1,77 @@ +/// + +var context = { + author: { firstName: "Alan", lastName: "Johnson" }, + body: "I Love Handlebars", + comments: [{ + author: { firstName: "Yehuda", lastName: "Katz" }, + body: "Me too!" + }] +}; +Handlebars.registerHelper('fullName', (person) => { + return person.firstName + " " + person.lastName; +}); + +Handlebars.registerHelper('agree_button', () => { + return new Handlebars.SafeString( + "" + ); +}); + +var source = "

Hello, my name is {{name}}. I am from {{hometown}}. I have " + + "{{kids.length}} kids:

" + + ""; +var template = Handlebars.compile(source); +var data = { "name": "Alan", "hometown": "Somewhere, TX", + "kids": [{"name": "Jimmy", "age": "12"}, {"name": "Sally", "age": "4"}]}; +var result = template(data); + +Handlebars.registerHelper('link_to', (context) => { + return "" + context.body + ""; +}); + +var context2 = { posts: [{url: "/hello-world", body: "Hello World!"}] }; +var source2 = "" + +var template2 = Handlebars.compile(source2); +template2(context2); + +Handlebars.registerHelper('link_to', (title, context) => { + return "" + title + "!" +}); + +var context3 = { posts: [{url: "/hello-world", body: "Hello World!"}] }; +var source3 = '' +var template3 = Handlebars.compile(source3); +template3(context3); + +var source4 = ""; +Handlebars.registerHelper('link', (context, options) => { + return '' + context.fn(this) + ''; +}); +var template4 = Handlebars.compile(source4); +var data2 = { "people": [ + { "name": "Alan", "id": 1 }, + { "name": "Yehuda", "id": 2 } +]}; +template4(data2); + +var source5 = ""; +Handlebars.registerPartial('link', '{{name}}') +var template5 = Handlebars.compile(source5); +var data3 = { "people": [ + { "name": "Alan", "id": 1 }, + { "name": "Yehuda", "id": 2 } +]}; +template5(data3); + +Handlebars.registerHelper('list', (items, fn) => { + var out = ""; +}); +Handlebars.registerHelper('fullName', (person) => { + return person.firstName + " " + person.lastName; +}); \ No newline at end of file From b63b8d9c826b3eebfb5ffc169cf0e171458fb8b1 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Wed, 24 Oct 2012 03:05:49 +0300 Subject: [PATCH 002/107] Improvements to and merge of John Vrbanac's definitions for Ember.js --- Definitions/ember-1.0.d.ts | 317 ++++++++++++++++++++++++++++++++----- Tests/ember-tests.ts | 205 +++++++++++++++++++----- 2 files changed, 440 insertions(+), 82 deletions(-) diff --git a/Definitions/ember-1.0.d.ts b/Definitions/ember-1.0.d.ts index 1ede154b1..254c19b8d 100644 --- a/Definitions/ember-1.0.d.ts +++ b/Definitions/ember-1.0.d.ts @@ -1,50 +1,291 @@ -// Type definitions for Ember.js 1.0 +// Type definitions for Ember.js 1.0.pre // Project: http://emberjs.com/ // Definitions: https://github.com/borisyankov/DefinitelyTyped +declare module Ember { -interface EmberApplication { - create(): EmberApplication; - MyView: EmberView; + export class CoreObject { + isDestroyed: bool; + isDestroying: bool; + + destroy(): Object; + eachComputedProperty(callback: Function, binding: Object): void; + metaForProperty(key: string): any; + } + + export class Object extends CoreObject { + + static create(...arguments: any[]): Object; + + addObserver(key: string, target: Object, method: any): Object; + apply(obj: Object): Object; + beginPropertyChanges(): Observable; + cacheFor(keyName: string): Object; + decrementProperty(keyName: string, increment: Object): Object; + detect(obj: Object): bool; + endPropertyChanges(): Observable; + get(key: string): Object; + getProperties(...list: string[]): any; + getProperties(list: string[]): any; + getWithDefault(keyName: string, defaultValue: Object): Object; + hasObserverFor(key: string): bool; + incrementProperty(keyName: string, increment: Object): Object; + notifyPropertyChange(keyName: string): Observable; + propertyDidChange(keyName: string): Observable; + propertyWillChange(key: string): Observable; + removeObserver(key: string, target: Object, method: string): Observable; + removeObserver(key: string, target: Object, method: Function): Observable; + reopen(...arguments: any[]); + set(key: string, value: Object): Observable; + setProperties(hash: any): Observable; + setUnknownProperty(key: string, value: Object): void; + toggleProperty(keyName: string): Object; + unknownProperty(key: string): Object; + } + + export interface Mixin { + create(obj: Object): Object; + extend(first: Object, second: Object): Object; + } + + export class View extends Object { + append(): View; + static create(...arguments: any[]): Application; + } + + export interface Enumerable extends Mixin { + // Fields + firstObject: Object; + hasEnumerableObservers: bool; + lastObject: Object; + nextObject: Object; + + // Methods + addEnumerableObserver(target, opts); + compact(): any[]; + contains(obj: Object): bool; + enumerableContentDidChange(removing: number, adding: number): Object; + enumerableContentDidChange(removing: Ember.Enumerable, adding: Ember.Enumerable): Object; + enumerableContentDidChange(start: Number, removing: number, adding: number): Object; + enumerableContentDidChange(start: Number, removing: Ember.Enumerable, adding: Ember.Enumerable): Object; + + enumerableContentWillChange(removing: number, adding: number): Ember.Enumerable; + enumerableContentWillChange(removing: Ember.Enumerable, adding: Ember.Enumerable): Ember.Enumerable; + enumerableContentWillChange(start: Number, removing: number, adding: number): Ember.Enumerable; + enumerableContentWillChange(start: Number, removing: Ember.Enumerable, adding: Ember.Enumerable): Ember.Enumerable; + + every(callback: Function, target?: Object): bool; + everyProperty(key: string, value?: string): any[]; + filter(callback: Function, target?: Object): any[]; + filterProperty(key: string, value?: string): any[]; + find(callback: Function, target?: Object): Object; + findProperty(key: string, value?: string): Object; + /*forEach + getEach + invoke + map + mapProperty + reduce + removeEnumerableObserver + setEach + some + someProperty + toArray + uniq + without*/ + } + + export interface NativeArray extends Array { + activate(); + } + + + + export class Application extends Object { + customEvents: Object; + eventDispatcher: EventDispatcher; + // rootElement: DOMElement; + ready; + static create(...arguments: any[]): Application; + initialize(router: Router); + } + + export class Router { + + } + + export class EventDispatcher { + } + + export class Binding { + static from(); + static oneWay(path: string, flag?: bool); + static to(); + + connect(obj: Object): Binding; + copy(): Binding; + disconnect(obj: Object): Binding; + from(path: string): Binding; + oneWay(): Binding; + to(propertyPath: string): Binding; + } + + export interface ComputedProperty { + cacheable(aFlag?: bool): ComputedProperty; + meta(hash: any): ComputedProperty; + property(path: string): ComputedProperty; + volatile(): ComputedProperty; + } + + export interface Map { + + } + + export interface Observable extends Mixin { + addBeforeObserver(key, target, method); + addObject(obj: Object); + addObserver(key: string, target: Object, method: Function): Ember.Object; + addObserver(key: string, target: Object, method: string): Ember.Object; + beginPropertyChanges(): Ember.Observable; + cacheFor(keyName: string): Object; + contentArrayDidChange(array, idx, removedCount, addedCount); + contentArrayWillChange(array, idx, removedCount, addedCount); + contentItemSortPropertyDidChange(item); + decrementProperty(keyName: string, increment: Object): Object; + destroy(); + endPropertyChanges(): Ember.Observable; + get(key: string): Object; + getPath(path: string): Object; + getProperties(...list: string[]): any; + getProperties(list: any[]): any; + getWithDefault(keyName: string, defaultValue: Object): Object; + hasObserverFor(key: string): bool; + incrementProperty(keyName: string, increment: Object): Object; + insertItemSorted(item); + notifyPropertyChange(keyName: string): Ember.Observable; + orderBy(item1, item2); + propertyDidChange(keyName: string): Ember.Observable; + propertyWillChange(key: string): Ember.Observable; + removeObject(obj: Object); + removeObserver(key: string, target: Object, method: string): Ember.Observable; + removeObserver(key: string, target: Object, method: Function): Ember.Observable; + set(key: string, value: Object): Ember.Observable; + setPath(path: string, value: Object): Ember.Observable; + setProperties(hash): Ember.Observable; + setUnknownProperty(key: string, value: Object); + toggleProperty(keyName: string): Object; + unknownProperty(key: string): Object; + } } -interface EmberAlias { -} - -interface EmberArrayController { -} - -interface EmberBinding { -} - -interface EmberDescriptor { -} - -interface EmberNativeArray { - activate(): void; -} - -interface EmberObject { -} - -interface EmberView { -} interface EmberStatic { - $; // jQuery - A(arr?: any[]): EmberNativeArray; - addListener(obj: any, eventName: string, targetOrMethod: any, method: any): void; - alias(methodName: EmberDescriptor): EmberAlias; - assert(desc: string, test: bool): void; - beforeObserver(func: Function, propertyNames: string): Function; - bind(obj: any, to: string, from: string): EmberBinding; - cacheFor(obj: any, key: string): void; + // Statics + CP_DEFAULT_CACHEABLE: bool; + ENV: Object; + EXTEND_PROTOTYPES: bool; + LOG_BINDINGS: bool; + LOG_STACKTRACE_ON_DEPRECATION: bool; + META_KEY: string; + SHIM_ES5: bool; + StringS: Object; + VERSION: string; + VIEW_PRESERVES_CONTEXT: bool; - Application: EmberApplication; - Object: EmberObject; - View: EmberView; + Application: Ember.Application; + View: Ember.View; + + $; // jQuery + + // API Doc Members + A(arr: any[]): Ember.NativeArray; + addBeforeObserver(obj: Object, path: string, target: Object, method: Function); + addListener(obj: Object, eventName: string, target: Object, method: Function); + addObserver(obj: Object, path: string, target: Object, method: Function); + alias(methodName: string); + assert(desc: string, test: bool); + beforeObserver(func: Function); + beginPropertyChanges(); + bind(obj: Object, to: string, from: string): Ember.Binding; + cacheFor(obj: Object, key: string); + canInvoke(obj: Object, methodName: string); + changeProperties(cb: Function, binding?: Ember.Binding); + compare(first: Object, second: Object): number; + computed(func: Function): Ember.ComputedProperty; + copy(obj: Object, deep: bool): Object; + create(obj: Object, props: any); + deferEvent(obj: Object, eventName: string, param: any); + deprecate(message: string, test?: bool); + deprecateFunc(message: string, func: Function); + destroy(obj: Object): void; + empty(obj: Object): bool; + endPropertyChanges(); + finishChains(obj: Object); + get(obj: Object, keyName: string): Object; + getMeta(obj: Object, property: any); + getWithDefault(root, key, defaultValue); + hasListeners(obj: Object, eventName: string): bool; + immediateObserver(); + inspect(obj: Object): string; + isArray(obj?: any): bool; + isEqual(a: Object, b: Object): bool; + isGlobalPath(path: string): bool; + isWatching(obj: Object, key): bool; + keys(obj: Object): any[]; + listenersFor(obj: Object, eventName: string): any[]; + makeArray(obj: Object): any[]; + + Map(); + MapWithDefault(options); + mixin(obj: Object); + none(obj: Object): bool; + observer(func: Function); + oneWay(obj: Object, to, from); + onLoad(name: string, callback: Function); + + OrderedSet(); + overrideChains(obj: Object, keyName: string, m: any); + propertyDidChange(obj: Object, keyName: string): void; + propertyWillChange(obj: Object, keyName: string, value: any): void; + removeBeforeObserver(obj, path, target, method); + removeListener(obj, eventName, target, method); + removeObserver(obj, path, target, method); + + required(); + runLoadHooks(name: string, object: Object); + sendEvent(obj: Object, eventName: string, params); + set(obj: Object, keyName: string, value, tolerant); + setMeta(obj: Object, property, value); + setProperties(self, hash); + toString(): string; + tryInvoke(obj: Object, methodName: string, args: any[]): bool; + trySet(root, path, value); + typeOf(item): string; + warn(message: string, test: bool); + watchedEvents(obj: Object); + + // Other public members not listed in API Doc + meta(obj, writable); + metaPath(obj, path, writable); + normalizeTuple(target, path); + notifyBeforeObservers(obj: Object, keyName: string); + notifyObservers(obj: Object, keyName: string); + observersFor(obj: Object, path: string); + rewatch(obj: Object); + run(target, method); + defineProperty(obj: Object, keyName: string, desc, data, meta); + beforeObserversFor(obj: Object, path: string); + generateGuid(obj: Object, prefix); + getPath(); + guidFor(obj: Object); + identifyNamespaces(); + setPath(); + trySetPath(); + unwatch(obj: Object, keyName: string); + watch(obj: Object, keyName: string); + wrap(func: Function, superFunc: Function); } -declare var Em: EmberStatic; -declare var Ember: EmberStatic; \ No newline at end of file +declare var Em: Ember; +//declare var Ember: EmberStatic; \ No newline at end of file diff --git a/Tests/ember-tests.ts b/Tests/ember-tests.ts index 2289a1d44..8fea25eaa 100644 --- a/Tests/ember-tests.ts +++ b/Tests/ember-tests.ts @@ -1,68 +1,185 @@ /// +/// var App; App = Em.Application.create(); -App.MyView = Em.View.extend({ - mouseDown: function() { - window.alert("hello world!"); -}); - -class MyView extends Em.View { - mouseDown() { - window.alert("hello world!"); - } -} - -App.Person = DS.Model.extend({ - firstName: DS.attr('string'), - lastName: DS.attr('string'), - fullName: function() { - return this.get('firstName') + - " " + this.get('lastName'); - }.property('firstName', 'lastName') -}); -App.peopleController = Em.ArrayController.create({ - content: App.Person.findAll() -}); - App.president = Ember.Object.create({ name: "Barack Obama" }); App.country = Ember.Object.create({ - presidentNameBinding: 'App.president.name' + presidentNameBinding: 'MyApp.president.name' }); App.country.get('presidentName'); App.president = Ember.Object.create({ firstName: "Barack", lastName: "Obama", - fullName: function() { + fullName: () => { return this.get('firstName') + ' ' + this.get('lastName'); }.property() }); App.president.get('fullName'); -App.president = Ember.Object.create({ - firstName: "Barack", - lastName: "Obama", - fullName: function() { - return this.get('firstName') + ' ' + this.get('lastName'); - }.property('firstName', 'lastName') +var Person = Ember.Object.extend({ + say: (thing) => { + alert(thing); + } +}); +var tom = Person.create({ + name: "Tom Dale", + helloWorld: () => { + this.say("Hi my name is " + this.get('name')); + } +}); +tom.helloWorld(); + +Person.reopen({ isPerson: true }); +Person.create().get('isPerson'); + +Person.reopenClass({ + createMan: () => { + return Person.create({ isMan: true }) + } +}); +Person.createMan().get('isMan'); + +var person = Person.create({ + firstName: "Yehuda", + lastName: "Katz" +}); +person.addObserver('fullName', () => { }); +person.set('firstName', "Brohuda"); + +App.todosController = Ember.Object.create({ + todos: [ + Ember.Object.create({ isDone: false }) + ], + remaining: () => { + var todos = this.get('todos'); + return todos.filterProperty('isDone', false).get('length'); + }.property('todos.@each.isDone') }); -App.PaintSample = Ember.Object.extend({ - color: 'red', - colour: Ember.alias('color'), - name: function () { - return "Zed"; - }, - moniker: Ember.alias("name") -}); -var paintSample = App.PaintSample.create(); -paintSample.get('colour'); -paintSample.moniker(); +var todos = App.todosController.get('todos'); +var todo = todos.objectAt(0); +todo.set('isDone', true); +App.todosController.get('remaining'); +todo = Ember.Object.create({ isDone: false }); +todos.pushObject(todo); +App.todosController.get('remaining'); -Ember.assert('Must pass a valid object', obj); -Ember.assert('This code path should never be run'); +App.wife = Ember.Object.create({ + householdIncome: 80000 +}); +App.husband = Ember.Object.create({ + householdIncomeBinding: 'App.wife.householdIncome' +}); +App.husband.get('householdIncome'); +App.husband.set('householdIncome', 90000); +App.wife.get('householdIncome'); + +App.user = Ember.Object.create({ + fullName: "Kara Gates" +}); +App.userView = Ember.View.create({ + userNameBinding: Ember.Binding.oneWay('App.user.fullName') +}); +App.user.set('fullName', "Krang Gates"); +App.userView.set('userName', "Truckasaurus Gates"); +App.user.get('fullName'); + +App = Ember.Application.create({ + rootElement: '#sidebar' +}); + +var view = Ember.View.create({ + templateName: 'say-hello', + name: "Bob" +}); +view.appendTo('#container'); +view.append(); +view.remove(); + +App.AlertView = Ember.View.extend({ + priority: "p4", + isUrgent: true +}); + +App.ListingView = Ember.View.extend({ + templateName: 'listing', + edit: (event) => { + event.view.set('isEditing', true); + } +}); + +App.userController = Ember.Object.create({ + content: Ember.Object.create({ + firstName: "Albert", + lastName: "Hofmann", + posts: 25, + hobbies: "Riding bicycles" + }) +}); + +Handlebars.registerHelper('highlight', (property, options) => { + var value = Ember.Handlebars.getPath(this, property, options); + return new Handlebars.SafeString('' + value + ''); +}); + +App.MyText = Ember.TextField.extend({ + formBlurredBinding: 'App.adminController.formBlurred', + change: (evt) => { + this.set('formBlurred', true); + } +}); + +var textArea = Ember.TextArea.create({ + valueBinding: 'TestObject.value' +}); + +App.ClickableView = Ember.View.extend({ + click: (evt) => { + alert("ClickableView was clicked!"); + } +}); + +var container = Ember.ContainerView.create(); +container.append(); +var coolView = App.CoolView.create(), + childViews = container.get('childViews'); +childViews.pushObject(coolView); + +Person = Ember.Object.extend({ + sayHello: () => { + console.log("Hello from " + this.get('name')); + } +}); +var people = [ + Person.create({ name: "Juan" }), + Person.create({ name: "Charles" }), + Person.create({ name: "Majd" }) +] +people.invoke('sayHello'); + +var arr = [Ember.Object.create(), Ember.Object.create()]; +arr.setEach('name', 'unknown'); +arr.getEach('name'); + +Person = Ember.Object.extend({ + name: null, + isHappy: false +}); +var people = [ + Person.create({ name: 'Yehuda', isHappy: true }), + Person.create({ name: 'Majd', isHappy: false }) +]; +people.every((person, index, self) => { + if (person.get('isHappy')) { return true; } +}); +people.some((person, index, self) => { + if (person.get('isHappy')) { return true; } +}); +people.everyProperty('isHappy', true); +people.someProperty('isHappy', true); \ No newline at end of file From 5bff217a3d2aa5b19cb0fc321eb601c534b48bc1 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Wed, 24 Oct 2012 05:07:47 +0300 Subject: [PATCH 003/107] node_redis definitions and tests added --- Definitions/node_redis-0.8.d.ts | 349 ++++++++++++++++++++++++++++++++ README.md | 1 + Tests/redis_node-tests.ts | 196 ++++++++++++++++++ 3 files changed, 546 insertions(+) create mode 100644 Definitions/node_redis-0.8.d.ts create mode 100644 Tests/redis_node-tests.ts diff --git a/Definitions/node_redis-0.8.d.ts b/Definitions/node_redis-0.8.d.ts new file mode 100644 index 000000000..a9ec115fc --- /dev/null +++ b/Definitions/node_redis-0.8.d.ts @@ -0,0 +1,349 @@ +// Type definitions for node_redis 0.8 +// Project: https://github.com/mranney/node_redis +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'redis' { + export var debug_mode: bool; + export function createClient(): RedisClient; + export function createClient(port: string, host: string, options: RedisOptions): RedisClient; + export function print(err: string, reply?: string); + + interface RedisOptions { + parser: string; + return_buffers: bool; + detect_buffers: bool; + socket_nodelay: bool; + no_ready_check: bool; + enable_offline_queue: bool; + } + + interface Command { + (...args: any[], callback?: Function): Commands; + } + + interface Commands { + + get: Command; + set: Command; + setnx: Command; + setex: Command; + append: Command; + strlen: Command; + del: Command; + exists: Command; + setbit: Command; + getbit: Command; + setrange: Command; + getrange: Command; + substr: Command; + incr: Command; + decr: Command; + mget: Command; + + rpush: Command; + lpush: Command; + rpushx: Command; + lpushx: Command; + linsert: Command; + rpop: Command; + lpop: Command; + brpop: Command; + brpoplpush: Command; + blpop: Command; + llen: Command; + lindex: Command; + lset: Command; + lrange: Command; + ltrim: Command; + lrem: Command; + rpoplpush: Command; + + sadd: Command; + srem: Command; + smove: Command; + sismember: Command; + scard: Command; + spop: Command; + srandmember: Command; + sinter: Command; + sinterstore: Command; + sunion: Command; + sunionstore: Command; + sdiff: Command; + sdiffstore: Command; + smembers: Command; + + zadd: Command; + zincrby: Command; + zrem: Command; + zremrangebyscore: Command; + zremrangebyrank: Command; + zunionstore: Command; + zinterstore: Command; + zrange: Command; + zrangebyscore: Command; + zrevrangebyscore: Command; + zcount: Command; + zrevrange: Command; + zcard: Command; + zscore: Command; + zrank: Command; + zrevrank: Command; + + hset: Command; + hsetnx: Command; + hget: Command; + hmset: Command; + hmget: Command; + hincrby: Command; + hdel: Command; + hlen: Command; + hkeys: Command; + hvals: Command; + hgetall: Command; + hexists: Command; + + incrby: Command; + decrby: Command; + getset: Command; + mset: Command; + msetnx: Command; + randomkey: Command; + select: Command; + move: Command; + rename: Command; + renamenx: Command; + expire: Command; + expireat: Command; + keys: Command; + dbsize: Command; + auth: Command; + ping: Command; + echo: Command; + save: Command; + bgsave: Command; + bgrewriteaof: Command; + shutdown: Command; + lastsave: Command; + type: Command; + multi: Command; + exec: Command; + discard: Command; + sync: Command; + flushdb: Command; + flushall: Command; + sort: Command; + info: Command; + monitor: Command; + ttl: Command; + persist: Command; + slaveof: Command; + debug: Command; + config: Command; + subscribe: Command; + unsubscribe: Command; + psubscribe: Command; + punsubscribe: Command; + publish: Command; + watch: Command; + unwatch: Command; + cluster: Command; + restore: Command; + migrate: Command; + dump: Command; + object: Command; + client: Command; + eval: Command; + evalsha: Command; + + ///////////////// + + GET: Command; + SET: Command; + SETNX: Command; + SETEX: Command; + APPEND: Command; + STRLEN: Command; + DEL: Command; + EXISTS: Command; + SETBIT: Command; + GETBIT: Command; + SETRANGE: Command; + GETRANGE: Command; + SUBSTR: Command; + INCR: Command; + DECR: Command; + MGET: Command; + + RPUSH: Command; + LPUSH: Command; + RPUSHX: Command; + LPUSHX: Command; + LINSERT: Command; + RPOP: Command; + LPOP: Command; + BRPOP: Command; + BRPOPLPUSH: Command; + BLPOP: Command; + LLEN: Command; + LINDEX: Command; + LSET: Command; + LRANGE: Command; + LTRIM: Command; + LREM: Command; + RPOPLPUSH: Command; + + SADD: Command; + SREM: Command; + SMOVE: Command; + SISMEMBER: Command; + SCARD: Command; + SPOP: Command; + SRANDMEMBER: Command; + SINTER: Command; + SINTERSTORE: Command; + SUNION: Command; + SUNIONSTORE: Command; + SDIFF: Command; + SDIFFSTORE: Command; + SMEMBERS: Command; + + ZADD: Command; + ZINCRBY: Command; + ZREM: Command; + ZREMRANGEBYSCORE: Command; + ZREMRANGEBYRANK: Command; + ZUNIONSTORE: Command; + ZINTERSTORE: Command; + ZRANGE: Command; + ZRANGEBYSCORE: Command; + ZREVRANGEBYSCORE: Command; + ZCOUNT: Command; + ZREVRANGE: Command; + ZCARD: Command; + ZSCORE: Command; + ZRANK: Command; + ZREVRANK: Command; + + HSET: Command; + HSETNX: Command; + HGET: Command; + HMSET: Command; + HMGET: Command; + HINCRBY: Command; + HDEL: Command; + HLEN: Command; + HKEYS: Command; + HVALS: Command; + HGETALL: Command; + HEXISTS: Command; + + INCRBY: Command; + DECRBY: Command; + GETSET: Command; + MSET: Command; + MSETNX: Command; + RANDOMKEY: Command; + SELECT: Command; + MOVE: Command; + RENAME: Command; + RENAMENX: Command; + EXPIRE: Command; + EXPIREAT: Command; + KEYS: Command; + DBSIZE: Command; + AUTH: Command; + PING: Command; + ECHO: Command; + SAVE: Command; + BGSAVE: Command; + BGREWRITEAOF: Command; + SHUTDOWN: Command; + LASTSAVE: Command; + TYPE: Command; + MULTI: Command; + EXEC: Command; + DISCARD: Command; + SYNC: Command; + FLUSHDB: Command; + FLUSHALL: Command; + SORT: Command; + INFO: Command; + MONITOR: Command; + TTL: Command; + PERSIST: Command; + SLAVEOF: Command; + DEBUG: Command; + CONFIG: Command; + SUBSCRIBE: Command; + UNSUBSCRIBE: Command; + PSUBSCRIBE: Command; + PUNSUBSCRIBE: Command; + PUBLISH: Command; + WATCH: Command; + UNWATCH: Command; + CLUSTER: Command; + RESTORE: Command; + MIGRATE: Command; + DUMP: Command; + OBJECT: Command; + CLIENT: Command; + EVAL: Command; + EVALSHA: Command; + + + hgetall(hash); + hmset(hash, obj, callback?: Function); + hmset(hash, key1, val1, ... keyn, valn, [callback]) + + hmset(args, callback: Function); + HMGET (args, callback: Function); + } + + interface Multi extends Commands { + exec(callback: Function, ...commands: any[]): void; + EXEC(callback: Function, ...commands: any[]): void; + } + + interface RedisClient extends Commands { + + initialize_retry_vars(): void; + flush_and_error(message: string): void; + on_error(message: string): void; + do_auth(): void; + on_connect(): void; + init_parser(): void; + on_ready(): void; + on_info_cmd(err, res): void; + ready_check(): void; + send_offline_queue(): void; + connection_gone(why: string): void; + on_data(data): void; + return_error(err): void; + return_reply(reply): void; + send_command(command: string, args: any[], callback?: Function); + send_command(command: string, ...args: any[], callback?: Function); + pub_sub_command(command: { command: string; args: any[]; }); + + eval(): void; + + server_info; + connected: bool; + command_queue: any[]; + offline_queue: any[]; + retry_delay : number; + retry_backoff: number; + + auth(password: string, callback: Function): void; + AUTH(password: string, callback: Function): void; + + end(): RedisClient; + + on("subscribe", (channel, count) => void); // +emit + + send_command(command_name, args, callback) + + multi(...commands: any[]): Multi; + MULTI(...commands: any[]): Multi; + } +} \ No newline at end of file diff --git a/README.md b/README.md index 87e7101c6..805439189 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ Complete * [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) * [Mustache.js](https://github.com/janl/mustache.js) * [Node.js](http://nodejs.org/) (from TypeScript samples) +* [node_redis](https://github.com/mranney/node_redis) * [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) * [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall)) * [Spin](http://fgnass.github.com/spin.js/) diff --git a/Tests/redis_node-tests.ts b/Tests/redis_node-tests.ts new file mode 100644 index 000000000..f900f30fe --- /dev/null +++ b/Tests/redis_node-tests.ts @@ -0,0 +1,196 @@ +/// + +import redis = module('redis'); + +function test1() { + var client = redis.createClient(); + + client.on("error", function (err) { + console.log("Error " + err); + }); + + client.set("string key", "string val", redis.print); + client.hset("hash key", "hashtest 1", "some value", redis.print); + client.hset(["hash key", "hashtest 2", "some other value"], redis.print); + client.hkeys("hash key", (err, replies) => { + console.log(replies.length + " replies:"); + replies.forEach((reply, i) => { + console.log(" " + i + ": " + reply); + }); + client.quit(); + }); + + client.mset(["test keys 1", "test val 1", "test keys 2", "test val 2"], function (err, res) { }); + client.mset("test keys 1", "test val 1", "test keys 2", "test val 2", function (err, res) { }); + client.set("some key", "some val"); + client.set(["some other key", "some val"]); + client.get("missingkey", (err, reply) => { }); +} + +function test2() { { + var client = redis.createClient(null, null, { + detect_buffers: true + }); + + client.set("foo_rand000000000000", "OK"); + client.get("foo_rand000000000000", (err, reply) => { + console.log(reply.toString()); + }); + client.get(new Buffer("foo_rand000000000000"), (err, reply) => { + console.log(reply.toString()); + }); + client.end(); +} + +function test3() { + var client = redis.createClient(); + + client.set("foo_rand000000000000", "some fantastic value"); + client.get("foo_rand000000000000", (err, reply) => { + console.log(reply.toString()); + }); + client.end(); + + client.hmset("hosts", "mjr", "1", "another", "23", "home", "1234"); + client.hgetall("hosts", function (err, obj) { + console.dir(obj); + }); + + client.HMSET(key2, { + "0123456789": "abcdefghij", // NOTE: the key and value must both be strings + "some manner of key": "a type of value" + }); + + client.HMSET(key1, "0123456789", "abcdefghij", "some manner of key", "a type of value"); +} + +function test4() { + var client1 = redis.createClient(), client2 = redis.createClient(), + msg_count = 0; + + client1.on("subscribe", function (channel, count) { + client2.publish("a nice channel", "I am sending a message."); + client2.publish("a nice channel", "I am sending a second message."); + client2.publish("a nice channel", "I am sending my last message."); + }); + + client1.on("message", function (channel, message) { + console.log("client1 channel " +channel + ": " +message); + msg_count += 1; + if(msg_count === 3) { + client1.unsubscribe(); + client1.end(); + client2.end(); + }}); + + client1.incr("did a thing"); + client1.subscribe("a nice channel"); +} + +function test5() { + var client = redis.createClient(), set_size = 20; + + client.sadd("bigset", "a member"); + client.sadd("bigset", "another member"); + + while (set_size > 0) { + client.sadd("bigset", "member " + set_size); + set_size -= 1; + } + + client.multi() + .scard("bigset") + .smembers("bigset") + .keys("*", function (err, replies) { + client.mget(replies, redis.print); + }) + .dbsize() + .exec(function (err, replies) { + console.log("MULTI got " + replies.length + " replies"); + replies.forEach(function (reply, index) { + console.log("Reply " + index + ": " + reply.toString()); + }); + } + } ); +} + +function test6() { + var client = redis.createClient(), multi; + + multi = client.multi(); + multi.incr("incr thing", redis.print); + multi.incr("incr other thing", redis.print); + + client.mset("incr thing", 100, "incr other thing", 1, redis.print); + + multi.exec(function (err, replies) { + console.log(replies); + }); + + multi.exec(function (err, replies) { + console.log(replies); + client.quit(); + }); +} + +function test7() { + var client = redis.createClient(), multi; + + client.multi([ + ["mget", "multifoo", "multibar", redis.print], + ["incr", "multifoo"], + ["incr", "multibar"] + ]).exec(function (err, replies) { + console.log(replies); + }); +} + +function test8() { + var util = require("util"); + + client.monitor(function (err, res) { + console.log("Entering monitoring mode."); + }); + + client.on("monitor", function (time, args) { + console.log(time + ": " +util.inspect(args)); + }); +} + +function test9() { + var client = redis.createClient(); + + client.on("connect", function () { + client.set("foo_rand000000000000", "some fantastic value", redis.print); + client.get("foo_rand000000000000", redis.print); + }); +} + +function test10() { + var client = redis.createClient(); + + redis.debug_mode = true; + + client.on("connect", function () { + client.set("foo_rand000000000000", "some fantastic value"); + }); + + var args = ['myzset', 1, 'one', 2, 'two', 3, 'three', 99, 'ninety-nine']; + client.zadd(args, function (err, response) { + if (err) throw err; + console.log('added ' + response + ' items.'); + + var args1 = ['myzset', '+inf', '-inf']; + client.zrevrangebyscore(args1, function (err, response) { + if (err) throw err; + console.log('example1', response); + }); + + var max = 3, min = 1, offset = 1, count = 2; + var args2 = ['myzset', max, min, 'WITHSCORES', 'LIMIT', offset, count]; + client.zrevrangebyscore(args2, function (err, response) { + if (err) throw err; + console.log('example2', response); + }); + }); +} \ No newline at end of file From 52a0dbed757b3ce82f91107715efba97771082f9 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Wed, 24 Oct 2012 05:29:12 +0300 Subject: [PATCH 004/107] node_redis definitions improved substantially + tons of tests --- Definitions/node_redis-0.8.d.ts | 542 +++++----- Tests/redis_node-tests.ts | 1700 ++++++++++++++++++++++++++++++- 2 files changed, 1947 insertions(+), 295 deletions(-) diff --git a/Definitions/node_redis-0.8.d.ts b/Definitions/node_redis-0.8.d.ts index a9ec115fc..4af9a2667 100644 --- a/Definitions/node_redis-0.8.d.ts +++ b/Definitions/node_redis-0.8.d.ts @@ -2,151 +2,152 @@ // Project: https://github.com/mranney/node_redis // Definitions: https://github.com/borisyankov/DefinitelyTyped + declare module 'redis' { export var debug_mode: bool; export function createClient(): RedisClient; - export function createClient(port: string, host: string, options: RedisOptions): RedisClient; + export function createClient(port: number, host: string, options?: RedisOptions): RedisClient; export function print(err: string, reply?: string); interface RedisOptions { - parser: string; - return_buffers: bool; - detect_buffers: bool; - socket_nodelay: bool; - no_ready_check: bool; - enable_offline_queue: bool; + parser?: string; + return_buffers?: bool; + detect_buffers?: bool; + socket_nodelay?: bool; + no_ready_check?: bool; + enable_offline_queue?: bool; } interface Command { - (...args: any[], callback?: Function): Commands; + (...args: any[]): Commands; } interface Commands { - get: Command; - set: Command; - setnx: Command; - setex: Command; - append: Command; - strlen: Command; - del: Command; - exists: Command; - setbit: Command; - getbit: Command; - setrange: Command; - getrange: Command; - substr: Command; - incr: Command; - decr: Command; - mget: Command; - - rpush: Command; - lpush: Command; - rpushx: Command; - lpushx: Command; - linsert: Command; - rpop: Command; - lpop: Command; - brpop: Command; - brpoplpush: Command; - blpop: Command; - llen: Command; - lindex: Command; - lset: Command; - lrange: Command; - ltrim: Command; - lrem: Command; - rpoplpush: Command; - - sadd: Command; - srem: Command; - smove: Command; - sismember: Command; - scard: Command; - spop: Command; - srandmember: Command; - sinter: Command; - sinterstore: Command; - sunion: Command; - sunionstore: Command; - sdiff: Command; - sdiffstore: Command; - smembers: Command; - - zadd: Command; - zincrby: Command; - zrem: Command; - zremrangebyscore: Command; - zremrangebyrank: Command; - zunionstore: Command; - zinterstore: Command; - zrange: Command; - zrangebyscore: Command; - zrevrangebyscore: Command; - zcount: Command; - zrevrange: Command; - zcard: Command; - zscore: Command; - zrank: Command; - zrevrank: Command; - - hset: Command; - hsetnx: Command; - hget: Command; - hmset: Command; - hmget: Command; - hincrby: Command; - hdel: Command; - hlen: Command; - hkeys: Command; - hvals: Command; - hgetall: Command; - hexists: Command; - - incrby: Command; - decrby: Command; - getset: Command; - mset: Command; - msetnx: Command; - randomkey: Command; - select: Command; - move: Command; - rename: Command; - renamenx: Command; - expire: Command; - expireat: Command; - keys: Command; - dbsize: Command; - auth: Command; - ping: Command; - echo: Command; - save: Command; - bgsave: Command; - bgrewriteaof: Command; - shutdown: Command; - lastsave: Command; - type: Command; - multi: Command; - exec: Command; - discard: Command; - sync: Command; - flushdb: Command; - flushall: Command; - sort: Command; - info: Command; - monitor: Command; - ttl: Command; - persist: Command; - slaveof: Command; - debug: Command; - config: Command; - subscribe: Command; - unsubscribe: Command; - psubscribe: Command; - punsubscribe: Command; - publish: Command; - watch: Command; - unwatch: Command; + get: Command; + set: Command; + setnx: Command; + setex: Command; + append: Command; + strlen: Command; + del: Command; + exists: Command; + setbit: Command; + getbit: Command; + setrange: Command; + getrange: Command; + substr: Command; + incr: Command; + decr: Command; + mget: Command; + + rpush: Command; + lpush: Command; + rpushx: Command; + lpushx: Command; + linsert: Command; + rpop: Command; + lpop: Command; + brpop: Command; + brpoplpush: Command; + blpop: Command; + llen: Command; + lindex: Command; + lset: Command; + lrange: Command; + ltrim: Command; + lrem: Command; + rpoplpush: Command; + + sadd: Command; + srem: Command; + smove: Command; + sismember: Command; + scard: Command; + spop: Command; + srandmember: Command; + sinter: Command; + sinterstore: Command; + sunion: Command; + sunionstore: Command; + sdiff: Command; + sdiffstore: Command; + smembers: Command; + + zadd: Command; + zincrby: Command; + zrem: Command; + zremrangebyscore: Command; + zremrangebyrank: Command; + zunionstore: Command; + zinterstore: Command; + zrange: Command; + zrangebyscore: Command; + zrevrangebyscore: Command; + zcount: Command; + zrevrange: Command; + zcard: Command; + zscore: Command; + zrank: Command; + zrevrank: Command; + + hset: Command; + hsetnx: Command; + hget: Command; + hmset: Command; + hmget: Command; + hincrby: Command; + hdel: Command; + hlen: Command; + hkeys: Command; + hvals: Command; + hgetall: Command; + hexists: Command; + + incrby: Command; + decrby: Command; + getset: Command; + mset: Command; + msetnx: Command; + randomkey: Command; + select: Command; + move: Command; + rename: Command; + renamenx: Command; + expire: Command; + expireat: Command; + keys: Command; + dbsize: Command; + auth: Command; + ping: Command; + echo: Command; + save: Command; + bgsave: Command; + bgrewriteaof: Command; + shutdown: Command; + lastsave: Command; + type: Command; + multi: Command; + exec: Command; + discard: Command; + sync: Command; + flushdb: Command; + flushall: Command; + sort: Command; + info: Command; + monitor: Command; + ttl: Command; + persist: Command; + slaveof: Command; + debug: Command; + config: Command; + subscribe: Command; + unsubscribe: Command; + psubscribe: Command; + punsubscribe: Command; + publish: Command; + watch: Command; + unwatch: Command; cluster: Command; restore: Command; migrate: Command; @@ -156,132 +157,134 @@ declare module 'redis' { eval: Command; evalsha: Command; + quit: Command; + ///////////////// - GET: Command; - SET: Command; - SETNX: Command; - SETEX: Command; - APPEND: Command; - STRLEN: Command; - DEL: Command; - EXISTS: Command; - SETBIT: Command; - GETBIT: Command; - SETRANGE: Command; - GETRANGE: Command; - SUBSTR: Command; - INCR: Command; - DECR: Command; - MGET: Command; - - RPUSH: Command; - LPUSH: Command; - RPUSHX: Command; - LPUSHX: Command; - LINSERT: Command; - RPOP: Command; - LPOP: Command; - BRPOP: Command; - BRPOPLPUSH: Command; - BLPOP: Command; - LLEN: Command; - LINDEX: Command; - LSET: Command; - LRANGE: Command; - LTRIM: Command; - LREM: Command; - RPOPLPUSH: Command; - - SADD: Command; - SREM: Command; - SMOVE: Command; - SISMEMBER: Command; - SCARD: Command; - SPOP: Command; - SRANDMEMBER: Command; - SINTER: Command; - SINTERSTORE: Command; - SUNION: Command; - SUNIONSTORE: Command; - SDIFF: Command; - SDIFFSTORE: Command; - SMEMBERS: Command; - - ZADD: Command; - ZINCRBY: Command; - ZREM: Command; - ZREMRANGEBYSCORE: Command; - ZREMRANGEBYRANK: Command; - ZUNIONSTORE: Command; - ZINTERSTORE: Command; - ZRANGE: Command; - ZRANGEBYSCORE: Command; - ZREVRANGEBYSCORE: Command; - ZCOUNT: Command; - ZREVRANGE: Command; - ZCARD: Command; - ZSCORE: Command; - ZRANK: Command; - ZREVRANK: Command; - - HSET: Command; - HSETNX: Command; - HGET: Command; - HMSET: Command; - HMGET: Command; - HINCRBY: Command; - HDEL: Command; - HLEN: Command; - HKEYS: Command; - HVALS: Command; - HGETALL: Command; - HEXISTS: Command; - - INCRBY: Command; - DECRBY: Command; - GETSET: Command; - MSET: Command; - MSETNX: Command; - RANDOMKEY: Command; - SELECT: Command; - MOVE: Command; - RENAME: Command; - RENAMENX: Command; - EXPIRE: Command; - EXPIREAT: Command; - KEYS: Command; - DBSIZE: Command; - AUTH: Command; - PING: Command; - ECHO: Command; - SAVE: Command; - BGSAVE: Command; - BGREWRITEAOF: Command; - SHUTDOWN: Command; - LASTSAVE: Command; - TYPE: Command; - MULTI: Command; - EXEC: Command; - DISCARD: Command; - SYNC: Command; - FLUSHDB: Command; - FLUSHALL: Command; - SORT: Command; - INFO: Command; - MONITOR: Command; - TTL: Command; - PERSIST: Command; - SLAVEOF: Command; - DEBUG: Command; - CONFIG: Command; - SUBSCRIBE: Command; - UNSUBSCRIBE: Command; - PSUBSCRIBE: Command; - PUNSUBSCRIBE: Command; - PUBLISH: Command; - WATCH: Command; - UNWATCH: Command; + GET: Command; + SET: Command; + SETNX: Command; + SETEX: Command; + APPEND: Command; + STRLEN: Command; + DEL: Command; + EXISTS: Command; + SETBIT: Command; + GETBIT: Command; + SETRANGE: Command; + GETRANGE: Command; + SUBSTR: Command; + INCR: Command; + DECR: Command; + MGET: Command; + + RPUSH: Command; + LPUSH: Command; + RPUSHX: Command; + LPUSHX: Command; + LINSERT: Command; + RPOP: Command; + LPOP: Command; + BRPOP: Command; + BRPOPLPUSH: Command; + BLPOP: Command; + LLEN: Command; + LINDEX: Command; + LSET: Command; + LRANGE: Command; + LTRIM: Command; + LREM: Command; + RPOPLPUSH: Command; + + SADD: Command; + SREM: Command; + SMOVE: Command; + SISMEMBER: Command; + SCARD: Command; + SPOP: Command; + SRANDMEMBER: Command; + SINTER: Command; + SINTERSTORE: Command; + SUNION: Command; + SUNIONSTORE: Command; + SDIFF: Command; + SDIFFSTORE: Command; + SMEMBERS: Command; + + ZADD: Command; + ZINCRBY: Command; + ZREM: Command; + ZREMRANGEBYSCORE: Command; + ZREMRANGEBYRANK: Command; + ZUNIONSTORE: Command; + ZINTERSTORE: Command; + ZRANGE: Command; + ZRANGEBYSCORE: Command; + ZREVRANGEBYSCORE: Command; + ZCOUNT: Command; + ZREVRANGE: Command; + ZCARD: Command; + ZSCORE: Command; + ZRANK: Command; + ZREVRANK: Command; + + HSET: Command; + HSETNX: Command; + HGET: Command; + HMSET: Command; + HMGET: Command; + HINCRBY: Command; + HDEL: Command; + HLEN: Command; + HKEYS: Command; + HVALS: Command; + HGETALL: Command; + HEXISTS: Command; + + INCRBY: Command; + DECRBY: Command; + GETSET: Command; + MSET: Command; + MSETNX: Command; + RANDOMKEY: Command; + SELECT: Command; + MOVE: Command; + RENAME: Command; + RENAMENX: Command; + EXPIRE: Command; + EXPIREAT: Command; + KEYS: Command; + DBSIZE: Command; + AUTH: Command; + PING: Command; + ECHO: Command; + SAVE: Command; + BGSAVE: Command; + BGREWRITEAOF: Command; + SHUTDOWN: Command; + LASTSAVE: Command; + TYPE: Command; + MULTI: Command; + EXEC: Command; + DISCARD: Command; + SYNC: Command; + FLUSHDB: Command; + FLUSHALL: Command; + SORT: Command; + INFO: Command; + MONITOR: Command; + TTL: Command; + PERSIST: Command; + SLAVEOF: Command; + DEBUG: Command; + CONFIG: Command; + SUBSCRIBE: Command; + UNSUBSCRIBE: Command; + PSUBSCRIBE: Command; + PUNSUBSCRIBE: Command; + PUBLISH: Command; + WATCH: Command; + UNWATCH: Command; CLUSTER: Command; RESTORE: Command; MIGRATE: Command; @@ -291,18 +294,10 @@ declare module 'redis' { EVAL: Command; EVALSHA: Command; - - hgetall(hash); - hmset(hash, obj, callback?: Function); - hmset(hash, key1, val1, ... keyn, valn, [callback]) - - hmset(args, callback: Function); - HMGET (args, callback: Function); + QUIT: Command; } interface Multi extends Commands { - exec(callback: Function, ...commands: any[]): void; - EXEC(callback: Function, ...commands: any[]): void; } interface RedisClient extends Commands { @@ -322,10 +317,13 @@ declare module 'redis' { return_error(err): void; return_reply(reply): void; send_command(command: string, args: any[], callback?: Function); - send_command(command: string, ...args: any[], callback?: Function); + send_command(command: string, ...args: any[]); pub_sub_command(command: { command: string; args: any[]; }); - eval(): void; + port: number; + host: string; + reply_parser; + stream; server_info; connected: bool; @@ -339,11 +337,11 @@ declare module 'redis' { end(): RedisClient; - on("subscribe", (channel, count) => void); // +emit + on(eventName: string, callback: Function): void; + once(eventName: string, callback: Function): void; + removeListener(eventName: string, callback: Function): void; - send_command(command_name, args, callback) - - multi(...commands: any[]): Multi; - MULTI(...commands: any[]): Multi; + multi(): Multi; + MULTI(): Multi; } } \ No newline at end of file diff --git a/Tests/redis_node-tests.ts b/Tests/redis_node-tests.ts index f900f30fe..db3bfd6a4 100644 --- a/Tests/redis_node-tests.ts +++ b/Tests/redis_node-tests.ts @@ -2,7 +2,7 @@ import redis = module('redis'); -function test1() { +function test1() { var client = redis.createClient(); client.on("error", function (err) { @@ -27,7 +27,9 @@ function test1() { client.get("missingkey", (err, reply) => { }); } -function test2() { { +declare var Buffer; + +function test2() { var client = redis.createClient(null, null, { detect_buffers: true }); @@ -36,6 +38,7 @@ function test2() { { client.get("foo_rand000000000000", (err, reply) => { console.log(reply.toString()); }); + client.get(new Buffer("foo_rand000000000000"), (err, reply) => { console.log(reply.toString()); }); @@ -56,6 +59,7 @@ function test3() { console.dir(obj); }); + var key1, key2; client.HMSET(key2, { "0123456789": "abcdefghij", // NOTE: the key and value must both be strings "some manner of key": "a type of value" @@ -75,13 +79,14 @@ function test4() { }); client1.on("message", function (channel, message) { - console.log("client1 channel " +channel + ": " +message); + console.log("client1 channel " + channel + ": " + message); msg_count += 1; - if(msg_count === 3) { + if (msg_count === 3) { client1.unsubscribe(); client1.end(); client2.end(); - }}); + } + }); client1.incr("did a thing"); client1.subscribe("a nice channel"); @@ -111,7 +116,7 @@ function test5() { console.log("Reply " + index + ": " + reply.toString()); }); } - } ); + ); } function test6() { @@ -124,11 +129,11 @@ function test6() { client.mset("incr thing", 100, "incr other thing", 1, redis.print); multi.exec(function (err, replies) { - console.log(replies); + console.log(replies); }); multi.exec(function (err, replies) { - console.log(replies); + console.log(replies); client.quit(); }); } @@ -146,18 +151,6 @@ function test7() { } function test8() { - var util = require("util"); - - client.monitor(function (err, res) { - console.log("Entering monitoring mode."); - }); - - client.on("monitor", function (time, args) { - console.log(time + ": " +util.inspect(args)); - }); -} - -function test9() { var client = redis.createClient(); client.on("connect", function () { @@ -166,7 +159,7 @@ function test9() { }); } -function test10() { +function test9() { var client = redis.createClient(); redis.debug_mode = true; @@ -175,7 +168,7 @@ function test10() { client.set("foo_rand000000000000", "some fantastic value"); }); - var args = ['myzset', 1, 'one', 2, 'two', 3, 'three', 99, 'ninety-nine']; + var args: any[] = ['myzset', 1, 'one', 2, 'two', 3, 'three', 99, 'ninety-nine']; client.zadd(args, function (err, response) { if (err) throw err; console.log('added ' + response + ' items.'); @@ -193,4 +186,1665 @@ function test10() { console.log('example2', response); }); }); -} \ No newline at end of file +} + + + + + + + + + + + + +/*global require console setTimeout process Buffer */ +var + client = redis.createClient(), + client2 = redis.createClient(), + client3 = redis.createClient(), + assert, + crypto, + util, + test_db_num = 15, // this DB will be flushed and used for testing + connected = false, + ended = false, + next, cur_start, run_next_test, all_tests, all_start, test_count; + + +function buffers_to_strings(arr) { + return arr.map(function (val) { + return val.toString(); + }); +} + +function require_number(expected, label) { + return function (err, results) { + assert.strictEqual(null, err, label + " expected " + expected + ", got error: " + err); + assert.strictEqual(expected, results, label + " " + expected + " !== " + results); + assert.strictEqual(typeof results, "number", label); + return true; + }; +} + +function require_number_any(label) { + return function (err, results) { + assert.strictEqual(null, err, label + " expected any number, got error: " + err); + assert.strictEqual(typeof results, "number", label + " " + results + " is not a number"); + return true; + }; +} + +function require_number_pos(label) { + return function (err, results) { + assert.strictEqual(null, err, label + " expected positive number, got error: " + err); + assert.strictEqual(true, (results > 0), label + " " + results + " is not a positive number"); + return true; + }; +} + +function require_string(str, label) { + return function (err, results) { + assert.strictEqual(null, err, label + " expected string '" + str + "', got error: " + err); + assert.equal(str, results, label + " " + str + " does not match " + results); + return true; + }; +} + +function require_null(label) { + return function (err, results) { + assert.strictEqual(null, err, label + " expected null, got error: " + err); + assert.strictEqual(null, results, label + ": " + results + " is not null"); + return true; + }; +} + +function require_error(label) { + return function (err, results) { + assert.notEqual(err, null, label + " err is null, but an error is expected here."); + return true; + }; +} + +function is_empty_array(obj) { + return Array.isArray(obj) && obj.length === 0; +} + +function last(name, fn) { + return function (err, results) { + fn(err, results); + next(name); + }; +} + +next = function next(name) { + console.log(" \x1b[33m" + (Date.now() - cur_start) + "\x1b[0m ms"); + run_next_test(); +}; + +declare var tests: any; + +tests.FLUSHDB = function () { + var name = "FLUSHDB"; + client.select(test_db_num, require_string("OK", name)); + client2.select(test_db_num, require_string("OK", name)); + client3.select(test_db_num, require_string("OK", name)); + client.mset("flush keys 1", "flush val 1", "flush keys 2", "flush val 2", require_string("OK", name)); + client.FLUSHDB(require_string("OK", name)); + client.dbsize(last(name, require_number(0, name))); +}; + +tests.MULTI_1 = function () { + var name = "MULTI_1", multi1, multi2; + + // Provoke an error at queue time + multi1 = client.multi(); + multi1.mset("multifoo", "10", "multibar", "20", require_string("OK", name)); + multi1.set("foo2", require_error(name)); + multi1.incr("multifoo", require_number(11, name)); + multi1.incr("multibar", require_number(21, name)); + multi1.exec(); + + // Confirm that the previous command, while containing an error, still worked. + multi2 = client.multi(); + multi2.incr("multibar", require_number(22, name)); + multi2.incr("multifoo", require_number(12, name)); + multi2.exec(function (err, replies) { + assert.strictEqual(22, replies[0]); + assert.strictEqual(12, replies[1]); + next(name); + }); +}; + +tests.MULTI_2 = function () { + var name = "MULTI_2"; + + // test nested multi-bulk replies + client.multi([ + ["mget", "multifoo", "multibar", function (err, res) { + assert.strictEqual(2, res.length, name); + assert.strictEqual("12", res[0].toString(), name); + assert.strictEqual("22", res[1].toString(), name); + }], + ["set", "foo2", require_error(name)], + ["incr", "multifoo", require_number(13, name)], + ["incr", "multibar", require_number(23, name)] + ]).exec(function (err, replies) { + assert.strictEqual(2, replies[0].length, name); + assert.strictEqual("12", replies[0][0].toString(), name); + assert.strictEqual("22", replies[0][1].toString(), name); + + assert.strictEqual("13", replies[1].toString()); + assert.strictEqual("23", replies[2].toString()); + next(name); + }); +}; + +tests.MULTI_3 = function () { + var name = "MULTI_3"; + + client.sadd("some set", "mem 1"); + client.sadd("some set", "mem 2"); + client.sadd("some set", "mem 3"); + client.sadd("some set", "mem 4"); + + // make sure empty mb reply works + client.del("some missing set"); + client.smembers("some missing set", function (err, reply) { + // make sure empty mb reply works + assert.strictEqual(true, is_empty_array(reply), name); + }); + + // test nested multi-bulk replies with empty mb elements. + client.multi([ + ["smembers", "some set"], + ["del", "some set"], + ["smembers", "some set"] + ]) + .scard("some set") + .exec(function (err, replies) { + assert.strictEqual(true, is_empty_array(replies[2]), name); + next(name); + }); +}; + +tests.MULTI_4 = function () { + var name = "MULTI_4"; + + client.multi() + .mset('some', '10', 'keys', '20') + .incr('some') + .incr('keys') + .mget('some', 'keys') + .exec(function (err, replies) { + assert.strictEqual(null, err); + assert.equal('OK', replies[0]); + assert.equal(11, replies[1]); + assert.equal(21, replies[2]); + assert.equal(11, replies[3][0].toString()); + assert.equal(21, replies[3][1].toString()); + next(name); + }); +}; + +tests.MULTI_5 = function () { + var name = "MULTI_5"; + + // test nested multi-bulk replies with nulls. + client.multi([ + ["mget", ["multifoo", "some", "random value", "keys"]], + ["incr", "multifoo"] + ]) + .exec(function (err, replies) { + assert.strictEqual(replies.length, 2, name); + assert.strictEqual(replies[0].length, 4, name); + next(name); + }); +}; + +tests.MULTI_6 = function () { + var name = "MULTI_6"; + + client.multi() + .hmset("multihash", "a", "foo", "b", 1) + .hmset("multihash", { + extra: "fancy", + things: "here" + }) + .hgetall("multihash") + .exec(function (err, replies) { + assert.strictEqual(null, err); + assert.equal("OK", replies[0]); + assert.equal(Object.keys(replies[2]).length, 4); + assert.equal("foo", replies[2].a); + assert.equal("1", replies[2].b); + assert.equal("fancy", replies[2].extra); + assert.equal("here", replies[2].things); + next(name); + }); +}; + +tests.EVAL_1 = function () { + var name = "EVAL_1"; + + if (client.server_info.versions[0] >= 2 && client.server_info.versions[1] >= 5) { + // test {EVAL - Lua integer -> Redis protocol type conversion} + client.eval("return 100.5", 0, require_number(100, name)); + // test {EVAL - Lua string -> Redis protocol type conversion} + client.eval("return 'hello world'", 0, require_string("hello world", name)); + // test {EVAL - Lua true boolean -> Redis protocol type conversion} + client.eval("return true", 0, require_number(1, name)); + // test {EVAL - Lua false boolean -> Redis protocol type conversion} + client.eval("return false", 0, require_null(name)); + // test {EVAL - Lua status code reply -> Redis protocol type conversion} + client.eval("return {ok='fine'}", 0, require_string("fine", name)); + // test {EVAL - Lua error reply -> Redis protocol type conversion} + client.eval("return {err='this is an error'}", 0, require_error(name)); + // test {EVAL - Lua table -> Redis protocol type conversion} + client.eval("return {1,2,3,'ciao',{1,2}}", 0, function (err, res) { + assert.strictEqual(5, res.length, name); + assert.strictEqual(1, res[0], name); + assert.strictEqual(2, res[1], name); + assert.strictEqual(3, res[2], name); + assert.strictEqual("ciao", res[3], name); + assert.strictEqual(2, res[4].length, name); + assert.strictEqual(1, res[4][0], name); + assert.strictEqual(2, res[4][1], name); + }); + // test {EVAL - Are the KEYS and ARGS arrays populated correctly?} + client.eval("return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", 2, "a", "b", "c", "d", function (err, res) { + assert.strictEqual(4, res.length, name); + assert.strictEqual("a", res[0], name); + assert.strictEqual("b", res[1], name); + assert.strictEqual("c", res[2], name); + assert.strictEqual("d", res[3], name); + }); + + // prepare sha sum for evalsha cache test + var source = "return redis.call('get', 'sha test')", + sha = crypto.createHash('sha1').update(source).digest('hex'); + + client.set("sha test", "eval get sha test", function (err, res) { + if (err) throw err; + // test {EVAL - is Lua able to call Redis API?} + client.eval(source, 0, function (err, res) { + require_string("eval get sha test", name)(err, res); + // test {EVALSHA - Can we call a SHA1 if already defined?} + client.evalsha(sha, 0, require_string("eval get sha test", name)); + // test {EVALSHA - Do we get an error on non defined SHA1?} + client.evalsha("ffffffffffffffffffffffffffffffffffffffff", 0, require_error(name)); + }); + }); + + // test {EVAL - Redis integer -> Lua type conversion} + client.set("incr key", 0, function (err, reply) { + if (err) throw err; + client.eval("local foo = redis.call('incr','incr key')\n" + "return {type(foo),foo}", 0, function (err, res) { + if (err) throw err; + assert.strictEqual(2, res.length, name); + assert.strictEqual("number", res[0], name); + assert.strictEqual(1, res[1], name); + }); + }); + + client.set("bulk reply key", "bulk reply value", function (err, res) { + // test {EVAL - Redis bulk -> Lua type conversion} + client.eval("local foo = redis.call('get','bulk reply key'); return {type(foo),foo}", 0, function (err, res) { + if (err) throw err; + assert.strictEqual(2, res.length, name); + assert.strictEqual("string", res[0], name); + assert.strictEqual("bulk reply value", res[1], name); + }); + }); + + // test {EVAL - Redis multi bulk -> Lua type conversion} + client.multi() + .del("mylist") + .rpush("mylist", "a") + .rpush("mylist", "b") + .rpush("mylist", "c") + .exec(function (err, replies) { + if (err) throw err; + client.eval("local foo = redis.call('lrange','mylist',0,-1); return {type(foo),foo[1],foo[2],foo[3],# foo}", 0, function (err, res) { + assert.strictEqual(5, res.length, name); + assert.strictEqual("table", res[0], name); + assert.strictEqual("a", res[1], name); + assert.strictEqual("b", res[2], name); + assert.strictEqual("c", res[3], name); + assert.strictEqual(3, res[4], name); + }); + }); + // test {EVAL - Redis status reply -> Lua type conversion} + client.eval("local foo = redis.call('set','mykey','myval'); return {type(foo),foo['ok']}", 0, function (err, res) { + if (err) throw err; + assert.strictEqual(2, res.length, name); + assert.strictEqual("table", res[0], name); + assert.strictEqual("OK", res[1], name); + }); + // test {EVAL - Redis error reply -> Lua type conversion} + client.set("error reply key", "error reply value", function (err, res) { + if (err) throw err; + client.eval("local foo = redis.pcall('incr','error reply key'); return {type(foo),foo['err']}", 0, function (err, res) { + if (err) throw err; + assert.strictEqual(2, res.length, name); + assert.strictEqual("table", res[0], name); + assert.strictEqual("ERR value is not an integer or out of range", res[1], name); + }); + }); + // test {EVAL - Redis nil bulk reply -> Lua type conversion} + client.del("nil reply key", function (err, res) { + if (err) throw err; + client.eval("local foo = redis.call('get','nil reply key'); return {type(foo),foo == false}", 0, function (err, res) { + if (err) throw err; + assert.strictEqual(2, res.length, name); + assert.strictEqual("boolean", res[0], name); + assert.strictEqual(1, res[1], name); + next(name); + }); + }); + } else { + console.log("Skipping " + name + " because server version isn't new enough."); + next(name); + } +}; + +tests.WATCH_MULTI = function () { + var name = 'WATCH_MULTI', multi; + + if (client.server_info.versions[0] >= 2 && client.server_info.versions[1] >= 1) { + client.watch(name); + client.incr(name); + multi = client.multi(); + multi.incr(name); + multi.exec(last(name, require_null(name))); + } else { + console.log("Skipping " + name + " because server version isn't new enough."); + next(name); + } +}; + +tests.detect_buffers = function () { + var name = "detect_buffers", detect_client = redis.createClient(null, null, {detect_buffers: true}); + + detect_client.on("ready", function () { + // single Buffer or String + detect_client.set("string key 1", "string value"); + detect_client.get("string key 1", require_string("string value", name)); + detect_client.get(new Buffer("string key 1"), function (err, reply) { + assert.strictEqual(null, err, name); + assert.strictEqual(true, Buffer.isBuffer(reply), name); + assert.strictEqual("", reply.inspect(), name); + }); + + detect_client.hmset("hash key 2", "key 1", "val 1", "key 2", "val 2"); + // array of Buffers or Strings + detect_client.hmget("hash key 2", "key 1", "key 2", function (err, reply) { + assert.strictEqual(null, err, name); + assert.strictEqual(true, Array.isArray(reply), name); + assert.strictEqual(2, reply.length, name); + assert.strictEqual("val 1", reply[0], name); + assert.strictEqual("val 2", reply[1], name); + }); + detect_client.hmget(new Buffer("hash key 2"), "key 1", "key 2", function (err, reply) { + assert.strictEqual(null, err, name); + assert.strictEqual(true, Array.isArray(reply)); + assert.strictEqual(2, reply.length, name); + assert.strictEqual(true, Buffer.isBuffer(reply[0])); + assert.strictEqual(true, Buffer.isBuffer(reply[1])); + assert.strictEqual("", reply[0].inspect(), name); + assert.strictEqual("", reply[1].inspect(), name); + }); + + // Object of Buffers or Strings + detect_client.hgetall("hash key 2", function (err, reply) { + assert.strictEqual(null, err, name); + assert.strictEqual("object", typeof reply, name); + assert.strictEqual(2, Object.keys(reply).length, name); + assert.strictEqual("val 1", reply["key 1"], name); + assert.strictEqual("val 2", reply["key 2"], name); + }); + detect_client.hgetall(new Buffer("hash key 2"), function (err, reply) { + assert.strictEqual(null, err, name); + assert.strictEqual("object", typeof reply, name); + assert.strictEqual(2, Object.keys(reply).length, name); + assert.strictEqual(true, Buffer.isBuffer(reply["key 1"])); + assert.strictEqual(true, Buffer.isBuffer(reply["key 2"])); + assert.strictEqual("", reply["key 1"].inspect(), name); + assert.strictEqual("", reply["key 2"].inspect(), name); + }); + + detect_client.quit(function (err, res) { + next(name); + }); + }); +}; + +tests.socket_nodelay = function () { + var name = "socket_nodelay", c1, c2, c3, ready_count = 0, quit_count = 0; + + c1 = redis.createClient(null, null, {socket_nodelay: true}); + c2 = redis.createClient(null, null, {socket_nodelay: false}); + c3 = redis.createClient(null, null); + + function quit_check() { + quit_count++; + + if (quit_count === 3) { + next(name); + } + } + + function run() { + assert.strictEqual(true, c1.options.socket_nodelay, name); + assert.strictEqual(false, c2.options.socket_nodelay, name); + assert.strictEqual(true, c3.options.socket_nodelay, name); + + c1.set(["set key 1", "set val"], require_string("OK", name)); + c1.set(["set key 2", "set val"], require_string("OK", name)); + c1.get(["set key 1"], require_string("set val", name)); + c1.get(["set key 2"], require_string("set val", name)); + + c2.set(["set key 3", "set val"], require_string("OK", name)); + c2.set(["set key 4", "set val"], require_string("OK", name)); + c2.get(["set key 3"], require_string("set val", name)); + c2.get(["set key 4"], require_string("set val", name)); + + c3.set(["set key 5", "set val"], require_string("OK", name)); + c3.set(["set key 6", "set val"], require_string("OK", name)); + c3.get(["set key 5"], require_string("set val", name)); + c3.get(["set key 6"], require_string("set val", name)); + + c1.quit(quit_check); + c2.quit(quit_check); + c3.quit(quit_check); + } + + function ready_check() { + ready_count++; + if (ready_count === 3) { + run(); + } + } + + c1.on("ready", ready_check); + c2.on("ready", ready_check); + c3.on("ready", ready_check); +}; + +tests.reconnect = function () { + var name = "reconnect"; + + client.set("recon 1", "one"); + client.set("recon 2", "two", function (err, res) { + // Do not do this in normal programs. This is to simulate the server closing on us. + // For orderly shutdown in normal programs, do client.quit() + client.stream.destroy(); + }); + + client.on("reconnecting", function on_recon(params) { + client.on("connect", function on_connect() { + client.select(test_db_num, require_string("OK", name)); + client.get("recon 1", require_string("one", name)); + client.get("recon 1", require_string("one", name)); + client.get("recon 2", require_string("two", name)); + client.get("recon 2", require_string("two", name)); + client.removeListener("connect", on_connect); + client.removeListener("reconnecting", on_recon); + next(name); + }); + }); +}; + +tests.idle = function () { + var name = "idle"; + + client.on("idle", function on_idle() { + client.removeListener("idle", on_idle); + next(name); + }); + + client.set("idle", "test"); +}; + +tests.HSET = function () { + var key = "test hash", + field1 = new Buffer("0123456789"), + value1 = new Buffer("abcdefghij"), + field2 = new Buffer(0), + value2 = new Buffer(0), + name = "HSET"; + + client.HSET(key, field1, value1, require_number(1, name)); + client.HGET(key, field1, require_string(value1.toString(), name)); + + // Empty value + client.HSET(key, field1, value2, require_number(0, name)); + client.HGET([key, field1], require_string("", name)); + + // Empty key, empty value + client.HSET([key, field2, value1], require_number(1, name)); + client.HSET(key, field2, value2, last(name, require_number(0, name))); +}; + +tests.HLEN = function () { + var key = "test hash", + field1 = new Buffer("0123456789"), + value1 = new Buffer("abcdefghij"), + field2 = new Buffer(0), + value2 = new Buffer(0), + name = "HSET", + timeout = 1000; + + client.HSET(key, field1, value1, function (err, results) { + client.HLEN(key, function (err, len) { + assert.ok(2 === +len); + next(name); + }); + }); +} + +tests.HMSET_BUFFER_AND_ARRAY = function () { + // Saving a buffer and an array to the same key should not error + var key = "test hash", + field1 = "buffer", + value1 = new Buffer("abcdefghij"), + field2 = "array", + value2 = ["array contents"], + name = "HSET"; + + client.HMSET(key, field1, value1, field2, value2, last(name, require_string("OK", name))); +}; + +// TODO - add test for HMSET with optional callbacks + +tests.HMGET = function () { + var key1 = "test hash 1", key2 = "test hash 2", name = "HMGET"; + + // redis-like hmset syntax + client.HMSET(key1, "0123456789", "abcdefghij", "some manner of key", "a type of value", require_string("OK", name)); + + // fancy hmset syntax + client.HMSET(key2, { + "0123456789": "abcdefghij", + "some manner of key": "a type of value" + }, require_string("OK", name)); + + client.HMGET(key1, "0123456789", "some manner of key", function (err, reply) { + assert.strictEqual("abcdefghij", reply[0].toString(), name); + assert.strictEqual("a type of value", reply[1].toString(), name); + }); + + client.HMGET(key2, "0123456789", "some manner of key", function (err, reply) { + assert.strictEqual("abcdefghij", reply[0].toString(), name); + assert.strictEqual("a type of value", reply[1].toString(), name); + }); + + client.HMGET(key1, ["0123456789"], function (err, reply) { + assert.strictEqual("abcdefghij", reply[0], name); + }); + + client.HMGET(key1, ["0123456789", "some manner of key"], function (err, reply) { + assert.strictEqual("abcdefghij", reply[0], name); + assert.strictEqual("a type of value", reply[1], name); + }); + + client.HMGET(key1, "missing thing", "another missing thing", function (err, reply) { + assert.strictEqual(null, reply[0], name); + assert.strictEqual(null, reply[1], name); + next(name); + }); +}; + +tests.HINCRBY = function () { + var name = "HINCRBY"; + client.hset("hash incr", "value", 10, require_number(1, name)); + client.HINCRBY("hash incr", "value", 1, require_number(11, name)); + client.HINCRBY("hash incr", "value 2", 1, last(name, require_number(1, name))); +}; + +tests.SUBSCRIBE = function () { + var client1 = client, msg_count = 0, name = "SUBSCRIBE"; + + client1.on("subscribe", function (channel, count) { + if (channel === "chan1") { + client2.publish("chan1", "message 1", require_number(1, name)); + client2.publish("chan2", "message 2", require_number(1, name)); + client2.publish("chan1", "message 3", require_number(1, name)); + } + }); + + client1.on("unsubscribe", function (channel, count) { + if (count === 0) { + // make sure this connection can go into and out of pub/sub mode + client1.incr("did a thing", last(name, require_number(2, name))); + } + }); + + client1.on("message", function (channel, message) { + msg_count += 1; + assert.strictEqual("message " + msg_count, message.toString()); + if (msg_count === 3) { + client1.unsubscribe("chan1", "chan2"); + } + }); + + client1.set("did a thing", 1, require_string("OK", name)); + client1.subscribe("chan1", "chan2", function (err, results) { + assert.strictEqual(null, err, "result sent back unexpected error: " + err); + assert.strictEqual("chan1", results.toString(), name); + }); +}; + +tests.SUB_UNSUB_SUB = function () { + var name = "SUB_UNSUB_SUB"; + client3.subscribe('chan3'); + client3.unsubscribe('chan3'); + client3.subscribe('chan3', function (err, results) { + assert.strictEqual(null, err, "unexpected error: " + err); + client2.publish('chan3', 'foo'); + }); + client3.on('message', function (channel, message) { + assert.strictEqual(channel, 'chan3'); + assert.strictEqual(message, 'foo'); + next(name); + }); +}; + +tests.SUBSCRIBE_QUIT = function () { + var name = "SUBSCRIBE_QUIT"; + client3.on("end", function () { + next(name); + }); + client3.on("subscribe", function (channel, count) { + client3.quit(); + }); + client3.subscribe("chan3"); +}; + +tests.SUBSCRIBE_CLOSE_RESUBSCRIBE = function () { + var name = "SUBSCRIBE_CLOSE_RESUBSCRIBE"; + var c1 = redis.createClient(); + var c2 = redis.createClient(); + var count = 0; + + /* Create two clients. c1 subscribes to two channels, c2 will publish to them. + c2 publishes the first message. + c1 gets the message and drops its connection. It must resubscribe itself. + When it resubscribes, c2 publishes the second message, on the same channel + c1 gets the message and drops its connection. It must resubscribe itself, again. + When it resubscribes, c2 publishes the third message, on the second channel + c1 gets the message and drops its connection. When it reconnects, the test ends. + */ + + c1.on("message", function(channel, message) { + if (channel === "chan1") { + assert.strictEqual(message, "hi on channel 1"); + c1.stream.end(); + + } else if (channel === "chan2") { + assert.strictEqual(message, "hi on channel 2"); + c1.stream.end(); + + } else { + c1.quit(); + c2.quit(); + assert.fail("test failed"); + } + }) + + c1.subscribe("chan1", "chan2"); + + c2.once("ready", function() { + console.log("c2 is ready"); + c1.on("ready", function(err, results) { + console.log("c1 is ready", count); + + count++; + if (count == 1) { + c2.publish("chan1", "hi on channel 1"); + return; + + } else if (count == 2) { + c2.publish("chan2", "hi on channel 2"); + + } else { + c1.quit(function() { + c2.quit(function() { + next(name); + }); + }); + } + }); + + c2.publish("chan1", "hi on channel 1"); + + }); +}; + +tests.EXISTS = function () { + var name = "EXISTS"; + client.del("foo", "foo2", require_number_any(name)); + client.set("foo", "bar", require_string("OK", name)); + client.EXISTS("foo", require_number(1, name)); + client.EXISTS("foo2", last(name, require_number(0, name))); +}; + +tests.DEL = function () { + var name = "DEL"; + client.DEL("delkey", require_number_any(name)); + client.set("delkey", "delvalue", require_string("OK", name)); + client.DEL("delkey", require_number(1, name)); + client.exists("delkey", require_number(0, name)); + client.DEL("delkey", require_number(0, name)); + client.mset("delkey", "delvalue", "delkey2", "delvalue2", require_string("OK", name)); + client.DEL("delkey", "delkey2", last(name, require_number(2, name))); +}; + +tests.TYPE = function () { + var name = "TYPE"; + client.set(["string key", "should be a string"], require_string("OK", name)); + client.rpush(["list key", "should be a list"], require_number_pos(name)); + client.sadd(["set key", "should be a set"], require_number_any(name)); + client.zadd(["zset key", "10.0", "should be a zset"], require_number_any(name)); + client.hset(["hash key", "hashtest", "should be a hash"], require_number_any(0, name)); + + client.TYPE(["string key"], require_string("string", name)); + client.TYPE(["list key"], require_string("list", name)); + client.TYPE(["set key"], require_string("set", name)); + client.TYPE(["zset key"], require_string("zset", name)); + client.TYPE("not here yet", require_string("none", name)); + client.TYPE(["hash key"], last(name, require_string("hash", name))); +}; + +tests.KEYS = function () { + var name = "KEYS"; + client.mset(["test keys 1", "test val 1", "test keys 2", "test val 2"], require_string("OK", name)); + client.KEYS(["test keys*"], function (err, results) { + assert.strictEqual(null, err, "result sent back unexpected error: " + err); + assert.strictEqual(2, results.length, name); + assert.strictEqual("test keys 1", results[0].toString(), name); + assert.strictEqual("test keys 2", results[1].toString(), name); + next(name); + }); +}; + +tests.MULTIBULK = function() { + var name = "MULTIBULK", + keys_values = []; + + for (var i = 0; i < 200; i++) { + var key_value = [ + "multibulk:" + crypto.randomBytes(256).toString("hex"), // use long strings as keys to ensure generation of large packet + "test val " + i + ]; + keys_values.push(key_value); + } + + client.mset(keys_values.reduce(function(a, b) { + return a.concat(b); + }), require_string("OK", name)); + + client.KEYS("multibulk:*", function(err, results) { + assert.strictEqual(null, err, "result sent back unexpected error: " + err); + assert.deepEqual(keys_values.map(function(val) { + return val[0]; + }).sort(), results.sort(), name); + }); + + next(name); +}; + +tests.MULTIBULK_ZERO_LENGTH = function () { + var name = "MULTIBULK_ZERO_LENGTH"; + client.KEYS(['users:*'], function (err, results) { + assert.strictEqual(null, err, 'error on empty multibulk reply'); + assert.strictEqual(true, is_empty_array(results), "not an empty array"); + next(name); + }); +}; + +tests.RANDOMKEY = function () { + var name = "RANDOMKEY"; + client.mset(["test keys 1", "test val 1", "test keys 2", "test val 2"], require_string("OK", name)); + client.RANDOMKEY([], function (err, results) { + assert.strictEqual(null, err, name + " result sent back unexpected error: " + err); + assert.strictEqual(true, /\w+/.test(results), name); + next(name); + }); +}; + +tests.RENAME = function () { + var name = "RENAME"; + client.set(['foo', 'bar'], require_string("OK", name)); + client.RENAME(["foo", "new foo"], require_string("OK", name)); + client.exists(["foo"], require_number(0, name)); + client.exists(["new foo"], last(name, require_number(1, name))); +}; + +tests.RENAMENX = function () { + var name = "RENAMENX"; + client.set(['foo', 'bar'], require_string("OK", name)); + client.set(['foo2', 'bar2'], require_string("OK", name)); + client.RENAMENX(["foo", "foo2"], require_number(0, name)); + client.exists(["foo"], require_number(1, name)); + client.exists(["foo2"], require_number(1, name)); + client.del(["foo2"], require_number(1, name)); + client.RENAMENX(["foo", "foo2"], require_number(1, name)); + client.exists(["foo"], require_number(0, name)); + client.exists(["foo2"], last(name, require_number(1, name))); +}; + +tests.DBSIZE = function () { + var name = "DBSIZE"; + client.set(['foo', 'bar'], require_string("OK", name)); + client.DBSIZE([], last(name, require_number_pos("DBSIZE"))); +}; + +tests.GET_1 = function () { + var name = "GET_1"; + client.set(["get key", "get val"], require_string("OK", name)); + client.GET(["get key"], last(name, require_string("get val", name))); +}; + +tests.GET_2 = function() { + var name = "GET_2"; + + // tests handling of non-existent keys + client.GET('this_key_shouldnt_exist', last(name, require_null(name))); +}; + +tests.SET = function () { + var name = "SET"; + client.SET(["set key", "set val"], require_string("OK", name)); + client.get(["set key"], last(name, require_string("set val", name))); +}; + +tests.GETSET = function () { + var name = "GETSET"; + client.set(["getset key", "getset val"], require_string("OK", name)); + client.GETSET(["getset key", "new getset val"], require_string("getset val", name)); + client.get(["getset key"], last(name, require_string("new getset val", name))); +}; + +tests.MGET = function () { + var name = "MGET"; + client.mset(["mget keys 1", "mget val 1", "mget keys 2", "mget val 2", "mget keys 3", "mget val 3"], require_string("OK", name)); + client.MGET("mget keys 1", "mget keys 2", "mget keys 3", function (err, results) { + assert.strictEqual(null, err, "result sent back unexpected error: " + err); + assert.strictEqual(3, results.length, name); + assert.strictEqual("mget val 1", results[0].toString(), name); + assert.strictEqual("mget val 2", results[1].toString(), name); + assert.strictEqual("mget val 3", results[2].toString(), name); + }); + client.MGET(["mget keys 1", "mget keys 2", "mget keys 3"], function (err, results) { + assert.strictEqual(null, err, "result sent back unexpected error: " + err); + assert.strictEqual(3, results.length, name); + assert.strictEqual("mget val 1", results[0].toString(), name); + assert.strictEqual("mget val 2", results[1].toString(), name); + assert.strictEqual("mget val 3", results[2].toString(), name); + }); + client.MGET(["mget keys 1", "some random shit", "mget keys 2", "mget keys 3"], function (err, results) { + assert.strictEqual(null, err, "result sent back unexpected error: " + err); + assert.strictEqual(4, results.length, name); + assert.strictEqual("mget val 1", results[0].toString(), name); + assert.strictEqual(null, results[1], name); + assert.strictEqual("mget val 2", results[2].toString(), name); + assert.strictEqual("mget val 3", results[3].toString(), name); + next(name); + }); +}; + +tests.SETNX = function () { + var name = "SETNX"; + client.set(["setnx key", "setnx value"], require_string("OK", name)); + client.SETNX(["setnx key", "new setnx value"], require_number(0, name)); + client.del(["setnx key"], require_number(1, name)); + client.exists(["setnx key"], require_number(0, name)); + client.SETNX(["setnx key", "new setnx value"], require_number(1, name)); + client.exists(["setnx key"], last(name, require_number(1, name))); +}; + +tests.SETEX = function () { + var name = "SETEX"; + client.SETEX(["setex key", "100", "setex val"], require_string("OK", name)); + client.exists(["setex key"], require_number(1, name)); + client.ttl(["setex key"], last(name, require_number_pos(name))); +}; + +tests.MSETNX = function () { + var name = "MSETNX"; + client.mset(["mset1", "val1", "mset2", "val2", "mset3", "val3"], require_string("OK", name)); + client.MSETNX(["mset3", "val3", "mset4", "val4"], require_number(0, name)); + client.del(["mset3"], require_number(1, name)); + client.MSETNX(["mset3", "val3", "mset4", "val4"], require_number(1, name)); + client.exists(["mset3"], require_number(1, name)); + client.exists(["mset4"], last(name, require_number(1, name))); +}; + +tests.HGETALL = function () { + var name = "HGETALL"; + client.hmset(["hosts", "mjr", "1", "another", "23", "home", "1234"], require_string("OK", name)); + client.HGETALL(["hosts"], function (err, obj) { + assert.strictEqual(null, err, name + " result sent back unexpected error: " + err); + assert.strictEqual(3, Object.keys(obj).length, name); + assert.strictEqual("1", obj.mjr.toString(), name); + assert.strictEqual("23", obj.another.toString(), name); + assert.strictEqual("1234", obj.home.toString(), name); + next(name); + }); +}; + +tests.HGETALL_NULL = function () { + var name = "HGETALL_NULL"; + + client.hgetall("missing", function (err, obj) { + assert.strictEqual(null, err); + assert.strictEqual(null, obj); + next(name); + }); +}; + +tests.UTF8 = function () { + var name = "UTF8", + utf8_sample = "?_?"; + + client.set(["utf8test", utf8_sample], require_string("OK", name)); + client.get(["utf8test"], function (err, obj) { + assert.strictEqual(null, err); + assert.strictEqual(utf8_sample, obj); + next(name); + }); +}; + +// Set tests were adapted from Brian Hammond's redis-node-client.js, which has a comprehensive test suite + +tests.SADD = function () { + var name = "SADD"; + + client.del('set0'); + client.SADD('set0', 'member0', require_number(1, name)); + client.sadd('set0', 'member0', last(name, require_number(0, name))); +}; + +tests.SADD2 = function () { + var name = "SADD2"; + + client.del("set0"); + client.sadd("set0", ["member0", "member1", "member2"], require_number(3, name)); + client.smembers("set0", function (err, res) { + assert.strictEqual(res.length, 3); + assert.strictEqual(res[0], "member0"); + assert.strictEqual(res[1], "member1"); + assert.strictEqual(res[2], "member2"); + }); + client.SADD("set1", ["member0", "member1", "member2"], require_number(3, name)); + client.smembers("set1", function (err, res) { + assert.strictEqual(res.length, 3); + assert.strictEqual(res[0], "member0"); + assert.strictEqual(res[1], "member1"); + assert.strictEqual(res[2], "member2"); + next(name); + }); +}; + +tests.SISMEMBER = function () { + var name = "SISMEMBER"; + + client.del('set0'); + client.sadd('set0', 'member0', require_number(1, name)); + client.sismember('set0', 'member0', require_number(1, name)); + client.sismember('set0', 'member1', last(name, require_number(0, name))); +}; + +tests.SCARD = function () { + var name = "SCARD"; + + client.del('set0'); + client.sadd('set0', 'member0', require_number(1, name)); + client.scard('set0', require_number(1, name)); + client.sadd('set0', 'member1', require_number(1, name)); + client.scard('set0', last(name, require_number(2, name))); +}; + +tests.SREM = function () { + var name = "SREM"; + + client.del('set0'); + client.sadd('set0', 'member0', require_number(1, name)); + client.srem('set0', 'foobar', require_number(0, name)); + client.srem('set0', 'member0', require_number(1, name)); + client.scard('set0', last(name, require_number(0, name))); +}; + +tests.SPOP = function () { + var name = "SPOP"; + + client.del('zzz'); + client.sadd('zzz', 'member0', require_number(1, name)); + client.scard('zzz', require_number(1, name)); + + client.spop('zzz', function (err, value) { + if (err) { + assert.fail(err); + } + assert.equal(value, 'member0', name); + }); + + client.scard('zzz', last(name, require_number(0, name))); +}; + +tests.SDIFF = function () { + var name = "SDIFF"; + + client.del('foo'); + client.sadd('foo', 'x', require_number(1, name)); + client.sadd('foo', 'a', require_number(1, name)); + client.sadd('foo', 'b', require_number(1, name)); + client.sadd('foo', 'c', require_number(1, name)); + + client.sadd('bar', 'c', require_number(1, name)); + + client.sadd('baz', 'a', require_number(1, name)); + client.sadd('baz', 'd', require_number(1, name)); + + client.sdiff('foo', 'bar', 'baz', function (err, values) { + if (err) { + assert.fail(err, name); + } + values.sort(); + assert.equal(values.length, 2, name); + assert.equal(values[0], 'b', name); + assert.equal(values[1], 'x', name); + next(name); + }); +}; + +tests.SDIFFSTORE = function () { + var name = "SDIFFSTORE"; + + client.del('foo'); + client.del('bar'); + client.del('baz'); + client.del('quux'); + + client.sadd('foo', 'x', require_number(1, name)); + client.sadd('foo', 'a', require_number(1, name)); + client.sadd('foo', 'b', require_number(1, name)); + client.sadd('foo', 'c', require_number(1, name)); + + client.sadd('bar', 'c', require_number(1, name)); + + client.sadd('baz', 'a', require_number(1, name)); + client.sadd('baz', 'd', require_number(1, name)); + + // NB: SDIFFSTORE returns the number of elements in the dstkey + + client.sdiffstore('quux', 'foo', 'bar', 'baz', require_number(2, name)); + + client.smembers('quux', function (err, values) { + if (err) { + assert.fail(err, name); + } + var members = buffers_to_strings(values).sort(); + + assert.deepEqual(members, [ 'b', 'x' ], name); + next(name); + }); +}; + +tests.SMEMBERS = function () { + var name = "SMEMBERS"; + + client.del('foo'); + client.sadd('foo', 'x', require_number(1, name)); + + client.smembers('foo', function (err, members) { + if (err) { + assert.fail(err, name); + } + assert.deepEqual(buffers_to_strings(members), [ 'x' ], name); + }); + + client.sadd('foo', 'y', require_number(1, name)); + + client.smembers('foo', function (err, values) { + if (err) { + assert.fail(err, name); + } + assert.equal(values.length, 2, name); + var members = buffers_to_strings(values).sort(); + + assert.deepEqual(members, [ 'x', 'y' ], name); + next(name); + }); +}; + +tests.SMOVE = function () { + var name = "SMOVE"; + + client.del('foo'); + client.del('bar'); + + client.sadd('foo', 'x', require_number(1, name)); + client.smove('foo', 'bar', 'x', require_number(1, name)); + client.sismember('foo', 'x', require_number(0, name)); + client.sismember('bar', 'x', require_number(1, name)); + client.smove('foo', 'bar', 'x', last(name, require_number(0, name))); +}; + +tests.SINTER = function () { + var name = "SINTER"; + + client.del('sa'); + client.del('sb'); + client.del('sc'); + + client.sadd('sa', 'a', require_number(1, name)); + client.sadd('sa', 'b', require_number(1, name)); + client.sadd('sa', 'c', require_number(1, name)); + + client.sadd('sb', 'b', require_number(1, name)); + client.sadd('sb', 'c', require_number(1, name)); + client.sadd('sb', 'd', require_number(1, name)); + + client.sadd('sc', 'c', require_number(1, name)); + client.sadd('sc', 'd', require_number(1, name)); + client.sadd('sc', 'e', require_number(1, name)); + + client.sinter('sa', 'sb', function (err, intersection) { + if (err) { + assert.fail(err, name); + } + assert.equal(intersection.length, 2, name); + assert.deepEqual(buffers_to_strings(intersection).sort(), [ 'b', 'c' ], name); + }); + + client.sinter('sb', 'sc', function (err, intersection) { + if (err) { + assert.fail(err, name); + } + assert.equal(intersection.length, 2, name); + assert.deepEqual(buffers_to_strings(intersection).sort(), [ 'c', 'd' ], name); + }); + + client.sinter('sa', 'sc', function (err, intersection) { + if (err) { + assert.fail(err, name); + } + assert.equal(intersection.length, 1, name); + assert.equal(intersection[0], 'c', name); + }); + + // 3-way + + client.sinter('sa', 'sb', 'sc', function (err, intersection) { + if (err) { + assert.fail(err, name); + } + assert.equal(intersection.length, 1, name); + assert.equal(intersection[0], 'c', name); + next(name); + }); +}; + +tests.SINTERSTORE = function () { + var name = "SINTERSTORE"; + + client.del('sa'); + client.del('sb'); + client.del('sc'); + client.del('foo'); + + client.sadd('sa', 'a', require_number(1, name)); + client.sadd('sa', 'b', require_number(1, name)); + client.sadd('sa', 'c', require_number(1, name)); + + client.sadd('sb', 'b', require_number(1, name)); + client.sadd('sb', 'c', require_number(1, name)); + client.sadd('sb', 'd', require_number(1, name)); + + client.sadd('sc', 'c', require_number(1, name)); + client.sadd('sc', 'd', require_number(1, name)); + client.sadd('sc', 'e', require_number(1, name)); + + client.sinterstore('foo', 'sa', 'sb', 'sc', require_number(1, name)); + + client.smembers('foo', function (err, members) { + if (err) { + assert.fail(err, name); + } + assert.deepEqual(buffers_to_strings(members), [ 'c' ], name); + next(name); + }); +}; + +tests.SUNION = function () { + var name = "SUNION"; + + client.del('sa'); + client.del('sb'); + client.del('sc'); + + client.sadd('sa', 'a', require_number(1, name)); + client.sadd('sa', 'b', require_number(1, name)); + client.sadd('sa', 'c', require_number(1, name)); + + client.sadd('sb', 'b', require_number(1, name)); + client.sadd('sb', 'c', require_number(1, name)); + client.sadd('sb', 'd', require_number(1, name)); + + client.sadd('sc', 'c', require_number(1, name)); + client.sadd('sc', 'd', require_number(1, name)); + client.sadd('sc', 'e', require_number(1, name)); + + client.sunion('sa', 'sb', 'sc', function (err, union) { + if (err) { + assert.fail(err, name); + } + assert.deepEqual(buffers_to_strings(union).sort(), ['a', 'b', 'c', 'd', 'e'], name); + next(name); + }); +}; + +tests.SUNIONSTORE = function () { + var name = "SUNIONSTORE"; + + client.del('sa'); + client.del('sb'); + client.del('sc'); + client.del('foo'); + + client.sadd('sa', 'a', require_number(1, name)); + client.sadd('sa', 'b', require_number(1, name)); + client.sadd('sa', 'c', require_number(1, name)); + + client.sadd('sb', 'b', require_number(1, name)); + client.sadd('sb', 'c', require_number(1, name)); + client.sadd('sb', 'd', require_number(1, name)); + + client.sadd('sc', 'c', require_number(1, name)); + client.sadd('sc', 'd', require_number(1, name)); + client.sadd('sc', 'e', require_number(1, name)); + + client.sunionstore('foo', 'sa', 'sb', 'sc', function (err, cardinality) { + if (err) { + assert.fail(err, name); + } + assert.equal(cardinality, 5, name); + }); + + client.smembers('foo', function (err, members) { + if (err) { + assert.fail(err, name); + } + assert.equal(members.length, 5, name); + assert.deepEqual(buffers_to_strings(members).sort(), ['a', 'b', 'c', 'd', 'e'], name); + next(name); + }); +}; + +// SORT test adapted from Brian Hammond's redis-node-client.js, which has a comprehensive test suite + +tests.SORT = function () { + var name = "SORT"; + + client.del('y'); + client.del('x'); + + client.rpush('y', 'd', require_number(1, name)); + client.rpush('y', 'b', require_number(2, name)); + client.rpush('y', 'a', require_number(3, name)); + client.rpush('y', 'c', require_number(4, name)); + + client.rpush('x', '3', require_number(1, name)); + client.rpush('x', '9', require_number(2, name)); + client.rpush('x', '2', require_number(3, name)); + client.rpush('x', '4', require_number(4, name)); + + client.set('w3', '4', require_string("OK", name)); + client.set('w9', '5', require_string("OK", name)); + client.set('w2', '12', require_string("OK", name)); + client.set('w4', '6', require_string("OK", name)); + + client.set('o2', 'buz', require_string("OK", name)); + client.set('o3', 'foo', require_string("OK", name)); + client.set('o4', 'baz', require_string("OK", name)); + client.set('o9', 'bar', require_string("OK", name)); + + client.set('p2', 'qux', require_string("OK", name)); + client.set('p3', 'bux', require_string("OK", name)); + client.set('p4', 'lux', require_string("OK", name)); + client.set('p9', 'tux', require_string("OK", name)); + + // Now the data has been setup, we can test. + + // But first, test basic sorting. + + // y = [ d b a c ] + // sort y ascending = [ a b c d ] + // sort y descending = [ d c b a ] + + client.sort('y', 'asc', 'alpha', function (err, sorted) { + if (err) { + assert.fail(err, name); + } + assert.deepEqual(buffers_to_strings(sorted), ['a', 'b', 'c', 'd'], name); + }); + + client.sort('y', 'desc', 'alpha', function (err, sorted) { + if (err) { + assert.fail(err, name); + } + assert.deepEqual(buffers_to_strings(sorted), ['d', 'c', 'b', 'a'], name); + }); + + // Now try sorting numbers in a list. + // x = [ 3, 9, 2, 4 ] + + client.sort('x', 'asc', function (err, sorted) { + if (err) { + assert.fail(err, name); + } + assert.deepEqual(buffers_to_strings(sorted), [2, 3, 4, 9], name); + }); + + client.sort('x', 'desc', function (err, sorted) { + if (err) { + assert.fail(err, name); + } + assert.deepEqual(buffers_to_strings(sorted), [9, 4, 3, 2], name); + }); + + // Try sorting with a 'by' pattern. + + client.sort('x', 'by', 'w*', 'asc', function (err, sorted) { + if (err) { + assert.fail(err, name); + } + assert.deepEqual(buffers_to_strings(sorted), [3, 9, 4, 2], name); + }); + + // Try sorting with a 'by' pattern and 1 'get' pattern. + + client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', function (err, sorted) { + if (err) { + assert.fail(err, name); + } + assert.deepEqual(buffers_to_strings(sorted), ['foo', 'bar', 'baz', 'buz'], name); + }); + + // Try sorting with a 'by' pattern and 2 'get' patterns. + + client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*', function (err, sorted) { + if (err) { + assert.fail(err, name); + } + assert.deepEqual(buffers_to_strings(sorted), ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux'], name); + }); + + // Try sorting with a 'by' pattern and 2 'get' patterns. + // Instead of getting back the sorted set/list, store the values to a list. + // Then check that the values are there in the expected order. + + client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*', 'store', 'bacon', function (err) { + if (err) { + assert.fail(err, name); + } + }); + + client.lrange('bacon', 0, -1, function (err, values) { + if (err) { + assert.fail(err, name); + } + assert.deepEqual(buffers_to_strings(values), ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux'], name); + next(name); + }); + + // TODO - sort by hash value +}; + +tests.MONITOR = function () { + var name = "MONITOR", responses = [], monitor_client; + + monitor_client = redis.createClient(); + monitor_client.monitor(function (err, res) { + client.mget("some", "keys", "foo", "bar"); + client.set("json", JSON.stringify({ + foo: "123", + bar: "sdflkdfsjk", + another: false + })); + }); + monitor_client.on("monitor", function (time, args) { + // skip monitor command for Redis <= 2.4.16 + if (args[0] === "monitor") return; + + responses.push(args); + if (responses.length === 2) { + assert.strictEqual(5, responses[0].length); + assert.strictEqual("mget", responses[0][0]); + assert.strictEqual("some", responses[0][1]); + assert.strictEqual("keys", responses[0][2]); + assert.strictEqual("foo", responses[0][3]); + assert.strictEqual("bar", responses[0][4]); + assert.strictEqual(3, responses[1].length); + assert.strictEqual("set", responses[1][0]); + assert.strictEqual("json", responses[1][1]); + assert.strictEqual('{"foo":"123","bar":"sdflkdfsjk","another":false}', responses[1][2]); + monitor_client.quit(function (err, res) { + next(name); + }); + } + }); +}; + +tests.BLPOP = function () { + var name = "BLPOP"; + + client.rpush("blocking list", "initial value", function (err, res) { + client2.BLPOP("blocking list", 0, function (err, res) { + assert.strictEqual("blocking list", res[0].toString()); + assert.strictEqual("initial value", res[1].toString()); + + client.rpush("blocking list", "wait for this value"); + }); + client2.BLPOP("blocking list", 0, function (err, res) { + assert.strictEqual("blocking list", res[0].toString()); + assert.strictEqual("wait for this value", res[1].toString()); + next(name); + }); + }); +}; + +tests.BLPOP_TIMEOUT = function () { + var name = "BLPOP_TIMEOUT"; + + // try to BLPOP the list again, which should be empty. This should timeout and return null. + client2.BLPOP("blocking list", 1, function (err, res) { + if (err) { + throw err; + } + + assert.strictEqual(res, null); + next(name); + }); +}; + +tests.EXPIRE = function () { + var name = "EXPIRE"; + client.set(['expiry key', 'bar'], require_string("OK", name)); + client.EXPIRE(["expiry key", "1"], require_number_pos(name)); + setTimeout(function () { + client.exists(["expiry key"], last(name, require_number(0, name))); + }, 2000); +}; + +tests.TTL = function () { + var name = "TTL"; + client.set(["ttl key", "ttl val"], require_string("OK", name)); + client.expire(["ttl key", "100"], require_number_pos(name)); + setTimeout(function () { + client.TTL(["ttl key"], last(name, require_number_pos(0, name))); + }, 500); +}; + +tests.OPTIONAL_CALLBACK = function () { + var name = "OPTIONAL_CALLBACK"; + client.del("op_cb1"); + client.set("op_cb1", "x"); + client.get("op_cb1", last(name, require_string("x", name))); +}; + +tests.OPTIONAL_CALLBACK_UNDEFINED = function () { + var name = "OPTIONAL_CALLBACK_UNDEFINED"; + client.del("op_cb2"); + client.set("op_cb2", "y", undefined); + client.get("op_cb2", last(name, require_string("y", name))); +}; + +tests.HMSET_THROWS_ON_NON_STRINGS = function () { + var name = "HMSET_THROWS_ON_NON_STRINGS"; + var hash = name; + var data = { "a": [ "this is not a string" ] }; + + client.hmset(hash, data, cb); + function cb(e, r) { + assert(e); // should be an error! + } + + // alternative way it throws + function thrower() { + client.hmset(hash, data); + } + assert.throws(thrower); + next(name); +}; + +tests.ENABLE_OFFLINE_QUEUE_TRUE = function () { + var name = "ENABLE_OFFLINE_QUEUE_TRUE"; + var cli = redis.createClient(9999, null, { + max_attempts: 1 + // default :) + // enable_offline_queue: true + }); + cli.on('error', function(e) { + // ignore, b/c expecting a "can't connect" error + }); + return setTimeout(function() { + cli.set(name, name, function(err, result) { + assert.ifError(err); + }); + + return setTimeout(function(){ + assert.strictEqual(cli.offline_queue.length, 1); + return next(name); + }, 25); + }, 50); +}; + +tests.ENABLE_OFFLINE_QUEUE_FALSE = function () { + var name = "ENABLE_OFFLINE_QUEUE_FALSE"; + var cli = redis.createClient(9999, null, { + max_attempts: 1, + enable_offline_queue: false + }); + cli.on('error', function() { + // ignore, see above + }); + assert.throws(function () { + cli.set(name, name) + }) + assert.doesNotThrow(function () { + cli.set(name, name, function (err) { + // should callback with an error + assert.ok(err); + setTimeout(function () { + next(name); + }, 50); + }); + }); +}; + +// TODO - need a better way to test auth, maybe auto-config a local Redis server or something. +// Yes, this is the real password. Please be nice, thanks. +tests.auth = function () { + var name = "AUTH", client4, ready_count = 0; + + client4 = redis.createClient(9006, "filefish.redistogo.com"); + client4.auth("664b1b6aaf134e1ec281945a8de702a9", function (err, res) { + assert.strictEqual(null, err, name); + assert.strictEqual("OK", res.toString(), name); + }); + + // test auth, then kill the connection so it'll auto-reconnect and auto-re-auth + client4.on("ready", function () { + ready_count++; + if (ready_count === 1) { + client4.stream.destroy(); + } else { + client4.quit(function (err, res) { + next(name); + }); + } + }); +}; + +all_tests = Object.keys(tests); +all_start = new Date(); +test_count = 0; + +run_next_test = function run_next_test() { + var test_name = all_tests.shift(); + if (typeof tests[test_name] === "function") { + util.print('- \x1b[1m' + test_name.toLowerCase() + '\x1b[0m:'); + cur_start = new Date(); + test_count += 1; + tests[test_name](); + } else { + console.log('\n completed \x1b[32m%d\x1b[0m tests in \x1b[33m%d\x1b[0m ms\n', test_count, new Date() - all_start); + client.quit(); + client2.quit(); + } +}; + +client.once("ready", function start_tests() { + console.log("Connected to " + client.host + ":" + client.port + ", Redis server version " + client.server_info.redis_version + "\n"); + console.log("Using reply parser " + client.reply_parser.name); + + run_next_test(); + + connected = true; +}); + +client.on('end', function () { + ended = true; +}); + +declare var process; +// Exit immediately on connection failure, which triggers "exit", below, which fails the test +client.on("error", function (err) { + console.error("client: " + err.stack); + process.exit(); +}); +client2.on("error", function (err) { + console.error("client2: " + err.stack); + process.exit(); +}); +client3.on("error", function (err) { + console.error("client3: " + err.stack); + process.exit(); +}); +client.on("reconnecting", function (params) { + console.log("reconnecting: " + util.inspect(params)); +}); + +process.on('uncaughtException', function (err) { + console.error("Uncaught exception: " + err.stack); + process.exit(1); +}); + +process.on('exit', function (code) { + assert.equal(true, connected); + assert.equal(true, ended); +}); From 8e9876c6a39c10fee76b8b3689743d98a31d96ea Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Wed, 24 Oct 2012 19:02:31 +0300 Subject: [PATCH 005/107] Add some jQuery tests --- Tests/jquery-tests.ts | 468 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 468 insertions(+) create mode 100644 Tests/jquery-tests.ts diff --git a/Tests/jquery-tests.ts b/Tests/jquery-tests.ts new file mode 100644 index 000000000..9e3ecf064 --- /dev/null +++ b/Tests/jquery-tests.ts @@ -0,0 +1,468 @@ +/// + +function test_add() { + $("p").add("div").addClass("widget"); + var pdiv = $("p").add("div"); + + $('li').add('p').css('background-color', 'red'); + $('li').add(document.getElementsByTagName('p')[0]) + .css('background-color', 'red'); + $('li').add('

new paragraph

') + .css('background-color', 'red'); + $("div").css("border", "2px solid red") + .add("p") + .css("background", "yellow"); + $("p").add("span").css("background", "yellow"); + $("p").clone().add("Again").appendTo(document.body); + $("p").add(document.getElementById("a")).css("background", "yellow"); + var collection = $("p"); + + collection = collection.add(document.getElementById("a")); + collection.css("background", "yellow"); +} + +function test_addClass() { + $("p").addClass("myClass yourClass"); + $("p").removeClass("myClass noClass").addClass("yourClass"); + $("ul li:last").addClass(function (index) { + return "item-" + index; + }); + $("p:last").addClass("selected"); + $("p:last").addClass("selected highlight"); + $("div").addClass(function (index, currentClass) { + var addedClass; + if (currentClass === "red") { + addedClass = "green"; + $("p").text("There is one green div"); + } + return addedClass; + }); +} + +function test_after() { + $('.inner').after('

Test

'); + $('
').after('

'); + $('
').after('

').addClass('foo') + .filter('p').attr('id', 'bar').html('hello') + .end() + .appendTo('body'); + $('p').after(function () { + return '
' + this.className + '
'; + }); + var $newdiv1 = $('
'), + newdiv2 = document.createElement('div'), + existingdiv1 = document.getElementById('foo'); + $('p').first().after($newdiv1, [newdiv2, existingdiv1]); + $("p").after(document.createTextNode("Hello")); + $("p").after($("b")); +} + +function test_ajax() { + $.ajax({ + url: "test.html", + context: document.body + }).done(function () { + $(this).addClass("done"); + }); + $.ajax({ + statusCode: { + 404: function () { + alert("page not found"); + } + } + }); + $.ajax({ + url: "http://fiddle.jshell.net/favicon.png", + beforeSend: function (xhr) { + xhr.overrideMimeType("text/plain; charset=x-user-defined"); + } + }).done(function (data) { + if (console && console.log) { + console.log("Sample of data:", data.slice(0, 100)); + } + }); + $.ajax({ + url: 'ajax/test.html', + success: function (data) { + $('.result').html(data); + alert('Load was performed.'); + } + }); + var _super = jQuery.ajaxSettings.xhr; + jQuery.ajaxSettings.xhr = function () { + var xhr = _super(), + getAllResponseHeaders = xhr.getAllResponseHeaders; + + xhr.getAllResponseHeaders = function () { + if (getAllResponseHeaders()) { + return getAllResponseHeaders(); + } + var allHeaders = ""; + $(["Cache-Control", "Content-Language", "Content-Type", + "Expires", "Last-Modified", "Pragma"]).each(function (i, header_name) { + + if (xhr.getResponseHeader(header_name)) { + allHeaders += header_name + ": " + xhr.getResponseHeader(header_name) + "\n"; + } + return allHeaders; + }); + }; + return xhr; + }; + $.ajax({ + type: "POST", + url: "some.php", + data: { name: "John", location: "Boston" } + }).done(function (msg) { + alert("Data Saved: " + msg); + }); + $.ajax({ + url: "test.html", + cache: false + }).done(function (html) { + $("#results").append(html); + }); + var xmlDocument = []; + var xmlRequest = $.ajax({ + url: "page.php", + processData: false, + data: xmlDocument + }); + var handleResponse; + xmlRequest.done(handleResponse); + + var menuId = $("ul.nav").first().attr("id"); + var request = $.ajax({ + url: "script.php", + type: "POST", + data: { id: menuId }, + dataType: "html" + }); + request.done(function (msg) { + $("#log").html(msg); + }); + request.fail(function (jqXHR, textStatus) { + alert("Request failed: " + textStatus); + }); + + $.ajax({ + type: "GET", + url: "test.js", + dataType: "script" + }); +} + +function test_ajaxComplete() { + $('.log').ajaxComplete(function () { + $(this).text('Triggered ajaxComplete handler.'); + }); + $('.trigger').click(function () { + $('.result').load('ajax/test.html'); + }); + $('.log').ajaxComplete(function (e, xhr, settings) { + if (settings.url == 'ajax/test.html') { + $(this).text('Triggered ajaxComplete handler. The result is ' + xhr.responseHTML); + } + }); + $("#msg").ajaxComplete(function (event, request, settings) { + $(this).append("
  • Request Complete.
  • "); + }); +} + +function test_ajaxError() { + $("div.log").ajaxError(function () { + $(this).text("Triggered ajaxError handler."); + }); + $("button.trigger").click(function () { + $("div.result").load("ajax/missing.html"); + }); + $("div.log").ajaxError(function (e, jqxhr, settings, exception) { + if (settings.url == "ajax/missing.html") { + $(this).text("Triggered ajaxError handler."); + } + }); + $("#msg").ajaxError(function (event, request, settings) { + $(this).append("
  • Error requesting page " + settings.url + "
  • "); + }); +} + +function test_ajaxPrefilter() { + var currentRequests = {}; + $.ajaxPrefilter(function (options, originalOptions, jqXHR) { + if (options.abortOnRetry) { + if (currentRequests[options.url]) { + currentRequests[options.url].abort(); + } + currentRequests[options.url] = jqXHR; + } + }); + $.ajaxPrefilter(function (options) { + if (options.crossDomain) { + options.url = "http://mydomain.net/proxy/" + encodeURIComponent(options.url); + options.crossDomain = false; + } + }); + $.ajaxPrefilter("json script", function (options, originalOptions, jqXHR) { + + }); + var isActuallyScript; + $.ajaxPrefilter(function (options) { + if (isActuallyScript(options.url)) { + return "script"; + } + }); +} + +function test_ajaxSend() { + $('.log').ajaxSend(function () { + $(this).text('Triggered ajaxSend handler.'); + }); + $('.trigger').click(function () { + $('.result').load('ajax/test.html'); + }); + $('.log').ajaxSend(function (e, jqxhr, settings) { + if (settings.url == 'ajax/test.html') { + $(this).text('Triggered ajaxSend handler.'); + } + }); + $("#msg").ajaxSend(function (evt, request, settings) { + $(this).append("
  • Starting request at " + settings.url + "
  • "); + }); +} + +function test_ajaxSetup() { + $.ajaxSetup({ + url: 'ping.php' + }); + $.ajax({ + data: { 'name': 'Dan' } + }); + $.ajaxSetup({ + url: "/xmlhttp/", + global: false, + type: "POST" + }); +} + +function test_ajaxStart() { + $('.log').ajaxStart(function () { + $(this).text('Triggered ajaxStart handler.'); + }); + $('.trigger').click(function () { + $('.result').load('ajax/test.html'); + }); + $("#loading").ajaxStart(function () { + $(this).show(); + }); +} + +function test_ajaxStop() { + $('.log').ajaxStop(function () { + $(this).text('Triggered ajaxStop handler.'); + }); + $('.trigger').click(function () { + $('.result').load('ajax/test.html'); + }); + $("#loading").ajaxStop(function () { + $(this).hide(); + }); +} + +function test_ajaxSuccess() { + $('.log').ajaxSuccess(function () { + $(this).text('Triggered ajaxSuccess handler.'); + }); + $('.trigger').click(function () { + $('.result').load('ajax/test.html'); + }); + $('.log').ajaxSuccess(function (e, xhr, settings) { + if (settings.url == 'ajax/test.html') { + $(this).text('Triggered ajaxSuccess handler. The ajax response was:' + xhr.responseText); + } + }); + $("#msg").ajaxSuccess(function (evt, request, settings) { + $(this).append("
  • Successful Request!
  • "); + }); +} + +function test_allSelector() { + var elementCount = $("*").css("border", "3px solid red").length; + $("body").prepend("

    " + elementCount + " elements found

    "); + var elementCount2 = $("#test").find("*").css("border", "3px solid red").length; + $("body").prepend("

    " + elementCount2 + " elements found

    "); +} + +function test_andSelf() { + $('li.third-item').nextAll().andSelf() + .css('background-color', 'red'); + $("div").find("p").andSelf().addClass("border"); + $("div").find("p").addClass("background"); +} + +function test_animate() { + $('#clickme').click(function () { + $('#book').animate({ + opacity: 0.25, + left: '+=50', + height: 'toggle' + }, 5000, function () { + }); + }); + $('li').animate({ + opacity: .5, + height: '50%' + }, { + step: function (now, fx) { + var data = fx.elem.id + ' ' + fx.prop + ': ' + now; + $('body').append('
    ' + data + '
    '); + } + }); + $('#clickme').click(function () { + $('#book').animate({ + width: ['toggle', 'swing'], + height: ['toggle', 'swing'], + opacity: 'toggle' + }, 5000, 'linear', function () { + $(this).after('
    Animation complete.
    '); + }); + }); + $('#clickme').click(function () { + $('#book').animate({ + width: 'toggle', + height: 'toggle' + }, { + duration: 5000, + specialEasing: { + width: 'linear', + height: 'easeOutBounce' + }, + complete: function () { + $(this).after('
    Animation complete.
    '); + } + }); + }); + $("#go").click(function () { + $("#block").animate({ + width: "70%", + opacity: 0.4, + marginLeft: "0.6in", + fontSize: "3em", + borderWidth: "10px" + }, 1500); + }); + $("#right").click(function () { + $(".block").animate({ "left": "+=50px" }, "slow"); + }); + $("#left").click(function () { + $(".block").animate({ "left": "-=50px" }, "slow"); + }); + $("#go1").click(function () { + $("#block1").animate({ width: "90%" }, { queue: false, duration: 3000 }) + .animate({ fontSize: "24px" }, 1500) + .animate({ borderRightWidth: "15px" }, 1500); + }); + $("#go2").click(function () { + $("#block2").animate({ width: "90%" }, 1000) + .animate({ fontSize: "24px" }, 1000) + .animate({ borderLeftWidth: "15px" }, 1000); + }); + $("#go3").click(function () { + $("#go1").add("#go2").click(); + }); + $("#go4").click(function () { + $("div").css({ width: "", fontSize: "", borderWidth: "" }); + }); + $("#go").click(function () { + $(".block:first").animate({ + left: 100 + }, { + duration: 1000, + step: function (now, fx) { + $(".block:gt(0)").css("left", now); + } + }); + }); + $("p").animate({ + height: "toggle", opacity: "toggle" + }, "slow"); + $("p").animate({ + left: 50, opacity: 1 + }, 500); + $("p").animate({ + left: "50px", opacity: 1 + }, { duration: 500, queue: false }); + $("p").animate({ + opacity: "show" + }, "slow", "easein"); + $("p").animate({ + height: "toggle", opacity: "toggle" + }, { duration: "slow" }); + $("p").animate({ + opacity: "show" + }, { duration: "slow", easing: "easein" }); + $("p").animate({ + height: 200, width: 400, opacity: 0.5 + }, 1000, "linear", function () { + alert("all done"); + }); +} + +function test_animatedSelector() { + $("#run").click(function () { + $("div:animated").toggleClass("colored"); + }); + function animateIt() { + $("#mover").slideToggle("slow", animateIt); + } + animateIt(); +} + +function test_append() { + $('.inner').append('

    Test

    '); + $('.container').append($('h2')); + + var $newdiv1 = $('
    '), + newdiv2 = document.createElement('div'), + existingdiv1 = document.getElementById('foo'); + + $('body').append($newdiv1, [newdiv2, existingdiv1]); +} + +function test_appendTo() { + $('

    Test

    ').appendTo('.inner'); + $('h2').appendTo($('.container')); +} + +function test_attr() { + var title = $("em").attr("title"); + $("div").text(title); + $('#greatphoto').attr('alt', 'Beijing Brush Seller'); + $('#greatphoto') + .attr('title', 'Photo by Kelly Clark'); + $('#greatphoto').attr({ + alt: 'Beijing Brush Seller', + title: 'photo by Kelly Clark' + }); + $('#greatphoto').attr('title', function (i, val) { + return val + ' - photo by Kelly Clark' + }); + $("div").attr("id", function (arr) { + return "div-id" + arr; + }) + .each(function () { + $("span", this).html("(ID = '" + this.id + "')"); + }); + $("img").attr("src", function () { + return "/images/" + this.title; + }); +} + +function test_attributeSelectors() { + $('a[hreflang|="en"]').css('border', '3px dotted green'); + $('input[name*="man"]').val('has man in it!'); + $('input[name~="man"]').val('mr. man is in it!'); + $('input[name$="letter"]').val('a letter'); + $('input[value="Hot Fuzz"]').next().text(" Hot Fuzz"); + $('input[name!="newsletter"]').next().append('; not newsletter'); + $('input[name^="news"]').val('news here!'); +} \ No newline at end of file From 34a07ba7a64d4a51426be109728dadd9f9af816c Mon Sep 17 00:00:00 2001 From: Diego Vilar Date: Wed, 24 Oct 2012 20:29:17 -0300 Subject: [PATCH 006/107] Definitions for AngularJS 1.0.2 modules ng, AUTO, ngCookies, ngMock, ngMockE2E, ngResource and ngSanitize --- Definitions/angular-1.0.2.d.ts | 637 ++++++++++++++++++++++++ Definitions/angular-cookies-1.0.2.d.ts | 29 ++ Definitions/angular-mocks-1.0.2.d.ts | 153 ++++++ Definitions/angular-resource-1.0.2.d.ts | 65 +++ Definitions/angular-sanitize-1.0.2.d.ts | 21 + 5 files changed, 905 insertions(+) create mode 100644 Definitions/angular-1.0.2.d.ts create mode 100644 Definitions/angular-cookies-1.0.2.d.ts create mode 100644 Definitions/angular-mocks-1.0.2.d.ts create mode 100644 Definitions/angular-resource-1.0.2.d.ts create mode 100644 Definitions/angular-sanitize-1.0.2.d.ts diff --git a/Definitions/angular-1.0.2.d.ts b/Definitions/angular-1.0.2.d.ts new file mode 100644 index 000000000..db76ea472 --- /dev/null +++ b/Definitions/angular-1.0.2.d.ts @@ -0,0 +1,637 @@ +// Type definitions for Angular JS 1.0.2 +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare var angular: ng.AngularStatic; + +/////////////////////////////////////////////////////////////////////////////// +// ng module (angular.js) +/////////////////////////////////////////////////////////////////////////////// +module ng { + + // For the sake of simplicity, let's assume jQuery is always preferred + interface JQLiteOrBetter extends JQuery { } + + // All service providers extend this interface + export interface ServiceProvider { + $get(): any; + } + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // see http://docs.angularjs.org/api + /////////////////////////////////////////////////////////////////////////// + export interface AngularStatic { + bind(context: any, fn: Function, ...args: any[]): Function; + bootstrap(element: Element, modules?: any[]): auto.InjectorService; + copy(source: any, destination?: any): any; + element: JQLiteOrBetter; + equals(value1: any, value2: any): bool; + extend(destination: any, ...sources: any[]): any; + forEach(obj: any, iterator: (value, key) => any, context?: any): any; + fromJson(json: string): any; + identity(arg?: any): any; + injector(modules?: any[]): auto.InjectorService; + isArray(value: any): bool; + isDate(value: any): bool; + isDefined(value: any): bool; + isElement(value: any): bool; + isFunction(value: any): bool; + isNumber(value: any): bool; + isObject(value: any): bool; + isString(value: any): bool; + isUndefined(value: any): bool; + lowercase(str: string): string; + module(name: string, requires?: string[], configFunction?: Function): Module; + noop(...args: any[]): void; + toJson(obj: any, pretty?: bool): string; + uppercase(str: string): string; + version: { + full: string; + major: number; + minor: number; + dot: number; + codename: string; + }; + } + + /////////////////////////////////////////////////////////////////////////// + // Module + // see http://docs.angularjs.org/api/angular.Module + /////////////////////////////////////////////////////////////////////////// + export interface Module { + config(configFn: Function): Module; + constant(name: string, value: any): Module; + controller(name: string, controllerConstructor: Function): Module; + controller(name: string, inlineAnnotadedConstructor: any[]): Module; + directive(name: string, directiveFactory: Function): Module; + factory(name: string, serviceFactoryFunction: Function): Module; + filter(name: string, filterFactoryFunction: Function): Module; + provider(name: string, serviceProviderConstructor: Function): Module; + run(initializationFunction: Function): Module; + service(name: string, serviceConstructor: Function): Module; + value(name: string, value: any): Module; + + // Properties + name: string; + requires: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // Attributes + // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes + /////////////////////////////////////////////////////////////////////////// + export interface Attributes { + $set(name: string, value: any): void; + $attr: any; + } + + /////////////////////////////////////////////////////////////////////////// + // FormController + // see http://docs.angularjs.org/api/ng.directive:form.FormController + /////////////////////////////////////////////////////////////////////////// + export interface FormController { + $pristine: bool; + $dirty: bool; + $valid: bool; + $invalid: bool; + $error: any; + } + + /////////////////////////////////////////////////////////////////////////// + // NgModelController + // see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController + /////////////////////////////////////////////////////////////////////////// + export interface NgModelController { + $render(): void; + $setValidity(validationErrorKey: string, isValid: bool): void; + $setViewValue(value: string): void; + + // XXX Not sure about the types here. Documentation states it's a string, but + // I've seen it receiving other types throughout the code. + // Falling back to any for now. + $viewValue: any; + + // XXX Same as avove + $modelValue: any; + + $parsers: ModelParser[]; + $formatters: ModelFormatter[]; + $error: any; + $pristine: bool; + $dirty: bool; + $valid: bool; + $invalid: bool; + } + + export interface ModelParser { + (value: any): any; + } + + export interface ModelFormatter { + (value: any): any; + } + + /////////////////////////////////////////////////////////////////////////// + // Scope + // see http://docs.angularjs.org/api/ng.$rootScope.Scope + /////////////////////////////////////////////////////////////////////////// + export interface Scope { + // Documentation says exp is optional, but actual implementaton counts on it + $apply(exp: string): any; + $apply(exp: (scope: Scope) => any): any; + + $broadcast(name: string, ...args: any[]): AngularEvent; + $destroy(): void; + $digest(): void; + $emit(name: string, ...args: any[]): AngularEvent; + + // Documentation says exp is optional, but actual implementaton counts on it + $eval(expression: string): any; + $eval(expression: (scope: Scope) => any): any; + + // Documentation says exp is optional, but actual implementaton counts on it + $evalAsync(expression: string): void; + $evalAsync(expression: (scope: Scope) => any): void; + + // Defaults to false by the implementation checking strategy + $new(isolate?: bool): Scope; + + $on(name: string, listener: (event: AngularEvent, ...args: any[]) => any): Function; + + $watch(watchExpression: string, listener?: string, objectEquality?: bool): Function; + $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: Scope) => any, objectEquality?: bool): Function; + $watch(watchExpression: (scope: Scope) => any, listener?: string, objectEquality?: bool): Function; + $watch(watchExpression: (scope: Scope) => any, listener?: (newValue: any, oldValue: any, scope: Scope) => any, objectEquality?: bool): Function; + + $id: number; + } + + export interface AngularEvent { + targetScope: Scope; + currentScope: Scope; + name: string; + preventDefault: Function; + defaultPrevented: bool; + + // Available only events that were $emit-ted + stopPropagation?: Function; + } + + /////////////////////////////////////////////////////////////////////////// + // WindowService + // see http://docs.angularjs.org/api/ng.$window + /////////////////////////////////////////////////////////////////////////// + export interface WindowService extends Window {} + + /////////////////////////////////////////////////////////////////////////// + // BrowserService + // TODO undocumented, so we need to get it from the source code + /////////////////////////////////////////////////////////////////////////// + export interface BrowserService {} + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ng.$timeout + /////////////////////////////////////////////////////////////////////////// + export interface TimeoutService { + (func: Function, delay?: number, invokeApply?: bool): Promise; + cancel(promise: Promise): bool; + } + + /////////////////////////////////////////////////////////////////////////// + // FilterService + // see http://docs.angularjs.org/api/ng.$filter + // see http://docs.angularjs.org/api/ng.$filterProvider + /////////////////////////////////////////////////////////////////////////// + export interface FilterService { + (name: string): Function; + } + + export interface FilterProvider extends ServiceProvider { + register(name: string, filterFactory: Function): ServiceProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // LocaleService + // see http://docs.angularjs.org/api/ng.$locale + /////////////////////////////////////////////////////////////////////////// + export interface LocaleService { + id: string; + + // These are not documented + // Check angular's i18n files for exemples + NUMBER_FORMATS: LocaleNumberFormatDescriptor; + DATETIME_FORMATS: any; + pluralCat: (num: any) => string; + } + + export interface LocaleNumberFormatDescriptor { + DECIMAL_SEP: string; + GROUP_SEP: string; + PATTERNS: LocaleNumberPatternDescriptor[]; + CURRENCY_SYM: string; + } + + export interface LocaleNumberPatternDescriptor { + minInt: number; + minFrac: number; + maxFrac: number; + posPre: string; + posSuf: string; + negPre: string; + negSuf: string; + gSize: number; + lgSize: number; + } + + export interface LacaleDateTimeFormatDescriptor { + MONTH: string[]; + SHORTMONTH: string[]; + DAY: string[]; + SHORTDAY: string[]; + AMPMS: string[]; + medium: string; + short: string; + fullDate: string; + longDate: string; + mediumDate: string; + shortDate: string; + mediumTime: string; + shortTime: string; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ng.$log + /////////////////////////////////////////////////////////////////////////// + export interface LogService { + error: LogCall; + info: LogCall; + log: LogCall; + warn: LogCall; + } + + // We define this as separete interface so we can reopen it later for + // the ngMock module. + interface LogCall { + (...args: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // ParseService + // see http://docs.angularjs.org/api/ng.$parse + /////////////////////////////////////////////////////////////////////////// + export interface ParseService { + (expression: string): CompiledExpression; + } + + export interface CompiledExpression { + (context: any, locals?: any): any; + + // If value is not provided, undefined is gonna be used since the implementation + // does not check the parameter. Let's force a value for consistency. If consumer + // whants to undefine it, pass the undefined value explicitly. + assign(context: any, value: any): any; + } + + /////////////////////////////////////////////////////////////////////////// + // LocationService + // see http://docs.angularjs.org/api/ng.$location + // see http://docs.angularjs.org/api/ng.$locationProvider + // see http://docs.angularjs.org/guide/dev_guide.services.$location + /////////////////////////////////////////////////////////////////////////// + export interface LocationService { + absUrl(): string; + hash(): string; + hash(newHash: string): LocationService; + host(): string; + path(): string; + path(newPath: string): LocationService; + port(): number; + protocol(): string; + replace(): LocationService; + search(): string; + search(parametersMap: any): LocationService; + search(parameter: string, parameterValue: any): LocationService; + url(): string; + url(url: string): LocationService; + } + + export interface LocationProvider extends ServiceProvider { + hashPrefix(): string; + hashPrefix(prefix: string): LocationProvider; + html5Mode(): bool; + + // Documentation states that parameter is string, but + // implementation tests it as boolean, which makes more sense + // since this is a toggler + html5Mode(active: bool): LocationProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // DocumentService + // see http://docs.angularjs.org/api/ng.$document + /////////////////////////////////////////////////////////////////////////// + export interface DocumentService extends Document {} + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ng.$exceptionHandler + /////////////////////////////////////////////////////////////////////////// + export interface ExceptionHandlerService { + (exception: Error, cause?: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // RootElementService + // see http://docs.angularjs.org/api/ng.$rootElement + /////////////////////////////////////////////////////////////////////////// + export interface RootElementService extends JQLiteOrBetter {} + + /////////////////////////////////////////////////////////////////////////// + // QService + // see http://docs.angularjs.org/api/ng.$q + /////////////////////////////////////////////////////////////////////////// + export interface QService { + all(promises: Promise[]): Promise; + defer(): Deferred; + reject(reason?: any): Promise; + when(value: any): Promise; + } + + export interface Promise { + then(successCallback: Function, errorCallback?: Function): Promise; + } + + export interface Deferred { + resolve(value?: any): void; + reject(reason?: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // AnchorScrollService + // see http://docs.angularjs.org/api/ng.$anchorScroll + /////////////////////////////////////////////////////////////////////////// + export interface AnchorScrollService { + (): void; + } + + export interface AnchorScrollProvider extends ServiceProvider { + disableAutoScrolling(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CacheFactoryService + // see http://docs.angularjs.org/api/ng.$cacheFactory + /////////////////////////////////////////////////////////////////////////// + export interface CacheFactoryService { + // Lets not foce the optionsMap to have the capacity member. Even though + // it's the ONLY option considered by the implementation today, a consumer + // might find it useful to associate some other options to the cache object. + //(cacheId: string, optionsMap?: { capacity: number; }): CacheObject; + (cacheId: string, optionsMap?: { capacity: number; }): CacheObject; + + // Methods bellow are not documented + info(): any; + get(cacheId: string): CacheObject; + } + + export interface CacheObject { + info(): { + id: string; + size: number; + + // Not garanteed to have, since it's a non-mandatory option + //capacity: number; + }; + put(key: string, value?: any): void; + get(key: string): any; + remove(key: string): void; + removeAll(): void; + destroy(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CompileService + // see http://docs.angularjs.org/api/ng.$compile + // see http://docs.angularjs.org/api/ng.$compileProvider + /////////////////////////////////////////////////////////////////////////// + export interface CompileService { + (element: string, transclude?: TemplateLinkingFunction, maxPriority?: number): TemplateLinkingFunction; + (element: Element, transclude?: TemplateLinkingFunction, maxPriority?: number): TemplateLinkingFunction; + (element: JQLiteOrBetter, transclude?: TemplateLinkingFunction, maxPriority?: number): TemplateLinkingFunction; + } + + export interface CompileProvider extends ServiceProvider { + directive(name: string, directiveFactory: Function): CompileProvider; + + // Undocumented, but it is there... + directive(directivesMap: any): CompileProvider; + } + + export interface TemplateLinkingFunction { + // Let's hint but not force cloneAttachFn's signature + (scope: Scope, cloneAttachFn?: (clonedElement?: JQLiteOrBetter, scope?: Scope) => any): JQLiteOrBetter; + } + + /////////////////////////////////////////////////////////////////////////// + // ControllerService + // see http://docs.angularjs.org/api/ng.$controller + // see http://docs.angularjs.org/api/ng.$controllerProvider + /////////////////////////////////////////////////////////////////////////// + export interface ControllerService { + // Although the documentation doesn't state this, locals are optional + (controllerConstructor: Function, locals?: any): any; + (controllerName: string, locals?: any): any; + } + + export interface ControlerPovider extends ServiceProvider { + register(name: string, controllerConstructor: Function): void; + register(name: string, dependencyAnnotadedConstructor: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpService + // see http://docs.angularjs.org/api/ng.$http + /////////////////////////////////////////////////////////////////////////// + export interface HttpService { + // At least moethod and url must be provided... + (config: RequestConfig): HttpPromise; + get(url: string, RequestConfig?: any): HttpPromise; + delete(url: string, RequestConfig?: any): HttpPromise; + head(url: string, RequestConfig?: any): HttpPromise; + jsonp(url: string, RequestConfig?: any): HttpPromise; + post(url: string, data: any, RequestConfig?: any): HttpPromise; + put(url: string, data: any, RequestConfig?: any): HttpPromise; + defaults: RequestConfig; + + // For debugging, BUT it is documented as public, so... + pendingRequests: any[]; + } + + // This is just for hinting. + // Some opetions might not be available depending on the request. + // see http://docs.angularjs.org/api/ng.$http#Usage for options explanations + export interface RequestConfig { + method: string; + url: string; + params?: any; + + // XXX it has it's own structure... perhaps we should define it in the future + headers?: any; + + cache?: any; + timeout?: number; + withCredentials?: bool; + + // These accept multiple types, so let's defile them as any + data?: any; + transformRequest?: any; + transformResponse?: any; + } + + export interface HttpPromise extends Promise { + success(callback: (response: DestructuredResponse) => any): HttpPromise; + error(callback: (response: DestructuredResponse) => any): HttpPromise; + } + + export interface DestructuredResponse { + data: any; + status: number; + headers: (headerName: string) => string; + config: RequestConfig; + } + + export interface HttpProvider extends ServiceProvider { + defaults: RequestConfig; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ng.$httpBackend + // You should never need to use this service directly. + /////////////////////////////////////////////////////////////////////////// + export interface HttpBackendService { + // XXX Perhaps define callback signature in the future + (method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: bool); void; + } + + /////////////////////////////////////////////////////////////////////////// + // InterpolateService + // see http://docs.angularjs.org/api/ng.$interpolate + // see http://docs.angularjs.org/api/ng.$interpolateProvider + /////////////////////////////////////////////////////////////////////////// + export interface InterpolateService { + (text: string, mustHaveExpression?: bool): InterpolationFunction; + endSymbol(): string; + startSymbol(): string; + } + + export interface InterpolationFunction { + (context: any): string; + } + + export interface InterpolateProvider extends ServiceProvider { + startSymbol(): string; + startSymbol(value: string): InterpolateProvider; + endSymbol(): string; + endSymbol(value: string): InterpolateProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // RouteParamsService + // see http://docs.angularjs.org/api/ng.$routeParams + /////////////////////////////////////////////////////////////////////////// + export interface RouteParamsService {} + + /////////////////////////////////////////////////////////////////////////// + // TemplateCacheService + // see http://docs.angularjs.org/api/ng.$templateCache + /////////////////////////////////////////////////////////////////////////// + export interface TemplateCacheService extends CacheObject {} + + /////////////////////////////////////////////////////////////////////////// + // RootScopeService + // see http://docs.angularjs.org/api/ng.$rootScope + /////////////////////////////////////////////////////////////////////////// + export interface RootScopeService extends Scope {} + + /////////////////////////////////////////////////////////////////////////// + // RouteService + // see http://docs.angularjs.org/api/ng.$route + // see http://docs.angularjs.org/api/ng.$routeProvider + /////////////////////////////////////////////////////////////////////////// + export interface RouteService { + reload(): void; + routes: any; + + // May not always be available. For instance, current will not be available + // to a controller that was not initialized as a result of a route maching. + current?: CurrentRoute; + } + + // see http://docs.angularjs.org/api/ng.$routeProvider#when for options explanations + export interface Route { + controller?: any; + template?: string; + templateUrl?: string; + resolve?: any; + redirectTo?: any; + reloadOnSearch?: bool; + } + + // see http://docs.angularjs.org/api/ng.$route#current + export interface CurrentRoute extends Route { + locals: { + $scope: Scope; + $template: string; + }; + } + + export interface RouteProviderProvider extends ServiceProvider { + otherwise(params: any): RouteProviderProvider; + when(path: string, route: Route): RouteProviderProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // AUTO module (angular.js) + /////////////////////////////////////////////////////////////////////////// + module auto { + + /////////////////////////////////////////////////////////////////////// + // InjectorService + // see http://docs.angularjs.org/api/AUTO.$injector + /////////////////////////////////////////////////////////////////////// + export interface InjectorService { + annotate(fn: Function): string[]; + annotate(inlineAnnotadedFunction: any[]): string[]; + get(name: string): any; + instantiate(typeConstructor: Function, locals?: any): any; + invoke(func: Function, context?: any, locals?: any): any; + } + + /////////////////////////////////////////////////////////////////////// + // ProvideService + // see http://docs.angularjs.org/api/AUTO.$provide + /////////////////////////////////////////////////////////////////////// + export interface ProvideService { + // Documentation says it returns the registered instance, but actual + // implementation does not return anything. + // constant(name: string, value: any): any; + constant(name: string, value: any): void; + + decorator(name: string, decorator: Function): void; + factory(name: string, serviceFactoryFunction: Function): ng.ServiceProvider; + provider(name: string, provider: ng.ServiceProvider): ng.ServiceProvider; + provider(name: string, serviceProviderConstructor: Function): ng.ServiceProvider; + service(name: string, constructor: Function): ng.ServiceProvider; + value(name: string, value: any): ng.ServiceProvider; + } + + } + +} diff --git a/Definitions/angular-cookies-1.0.2.d.ts b/Definitions/angular-cookies-1.0.2.d.ts new file mode 100644 index 000000000..876ae5f2e --- /dev/null +++ b/Definitions/angular-cookies-1.0.2.d.ts @@ -0,0 +1,29 @@ +// Type definitions for Angular JS 1.0.2 (ngCookies module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/////////////////////////////////////////////////////////////////////////////// +// ngCookies module (angular-cookies.js) +/////////////////////////////////////////////////////////////////////////////// +module ng.cookies { + + /////////////////////////////////////////////////////////////////////////// + // CookieService + // see http://docs.angularjs.org/api/ngCookies.$cookies + /////////////////////////////////////////////////////////////////////////// + export interface CookiesService {} + + /////////////////////////////////////////////////////////////////////////// + // CookieStoreService + // see http://docs.angularjs.org/api/ngCookies.$cookieStore + /////////////////////////////////////////////////////////////////////////// + export interface CookieStoreService { + get(key: string): any; + put(key: string, value: any): void; + remove(key: string): void; + } + +} diff --git a/Definitions/angular-mocks-1.0.2.d.ts b/Definitions/angular-mocks-1.0.2.d.ts new file mode 100644 index 000000000..cbadc152b --- /dev/null +++ b/Definitions/angular-mocks-1.0.2.d.ts @@ -0,0 +1,153 @@ +// Type definitions for Angular JS 1.0.2 (ngMock, ngMockE2E module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/////////////////////////////////////////////////////////////////////////////// +// ngMock module (angular-mocks.js) +/////////////////////////////////////////////////////////////////////////////// +module ng { + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // We reopen it to add the MockStatic definition + /////////////////////////////////////////////////////////////////////////// + export interface AngularStatic { + mock: MockStatic; + } + + interface MockStatic { + // see http://docs.angularjs.org/api/angular.mock.debug + debug(obj: any): string; + + // see http://docs.angularjs.org/api/angular.mock.inject + inject(...fns: Function[]): void; + + // see http://docs.angularjs.org/api/angular.mock.module + module(...modules: any[]): any; + + // see http://docs.angularjs.org/api/angular.mock.TzDate + TzDate(offset: number, timestamp: number): Date; + TzDate(offset: number, timestamp: string): Date; + } + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ngMock.$exceptionHandler + // see http://docs.angularjs.org/api/ngMock.$exceptionHandlerProvider + /////////////////////////////////////////////////////////////////////////// + export interface ExceptionHandlerProvider extends ServiceProvider { + mode(mode: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ngMock.$timeout + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + export interface TimeoutService { + flush(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ngMock.$log + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + export interface LogService { + assertEmpty(): void; + reset(): void; + } + + interface LogCall { + logs: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ngMock.$httpBackend + /////////////////////////////////////////////////////////////////////////// + export interface HttpBackendService { + flush(count: number): void; + resetExpectations(): void; + verifyNoOutstandingExpectation(): void; + verifyNoOutstandingRequest(): void; + + expect(method: string, url: string, data?: string, headers?: any): mock.RequestHandler; + expect(method: string, url: RegExp, data?: string, headers?: any): mock.RequestHandler; + expect(method: string, url: string, data?: RegExp, headers?: any): mock.RequestHandler; + expect(method: string, url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + expect(method: RegExp, url: string, data?: string, headers?: any): mock.RequestHandler; + expect(method: RegExp, url: RegExp, data?: string, headers?: any): mock.RequestHandler; + expect(method: RegExp, url: string, data?: RegExp, headers?: any): mock.RequestHandler; + expect(method: RegExp, url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + + when(method: string, url: string, data?: string, headers?: any): mock.RequestHandler; + when(method: string, url: RegExp, data?: string, headers?: any): mock.RequestHandler; + when(method: string, url: string, data?: RegExp, headers?: any): mock.RequestHandler; + when(method: string, url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + when(method: RegExp, url: string, data?: string, headers?: any): mock.RequestHandler; + when(method: RegExp, url: RegExp, data?: string, headers?: any): mock.RequestHandler; + when(method: RegExp, url: string, data?: RegExp, headers?: any): mock.RequestHandler; + when(method: RegExp, url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + + expectDELETE(url: string, headers?: any): mock.RequestHandler; + expectDELETE(url: RegExp, headers?: any): mock.RequestHandler; + expectGET(url: string, headers?: any): mock.RequestHandler; + expectGET(url: RegExp, headers?: any): mock.RequestHandler; + expectHEAD(url: string, headers?: any): mock.RequestHandler; + expectHEAD(url: RegExp, headers?: any): mock.RequestHandler; + expectJSONP(url: string): mock.RequestHandler; + expectJSONP(url: RegExp): mock.RequestHandler; + expectPATCH(url: string, data?: string, headers?: any): mock.RequestHandler; + expectPATCH(url: RegExp, data?: string, headers?: any): mock.RequestHandler; + expectPATCH(url: string, data?: RegExp, headers?: any): mock.RequestHandler; + expectPATCH(url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + expectPOST(url: string, data?: string, headers?: any): mock.RequestHandler; + expectPOST(url: RegExp, data?: string, headers?: any): mock.RequestHandler; + expectPOST(url: string, data?: RegExp, headers?: any): mock.RequestHandler; + expectPOST(url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + expectPUT(url: string, data?: string, headers?: any): mock.RequestHandler; + expectPUT(url: RegExp, data?: string, headers?: any): mock.RequestHandler; + expectPUT(url: string, data?: RegExp, headers?: any): mock.RequestHandler; + expectPUT(url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + + whenDELETE(url: string, headers?: any): mock.RequestHandler; + whenDELETE(url: RegExp, headers?: any): mock.RequestHandler; + whenGET(url: string, headers?: any): mock.RequestHandler; + whenGET(url: RegExp, headers?: any): mock.RequestHandler; + whenHEAD(url: string, headers?: any): mock.RequestHandler; + whenHEAD(url: RegExp, headers?: any): mock.RequestHandler; + whenJSONP(url: string): mock.RequestHandler; + whenJSONP(url: RegExp): mock.RequestHandler; + whenPATCH(url: string, data?: string, headers?: any): mock.RequestHandler; + whenPATCH(url: RegExp, data?: string, headers?: any): mock.RequestHandler; + whenPATCH(url: string, data?: RegExp, headers?: any): mock.RequestHandler; + whenPATCH(url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + whenPOST(url: string, data?: string, headers?: any): mock.RequestHandler; + whenPOST(url: RegExp, data?: string, headers?: any): mock.RequestHandler; + whenPOST(url: string, data?: RegExp, headers?: any): mock.RequestHandler; + whenPOST(url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + whenPUT(url: string, data?: string, headers?: any): mock.RequestHandler; + whenPUT(url: RegExp, data?: string, headers?: any): mock.RequestHandler; + whenPUT(url: string, data?: RegExp, headers?: any): mock.RequestHandler; + whenPUT(url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + } + + export module mock { + + // returned interface by the the mocked HttpBackendService expect/when methods + export interface RequestHandler { + respond(func: Function): void; + respond(status: number, data?: any, headers?: any): void; + respond(data: any, headers?: any): void; + + // Available wehn ngMockE2E is loaded + passThrough(): void; + } + + } + +} diff --git a/Definitions/angular-resource-1.0.2.d.ts b/Definitions/angular-resource-1.0.2.d.ts new file mode 100644 index 000000000..0ae67e1b0 --- /dev/null +++ b/Definitions/angular-resource-1.0.2.d.ts @@ -0,0 +1,65 @@ +// Type definitions for Angular JS 1.0.2 (ngResource module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/////////////////////////////////////////////////////////////////////////////// +// ngResource module (angular-resource.js) +/////////////////////////////////////////////////////////////////////////////// +module ng.resource { + + /////////////////////////////////////////////////////////////////////////// + // ResourceService + // see http://docs.angularjs.org/api/ngResource.$resource + // Most part of the following definitions were achieved by analyzing the + // actual implementation, since the documentation doesn't seem to cover + // that deeply. + /////////////////////////////////////////////////////////////////////////// + export interface ResourceService { + (url: string, paramDefaults?: any, actionDescriptors?: any): ResourceClass; + } + + // Just a reference to facilitate describing new actions + export interface ActionDescriptor { + method: string; + isArray?: bool; + params?: any; + headers?: any; + } + + // Baseclass for everyresource with default actions. + // If you define your new actions for the resource, you will need + // to extend this interface and typecast the ResourceClass to it. + export interface ResourceClass { + get: ActionCall; + save: ActionCall; + query: ActionCall; + remove: ActionCall; + delete: ActionCall; + } + + // In case of passing the first argument as anything but a function, + // it's gonna be considered data if the action method is POST, PUT or + // PATCH (in other words, methods with body). Otherwise, it's going + // to be considered as parameters to the request. + export interface ActionCall { + (): Resource; + (dataOrParams: any): Resource; + (dataOrParams: any, success: Function): Resource; + (success: Function, error?: Function): Resource; + (params: any, data: any, success?: Function, error?: Function): Resource; + } + + export interface Resource { + $save: ActionCall; + $remove: ActionCall; + $delete: ActionCall; + + // No documented, but they are there, just as any custom action will be + $query: ActionCall; + $get: ActionCall; + } + +} diff --git a/Definitions/angular-sanitize-1.0.2.d.ts b/Definitions/angular-sanitize-1.0.2.d.ts new file mode 100644 index 000000000..105a9d5ca --- /dev/null +++ b/Definitions/angular-sanitize-1.0.2.d.ts @@ -0,0 +1,21 @@ +// Type definitions for Angular JS 1.0.2 (ngSanitize module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/////////////////////////////////////////////////////////////////////////////// +// ngSanitize module (angular-sanitize.js) +/////////////////////////////////////////////////////////////////////////////// +module ng.sanitize { + + /////////////////////////////////////////////////////////////////////////// + // SanitizeService + // see http://docs.angularjs.org/api/ngSanitize.$sanitize + /////////////////////////////////////////////////////////////////////////// + export interface SanitizeService { + (html: string): string; + } + +} From 8957de3116be1891b1e011094c4446b4ae7d7a4a Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Thu, 25 Oct 2012 04:43:38 +0300 Subject: [PATCH 007/107] Add JQuery Mobile Definitions and tests --- Definitions/jquerymobile-1.2.d.ts | 380 ++++++++++++++++++++++++++++++ README.md | 3 +- Tests/jquerymobile-tests.ts | 254 ++++++++++++++++++++ 3 files changed, 636 insertions(+), 1 deletion(-) create mode 100644 Definitions/jquerymobile-1.2.d.ts create mode 100644 Tests/jquerymobile-tests.ts diff --git a/Definitions/jquerymobile-1.2.d.ts b/Definitions/jquerymobile-1.2.d.ts new file mode 100644 index 000000000..c8a7f0e1a --- /dev/null +++ b/Definitions/jquerymobile-1.2.d.ts @@ -0,0 +1,380 @@ +// Type definitions for jQuery Mobile 1.2 +// Project: http://jquerymobile.com/ +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + + +interface JQueryMobileEvent { (event: Event, ui): void; } + +interface DialogOptions { + closeBtnText?: string; + initSelector?: string; + overlayTheme?: string; +} + +interface DialogEvents { + create?: JQueryMobileEvent; +} + +interface PopupOptions { + corners?: bool; + history?: bool; + initSelector?: string; + overlayTheme?: string; + positionTo?: string; + shadow?: bool; + theme?: string; + tolerance?: string; + transition?: string; +} + +interface PopupEvents { + popupbeforeposition?: JQueryMobileEvent; + popupafteropen?: JQueryMobileEvent; + popupafterclose?: JQueryMobileEvent; +} + +interface FixedToolbarOptions { + visibleOnPageShow?: bool; + disablePageZoom?: bool; + transition?: string; + fullscreen?: bool; + tapToggle?: bool; + tapToggleBlacklist?: string; + hideDuringFocus?: string; + updatePagePadding?: bool; + supportBlacklist?: Function; + initSelector?: string; +} + +interface FixedToolbarEvents { + create?: JQueryMobileEvent; +} + +interface ButtonOptions { + corners?: bool; + icon?: string; + iconpos?: string; + iconshadow?: bool; + inline?: bool; + mini?: bool; + shadow?: bool; + theme?: string; + initSelector?: string; +} + +interface ButtonEvents { + create?: JQueryMobileEvent; +} + +interface CollapsibleOptions { + collapsed?: bool; + collapseCueText?: string; + collapsedIcon?: string; + contentTheme?: string; + expandCueText?: string; + expandedIcon?: string; + heading?: string; + iconpos?: string; + initSelector?: string; + inset?: bool; + mini?: bool; + theme?: string; +} + +interface CollapsibleEvents { + create?: JQueryMobileEvent; + collapse?: JQueryMobileEvent; + expand?: JQueryMobileEvent; +} + +interface CollapsibleSetOptions { + collapsedIcon?: string; + expandedIcon?: string; + iconpos?: string; + initSelector?: string; + inset?: bool; + mini?: bool; + theme?: string; +} + +interface CollapsibleSetEvents { + create?: JQueryMobileEvent; +} + +interface TextInputOptions { + disabled?: bool; + initSelector?: string; + mini?: bool; + preventFocusZoom?: bool; + theme?: string; +} + +interface TextInputEvents { + create?: JQueryMobileEvent; +} + +interface SearchInputOptions { + clearSearchButtonText?: string; + disabled?: bool; + initSelector?: string; + mini?: bool; + theme?: string; +} + +interface SliderOptions { + disabled?: bool; + highlight?: bool; + initSelector?: string; + mini?: bool; + theme?: string; + trackTheme?: string; +} + +interface SliderEvents { + create?: JQueryMobileEvent; + slidestart?: JQueryMobileEvent; + slidestop?: JQueryMobileEvent; +} + +interface CheckboxRadioOptions { + mini?: bool; + theme?: string; +} + +interface CheckboxRadioEvents { + createp?: JQueryMobileEvent; +} + +interface SelectMenuOptions { + corners?: bool; + icon?: string; + iconpos?: string; + iconshadow?: bool; + initSelector?: string; + inline?: bool; + mini?: bool; + nativeMenu?: bool; + overlayTheme?: string; + preventFocusZoom?: bool; + shadow?: bool; + theme?: string; +} + +interface SelectMenuEvents { + create?: JQueryMobileEvent; +} + +interface ListViewOptions { + countTheme?: string; + dividerTheme?: string; + filter?: bool; + filterCallback?: Function; + filterPlaceholder?: string; + filterTheme?: string; + headerTheme?: string; + initSelector?: string; + inset?: bool; + splitIcon?: string; + splitTheme?: string; + theme?: string; +} + +interface ListViewEvents { + create?: JQueryMobileEvent; +} + +interface JQueryMobileOptions { + activeBtnClass?: string; + activePageClass?: string; + ajaxEnabled?: bool; + allowCrossDomainPages?: bool; + autoInitializePage?: bool; + buttonMarkup; + defaultDialogTransition?: string; + defaultPageTransition?: string; + getMaxScrollForTransition?: number; + gradeA?: Function; + hashListeningEnabled?: bool; + ignoreContentEnabled?: bool; + linkBindingEnabled?: bool; + loadingMessageTextVisible?: bool; + loadingMessageTheme?: string; + maxTransitionWidth?: number; + minScrollBack?: number; + ns?: number; + pageLoadErrorMessage?: string; + pageLoadErrorMessageTheme?: string; + phonegapNavigationEnabled?: bool; + pushStateEnabled?: bool; + subPageUrlKey?: string; + touchOverflowEnabled?: bool; + transitionFallbacks; +} + +interface JQueryMobileEvents { + tap; + taphold; + swipe; + swipeleft; + swiperight; + + vmouseover; + vmouseout; + vmousedown; + vmousemove; + vmouseup; + vclick; + vmousecancel; + + orientationchange; + scrollstart; + scrollstop; + + pagebeforeload; + pageload; + pageloadfailed; + pagebeforechange; + pagechange; + pagechangefailed; + pagebeforeshow; + pagebeforehide; + pageshow; + pagehide; + pagebeforecreate; + pagecreate; + pageinit; + pageremove; + updatelayout; +} + +interface ChangePageOptions { + allowSamePageTransition?: bool; + changeHash?: bool; + data?: any; + dataUrl?: string; + pageContainer?: JQuery; + reloadPage?: bool; + reverse?: bool; + role?: string; + showLoadMsg?: bool; + transition?: string; + type?: string; +} + +interface LoadPageOptions { + data?: any; + loadMsgDelay?: number; + pageContainer?: JQuery; + reloadPage?: bool; + role?: string; + showLoadMsg?: bool; + type?: string; +} + +interface JQueryMobile extends JQueryMobileOptions { + + changePage(to: any, options?: ChangePageOptions): void; + loadPage(url: any, options?: LoadPageOptions): void; + loading(command: string, options?): void; + + base; + silentScroll(yPos: number):void; + activePage; + + options: JQueryMobileOptions; + + transitionFallbacks; + loader; + loading; + loadPage; + page; + + silentScroll; + touchOverflow; + showCategory; + path; + + dialog; + popup; + fixedtoolbar; + button; + collapsible; + collapsibleset; + textinput; + slider; + checkboxradio; + selectmenu; + listview; +} + +interface JQuerySupport { + touchOverflow; +} + +interface JQuery { + + dialog(): JQuery; + dialog(command: string): JQuery; + dialog(options: DialogOptions): JQuery; + dialog(events: DialogEvents): JQuery; + + popup(): JQuery; + popup(command: string): JQuery; + popup(options: PopupOptions): JQuery; + popup(command: string, options: PopupOptions): JQuery; + popup(events: PopupEvents): JQuery; + + fixedtoolbar(): JQuery; + fixedtoolbar(command: string): JQuery; + fixedtoolbar(options: FixedToolbarOptions): JQuery; + fixedtoolbar(events: FixedToolbarEvents): JQuery; + + + button(): JQuery; + button(command: string): JQuery; + buttonMarkup(options: ButtonOptions): JQuery; + button(events: ButtonEvents): JQuery; + + collapsible(): JQuery; + collapsible(command: string): JQuery; + collapsible(options: CollapsibleOptions): JQuery; + collapsible(events: CollapsibleEvents): JQuery; + collapsibleSet(): JQuery; + collapsibleSet(command: string): JQuery; + collapsibleset(options: CollapsibleSetOptions): JQuery; + collapsibleset(events: CollapsibleSetEvents): JQuery; + + textinput(): JQuery; + textinput(command: string): JQuery; + textinput(options: TextInputOptions): JQuery; + textinput(events: TextInputEvents): JQuery; + textinput(options: SearchInputOptions): JQuery; + + slider(): JQuery; + slider(command: string): JQuery; + slider(options: SliderOptions): JQuery; + slider(events: SliderEvents): JQuery; + + checkboxradio(): JQuery; + checkboxradio(command: string): JQuery; + checkboxradio(options: CheckboxRadioOptions): JQuery; + checkboxradio(events: CheckboxRadioEvents): JQuery; + + selectmenu(): JQuery; + selectmenu(command: string): JQuery; + selectmenu(command: string, update: bool): JQuery; + selectmenu(options: CheckboxRadioOptions): JQuery; + selectmenu(events: CheckboxRadioEvents): JQuery; + + listview(): JQuery; + listview(command: string): JQuery; + listview(options: ListViewOptions): JQuery; + listview(events: ListViewEvents): JQuery; +} + + +interface JQueryStatic { + mobile: JQueryMobile; +} \ No newline at end of file diff --git a/README.md b/README.md index 805439189..da81beb5d 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Complete * [Jasmine](http://pivotal.github.com/jasmine/) * [jQuery.Globalize](https://github.com/jquery/globalize) * [jQuery](http://jquery.com/) (from TypeScript samples) +* [jQuery Mobile](http://jquerymobile.com) * [jQuery UI](http://jqueryui.com/) * [Knockout.js](http://knockoutjs.com/) * [Modernizr](http://modernizr.com/) @@ -35,10 +36,10 @@ Complete Next ---- * Knockout.Mapping +* Chosen * Angular.js * Facebook SDK * jQuery.Validate -* jQuery Mobile * google.visualization * Meteor * PhoneGap diff --git a/Tests/jquerymobile-tests.ts b/Tests/jquerymobile-tests.ts new file mode 100644 index 000000000..d081a304c --- /dev/null +++ b/Tests/jquerymobile-tests.ts @@ -0,0 +1,254 @@ +/// +/// + +function test_api() { + $.mobile.changePage("about/us.html", { transition: "slideup" }); + $.mobile.changePage("searchresults.php", { + type: "post", + data: $("form#search").serialize() + }); + $.mobile.changePage("../alerts/confirm.html", { + transition: "pop", + reverse: false, + changeHash: false + }); + + $.mobile.loadPage("about/us.html"); + $.mobile.loadPage("searchresults.php", { + type: "post", + data: $("form#search").serialize() + }); + $.mobile.loading('show', { theme: "b", text: "foo", textonly: true }); + $.mobile.path.parseUrl("http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234"); + var absUrl = $.mobile.path.makeUrlAbsolute("#bar", "http://foo.com/a/b/c/test.html"); + var isRel = $.mobile.path.isRelativeUrl("#foo"); + var isAbs = $.mobile.path.isAbsoluteUrl("//foo.com/a/file.html"); + var dirName = $.mobile.path.get("http://foo.com/a"); + $.mobile.silentScroll(100); +} + +function test_pagesDialogs() { + $.mobile.transitionFallbacks.slideout = "none"; + + $(document).bind('mobileinit', function () { + $.mobile.loader.prototype.options.text = "loading"; + $.mobile.loader.prototype.options.textVisible = false; + $.mobile.loader.prototype.options.theme = "a"; + $.mobile.loader.prototype.options.html = ""; + }); + + $.mobile.loading('show', { + text: 'foo', + textVisible: true, + theme: 'z', + html: "" + }); + + $('.ui-dialog').dialog('close'); + $("#myPopupDiv").popup(); + var options; + $(".selector").popup("open", options); + $("#myPopupDiv").popup("open"); + + $(document).on("pageinit", function () { + $('.popupParent').on({ + popupafterclose: function () { + setTimeout(function () { $('.popupChild').popup('open') }, 100); + } + }); + }); + + var pageUrl; + $.mobile.loadPage(pageUrl, { showLoadMsg: false }); + $.mobile.page.prototype.options.domCache = true; + + $.ajaxPrefilter(function (options, originalOptions, jqXHR) { + if (applicationCache && + applicationCache.status != applicationCache.UNCACHED && + applicationCache.status != applicationCache.OBSOLETE) { + // the important bit + options.isLocal = true; + } + }); + + $(document).bind("pagebeforechange", function (e, data) { + if (typeof data.toPage === "string") { + var u = $.mobile.path.parseUrl(data.toPage), + re = /^#category-item/; + if (u.hash.search(re) !== -1) { + var showCategory; + showCategory(u, data.options); + e.preventDefault(); + } + } + }); + $(document).delegate("#aboutPage", "pageinit", function () { + alert('A page with an id of "aboutPage" was just created by jQuery Mobile!'); + }); + $(document).delegate("#aboutPage", "pagebeforecreate", function () { + alert('A page with an id of "aboutPage" is about to be created by jQuery Mobile!'); + }); + $.mobile.changePage("about/us.html", { transition: "slideup" }); + $.mobile.changePage("searchresults.php", { + type: "post", + data: $("form#search").serialize() + }); + $.mobile.loadPage("about/us.html"); + $.mobile.silentScroll(300); + $(document).bind("mobileinit", function () { + $.mobile.allowCrossDomainPages = true; + }); + $.mobile.touchOverflowEnabled = true; + $(document).bind("mobileinit", function () { + $.support.touchOverflow = true; + $.mobile.touchOverflowEnabled = true; + }); +} + +function test_toolbars() { + $.mobile.page.prototype.options.backBtnText = "previous"; + $.mobile.page.prototype.options.backBtnTheme = "a"; + $("[data-role=header]").fixedtoolbar({ visibleOnPageShow: false }); + $("[data-role=header]").fixedtoolbar({ disablePageZoom: false }); + $("[data-role=header]").fixedtoolbar({ transition: "fade" }); + $("[data-role=header]").fixedtoolbar({ fullscreen: true }); + $("[data-role=header]").fixedtoolbar({ tapToggle: true }); + $("[data-role=header]").fixedtoolbar({ tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed" }); + $("[data-role=header]").fixedtoolbar({ hideDuringFocus: "input, select, textarea" }); + $("[data-role=header]").fixedtoolbar({ updatePagePadding: false }); + $(document).bind("mobileinit", function () { + $.mobile.fixedtoolbar.prototype.options.supportBlacklist = function () { + var result; + return result; + }; + $(document).bind("mobileinit", function () { + $.mobile.fixedtoolbar.prototype.options.initSelector = ".myselector"; + }); + }); + $("[data-position='fixed']").fixedtoolbar('show'); + $("[data-position='fixed']").fixedtoolbar('hide'); + $(".selector").fixedtoolbar({ + create: function (event, ui) { } + }); +} + +function test_button() { + $('[type="submit"]').button(); + $('a').buttonMarkup({ corners: false }); + $('a').buttonMarkup({ icon: "star" }); + $('a').buttonMarkup({ iconpos: "right" }); + $('a').buttonMarkup({ iconshadow: false }); + $('a').buttonMarkup({ inline: true }); + $('a').buttonMarkup({ mini: true }); + $('a').buttonMarkup({ shadow: false }); + $('a').buttonMarkup({ theme: "a" }); + $.mobile.button.prototype.options.initSelector = ".myButtons"; + $('[type="submit"]').button('enable'); + $('[type="submit"]').button('disable'); + $('[type="submit"]').button('refresh'); + $('[type="submit"]').button({ + create: function (event, ui) { } + }); +} + +function test_collapsible() { + $.mobile.collapsible.prototype.options.collapsed = false; + $.mobile.collapsible.prototype.options.collapseCueText = " collapse with a click"; + $.mobile.collapsible.prototype.options.collapsedIcon = "arrow-r"; + $.mobile.collapsible.prototype.options.contentTheme = "a"; + $.mobile.collapsible.prototype.options.expandCueText = " expand with a click"; + $.mobile.collapsible.prototype.options.expandedIcon = "arrow-d"; + $.mobile.collapsible.prototype.options.heading = ".mycollapsibleheading"; + $.mobile.collapsible.prototype.options.iconpos = "right"; + $.mobile.collapsible.prototype.options.initSelector = ".mycollapsible"; + $.mobile.collapsible.prototype.options.inset = false; + $.mobile.collapsible.prototype.options.mini = true; + $.mobile.collapsible.prototype.options.theme = "a"; + $(".selector").trigger("collapse"); + $(".selector").collapsible({ + create: function (event, ui) { }, + collapse: function (event, ui) { }, + expand: function (event, ui) { } + }); + $.mobile.collapsibleset.prototype.options.collapsedIcon = "arrow-r"; + $.mobile.collapsibleset.prototype.options.expandedIcon = "arrow-d"; + $.mobile.collapsibleset.prototype.options.iconpos = "right"; + $.mobile.collapsibleset.prototype.options.initSelector = ".mycollapsibleset"; + $.mobile.collapsible.prototype.options.inset = false; + $.mobile.collapsibleset.prototype.options.mini = true; + $.mobile.collapsibleset.prototype.options.theme = "a"; + $(".selector").collapsibleset({ + create: function (event, ui) { } + }); +} + +function test_form() { + $("input[type='checkbox']").prop("checked", true).checkboxradio("refresh"); + $.mobile.page.prototype.options.keepNative = "select, input.foo, textarea.bar"; + + $('input').textinput(); + $('.selector').textinput({ disabled: true }); + $.mobile.textinput.prototype.options.initSelector = ".myInputs"; + $('.selector').textinput({ mini: true }); + $('input').textinput({ preventFocusZoom: true }); + $('.selector').textinput({ theme: "a" }); + $('.selector').textinput('enable'); + $(".selector").textinput({ + create: function (event, ui) { } + }); + + $('select').slider(); + $('.selector').slider({ disabled: true }); + $('.selector').slider({ highlight: true }); + $.mobile.slider.prototype.options.initSelector = ".myslider"; + $('.selector').slider({ mini: true }); + $('.selector').slider({ theme: "a" }); + $('.selector').slider({ trackTheme: "a" }); + $(".selector").slider({ + create: function (event, ui) { } + }); + $(".selector").on('slidestart', function (event) { }); + $(".selector").on('slidestop', function (event) { }); + + $("input[type='radio']").checkboxradio({ mini: true }); + $("input[type='radio']").checkboxradio({ theme: "a" }); + $("input[type='radio']").checkboxradio('enable'); + $("input[type='radio']:first").attr("checked", true).checkboxradio("refresh"); + $("input[type='radio']").checkboxradio({ + create: function (event, ui) { } + }); + + $('select').selectmenu(); + $('select').selectmenu('enable'); + $('select').selectmenu('refresh', true); + $(".selector").selectmenu({ + create: function (event, ui) { } + }); +} + +function test_listview() { + $("#mylistview").listview({ + autodividers: true, + autodividersSelector: function (li) { + var out; + return out; + } + }); + $.mobile.listview.prototype.options.countTheme = "a"; + $.mobile.listview.prototype.options.dividerTheme = "a"; + $.mobile.listview.prototype.options.filter = true; + $.mobile.listview.prototype.options.filterCallback = function (text, searchValue) { + // only show items that *begin* with the search string + return text.toLowerCase().substring(0, searchValue.length) !== searchValue; + }; + $.mobile.listview.prototype.options.filterPlaceholder = "Search..."; + $.mobile.listview.prototype.options.filterTheme = "a"; + $.mobile.listview.prototype.options.headerTheme = "a"; + $.mobile.listview.prototype.options.initSelector = ".mylistview"; + $.mobile.listview.prototype.options.inset = true; + $.mobile.listview.prototype.options.splitIcon = "star"; + $.mobile.listview.prototype.options.splitTheme = "a"; + $.mobile.listview.prototype.options.theme = "a"; + $('#mylist').listview(); + $('#mylist').listview('refresh'); +} \ No newline at end of file From 908f7052739213fb6b8e222e581f97d6b1462c66 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Thu, 25 Oct 2012 06:17:06 +0300 Subject: [PATCH 008/107] Make module definitions external --- Definitions/backbone-0.9.d.ts | 2 +- Definitions/ember-1.0.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Definitions/backbone-0.9.d.ts b/Definitions/backbone-0.9.d.ts index 64a9fe8e3..46281829f 100644 --- a/Definitions/backbone-0.9.d.ts +++ b/Definitions/backbone-0.9.d.ts @@ -1,7 +1,7 @@ // Type definitions for Backbone 0.9 // https://github.com/borisyankov/DefinitelyTyped -declare module Backbone { +declare module "Backbone" { export class Events { on(events: string, callback: (event) => any, context?: any): any; diff --git a/Definitions/ember-1.0.d.ts b/Definitions/ember-1.0.d.ts index 254c19b8d..d879996cf 100644 --- a/Definitions/ember-1.0.d.ts +++ b/Definitions/ember-1.0.d.ts @@ -2,7 +2,7 @@ // Project: http://emberjs.com/ // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module Ember { +declare module "Ember" { export class CoreObject { isDestroyed: bool; From 916e13f8f0ae0d425293e34f6687684849930ff6 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Thu, 25 Oct 2012 06:30:16 +0300 Subject: [PATCH 009/107] Add CodeMirror definitions and tests --- Definitions/codemirror-3.0.d.ts | 220 ++++++++++++++++++++++++++++++++ README.md | 1 + Tests/codemirror-tests.ts | 15 +++ 3 files changed, 236 insertions(+) create mode 100644 Definitions/codemirror-3.0.d.ts create mode 100644 Tests/codemirror-tests.ts diff --git a/Definitions/codemirror-3.0.d.ts b/Definitions/codemirror-3.0.d.ts new file mode 100644 index 000000000..0db876824 --- /dev/null +++ b/Definitions/codemirror-3.0.d.ts @@ -0,0 +1,220 @@ +// Type definitions for CodeMirror 3.0 +// Project: http://codemirror.net +// Definitions by: https://github.com/fdecampredon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface CodeMirrorScrollInfo { + x: number; + y: number; + width: number; + height: number; +} + +interface CodeMirrorCoords { + x: number; + y: number; + yBot: number; +} + +interface CodeMirrorPosition { + line: number; + ch: number; +} + +interface CodeMirrorHistorySize { + undo: number; + redo: number; +} + +interface CodeMirrorToken { + start: number; + end: number; + string: string; + className: string; + state: any; +} + +interface CodeMirrorMarkTextOptions { + inclusiveLeft: bool; + inclusiveRight: bool; + startStype: string; + endStyle: string; +} + + +interface CodeMirrorBookMark { + clear(): void; + find(): CodeMirrorPosition; +} + +interface CodeMirrorLineHandle { + +} + +interface CodeMirrorLineInfo { + line: number; + handler: CodeMirrorLineHandle; + text: string; + markerText: string; + markerClass: string; + lineClass: string; + bgClass: string; +} + + +interface CodeMirrorViewPort { + from: number; + to: number; +} + + +interface CodeMirrorChange { + from: CodeMirrorPosition; + to: CodeMirrorPosition; + text: string[]; + next: CodeMirrorChange; +} + +interface CodeMirrorChangeListener { + (editor: CodeMirrorEditor, change: CodeMirrorChange): void; +} + +interface CodeMirrorViewPortChangeListener { + (editor: CodeMirrorEditor, from: CodeMirrorPosition, to: CodeMirrorPosition): void; +} + + +interface CodeMirrorStream { + eol(): bool; + sol(): bool; + peek(): string; + next(): string; + eat(match: any): string; + eatWhile(match: any): bool; + eatSpace(): bool; + skipToEnd(): void; + skipTo(ch: string): bool; + match(pattern: RegExp, consume: bool, caseFold: bool): bool; + backUp(n: number): void; + column(): number; + indentation(): number; + current(): string; + string: string; + pos: number; +} + + +interface CodeMirrorModeDefition { + (options: CodeMirrorOptions, modeOptions: any): CodeMirrorMode; +} + + + +interface CodeMirrorMode { + startState(): any; + token(stream: CodeMirrorStream, state: any): string; + blankLine? (state: any): string; + copyState? (state: any): any; + indent? (state: any, textAfter: string, text: String): number; + electricChars?: string; +} + + +interface CodeMirrorEditor { + getValue(): string; + setValue(valu: string): void; + getSelection(): string; + replaceSelection(value: string): void; + setSize(width: number, height: number): void; + focus(): void; + scrollTo(x: number, y: number): void; + getScrollInfo(): CodeMirrorScrollInfo; + setOption(option: string, value: any); + getOption(option: string): any; + getMode(): CodeMirrorMode; + cursorCoords(start: bool, mode: string): CodeMirrorCoords; + charCoords(pos: CodeMirrorPosition, mode: string): CodeMirrorCoords; + undo(): void; + redo(): void; + historySize(): CodeMirrorHistorySize; + clearHistory(): void; + getHistory(): any; + setHistory(history: any); + indentLine(line: number, dir?: bool); + getTokenAt(pos: CodeMirrorPosition): CodeMirrorToken; + markText(from: CodeMirrorPosition, to: CodeMirrorPosition, className: string, + option?: CodeMirrorMarkTextOptions): CodeMirrorBookMark; + setBookmark(pos: CodeMirrorPosition): CodeMirrorBookMark; + findMarksAt(pos: CodeMirrorPosition): CodeMirrorBookMark[]; + setMarker(line: number, text: string, className: string): CodeMirrorLineHandle; + clarMarker(line: number): void; + setLineClass(line: number, className: string, backgroundClassName: string): CodeMirrorLineHandle; + hideLine(line: number): CodeMirrorLineHandle; + showLine(line: number): CodeMirrorLineHandle; + onDeleteLine(line: number, callBack: Function); + lineInfo(line: number): CodeMirrorLineInfo; + getLineHandler(line: number): CodeMirrorLineHandle; + getViewPort(): CodeMirrorViewPort; + addWidget(pos: CodeMirrorPosition, node: Node, scrollIntoView: bool); + matchBrackets(): void; + lineCount(): number; + getCursor(start?: bool): CodeMirrorPosition; + somethingSelected(): bool; + setCursor(pos: CodeMirrorPosition): void; + setSelection(start: CodeMirrorPosition, end: CodeMirrorPosition): void; + getLine(n: number): string; + setLine(n: string, text: string): void; + removeLine(n: number): void; + getRange(from: CodeMirrorPosition, to: CodeMirrorPosition): string; + replaceRange(text: string, from: CodeMirrorPosition, to?: CodeMirrorPosition): void; + posFromIndex(index: number): CodeMirrorPosition; + indexFromPos(pos: CodeMirrorPosition): number; + operation(func: Function): any; + compundChange(func: Function): any; + refresh(): void; + getInputField(): HTMLTextAreaElement; + getWrapperElement(): HTMLElement; + getScrollerElement(): HTMLElement; + getGutterElement(): HTMLElement; + getStateAfter(line): any; +} + + +interface CodeMirrorOptions { + value?: string; + mode?: string; + them?: string; + indentUnit?: number; + smartIndend?: number; + tabSize?: number; + indentWithTabs?: bool; + electricsChars?: bool; + autoClearEmptyLines?: bool; + keyMap?: string; + extraKeys?: any; + lineWrapping?: bool; + lineNumbers?: bool; + firstLineNumber?: bool; + lineNumberFormatter?: Function; + gutter?: bool; + fixedGutter?: bool; + readOnly?: bool; + onChange?: CodeMirrorChangeListener; + onCursorActivity?: Function; + onViewportChange?: CodeMirrorViewPortChangeListener; + //**todo finish +} + + +declare var CodeMirror: { + (element: HTMLElement, options?: CodeMirrorOptions): CodeMirrorEditor; + (element: Function, options?: CodeMirrorOptions): CodeMirrorEditor; + version: string; + defaults: CodeMirrorOptions; + fromTextArea(textArea: HTMLTextAreaElement, options?: CodeMirrorOptions): CodeMirrorEditor; + defineMode(name: string, func: CodeMirrorModeDefition); + defineMIME(mime: string, mode: string); + connect(target: EventTarget, event: String, func: Function); + commands: any; +} diff --git a/README.md b/README.md index da81beb5d..08e73c226 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ Complete * [async](https://github.com/caolan/async) * [Backbone.js](http://backbonejs.org/) * [Bootstrap](http://twitter.github.com/bootstrap/) +* [CodeMirror](http://codemirror.net) (by [Franois de Campredon](https://github.com/fdecampredon)) * [ember.js](http://emberjs.com/) * [Express](http://expressjs.com/) (from TypeScript samples) * [Fancybox](http://fancybox.net/) diff --git a/Tests/codemirror-tests.ts b/Tests/codemirror-tests.ts new file mode 100644 index 000000000..12c028b90 --- /dev/null +++ b/Tests/codemirror-tests.ts @@ -0,0 +1,15 @@ +/// + +var myCodeMirror = CodeMirror(document.body); + +var myCodeMirror2 = CodeMirror(document.body, { + value: "function myScript(){return 100;}\n", + mode: "javascript" +}); + +var myTextArea; +var myCodeMirror3 = CodeMirror(function (elt) { + myTextArea.parentNode.replaceChild(elt, myTextArea); +}, { value: myTextArea.value }); + +var myCodeMirror4 = CodeMirror.fromTextArea(myTextArea); \ No newline at end of file From 6b1e20a832faf9634fce832a2cc58f40c6f3ff8c Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Thu, 25 Oct 2012 06:38:17 +0300 Subject: [PATCH 010/107] Readme update --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 08e73c226..304086ecc 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Complete * [Fancybox](http://fancybox.net/) * [Handlebars](http://handlebarsjs.com/) * [History.js](https://github.com/balupton/History.js/) -* [Humane.js](http://wavded.github.com/humane-js/) (by [jmvrbanac](https://github.com/jmvrbanac)) +* [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac)) * [Impress.js](https://github.com/bartaz/impress.js) * [Jasmine](http://pivotal.github.com/jasmine/) * [jQuery.Globalize](https://github.com/jquery/globalize) From 329e52af0f48db022bdab04a1a0b2050e0008285 Mon Sep 17 00:00:00 2001 From: Diego Vilar Date: Thu, 25 Oct 2012 01:33:16 -0300 Subject: [PATCH 011/107] Remove export keyword for all interfaces (unnecessary); Renamed interfaces to start with an I; IAngularStatic.bootstrap is now overloaded to accept Element, IJQLiteOrBetter or string as the first parameter. --- Definitions/angular-1.0.2.d.ts | 292 ++++++++++++------------ Definitions/angular-cookies-1.0.2.d.ts | 4 +- Definitions/angular-mocks-1.0.2.d.ts | 128 +++++------ Definitions/angular-resource-1.0.2.d.ts | 42 ++-- Definitions/angular-sanitize-1.0.2.d.ts | 2 +- 5 files changed, 235 insertions(+), 233 deletions(-) diff --git a/Definitions/angular-1.0.2.d.ts b/Definitions/angular-1.0.2.d.ts index db76ea472..73d491507 100644 --- a/Definitions/angular-1.0.2.d.ts +++ b/Definitions/angular-1.0.2.d.ts @@ -5,7 +5,7 @@ /// -declare var angular: ng.AngularStatic; +declare var angular: ng.IAngularStatic; /////////////////////////////////////////////////////////////////////////////// // ng module (angular.js) @@ -13,10 +13,10 @@ declare var angular: ng.AngularStatic; module ng { // For the sake of simplicity, let's assume jQuery is always preferred - interface JQLiteOrBetter extends JQuery { } + interface IJQLiteOrBetter extends JQuery { } // All service providers extend this interface - export interface ServiceProvider { + interface IServiceProvider { $get(): any; } @@ -24,17 +24,19 @@ module ng { // AngularStatic // see http://docs.angularjs.org/api /////////////////////////////////////////////////////////////////////////// - export interface AngularStatic { + interface IAngularStatic { bind(context: any, fn: Function, ...args: any[]): Function; - bootstrap(element: Element, modules?: any[]): auto.InjectorService; + bootstrap(element: string, modules?: any[]): auto.IInjectorService; + bootstrap(element: IJQLiteOrBetter, modules?: any[]): auto.IInjectorService; + bootstrap(element: Element, modules?: any[]): auto.IInjectorService; copy(source: any, destination?: any): any; - element: JQLiteOrBetter; + element: IJQLiteOrBetter; equals(value1: any, value2: any): bool; extend(destination: any, ...sources: any[]): any; forEach(obj: any, iterator: (value, key) => any, context?: any): any; fromJson(json: string): any; identity(arg?: any): any; - injector(modules?: any[]): auto.InjectorService; + injector(modules?: any[]): auto.IInjectorService; isArray(value: any): bool; isDate(value: any): bool; isDefined(value: any): bool; @@ -45,7 +47,7 @@ module ng { isString(value: any): bool; isUndefined(value: any): bool; lowercase(str: string): string; - module(name: string, requires?: string[], configFunction?: Function): Module; + module(name: string, requires?: string[], configFunction?: Function): IModule; noop(...args: any[]): void; toJson(obj: any, pretty?: bool): string; uppercase(str: string): string; @@ -62,18 +64,18 @@ module ng { // Module // see http://docs.angularjs.org/api/angular.Module /////////////////////////////////////////////////////////////////////////// - export interface Module { - config(configFn: Function): Module; - constant(name: string, value: any): Module; - controller(name: string, controllerConstructor: Function): Module; - controller(name: string, inlineAnnotadedConstructor: any[]): Module; - directive(name: string, directiveFactory: Function): Module; - factory(name: string, serviceFactoryFunction: Function): Module; - filter(name: string, filterFactoryFunction: Function): Module; - provider(name: string, serviceProviderConstructor: Function): Module; - run(initializationFunction: Function): Module; - service(name: string, serviceConstructor: Function): Module; - value(name: string, value: any): Module; + interface IModule { + config(configFn: Function): IModule; + constant(name: string, value: any): IModule; + controller(name: string, controllerConstructor: Function): IModule; + controller(name: string, inlineAnnotadedConstructor: any[]): IModule; + directive(name: string, directiveFactory: Function): IModule; + factory(name: string, serviceFactoryFunction: Function): IModule; + filter(name: string, filterFactoryFunction: Function): IModule; + provider(name: string, serviceProviderConstructor: Function): IModule; + run(initializationFunction: Function): IModule; + service(name: string, serviceConstructor: Function): IModule; + value(name: string, value: any): IModule; // Properties name: string; @@ -84,7 +86,7 @@ module ng { // Attributes // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes /////////////////////////////////////////////////////////////////////////// - export interface Attributes { + interface IAttributes { $set(name: string, value: any): void; $attr: any; } @@ -93,7 +95,7 @@ module ng { // FormController // see http://docs.angularjs.org/api/ng.directive:form.FormController /////////////////////////////////////////////////////////////////////////// - export interface FormController { + interface IFormController { $pristine: bool; $dirty: bool; $valid: bool; @@ -105,7 +107,7 @@ module ng { // NgModelController // see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController /////////////////////////////////////////////////////////////////////////// - export interface NgModelController { + interface INgModelController { $render(): void; $setValidity(validationErrorKey: string, isValid: bool): void; $setViewValue(value: string): void; @@ -118,8 +120,8 @@ module ng { // XXX Same as avove $modelValue: any; - $parsers: ModelParser[]; - $formatters: ModelFormatter[]; + $parsers: IModelParser[]; + $formatters: IModelFormatter[]; $error: any; $pristine: bool; $dirty: bool; @@ -127,11 +129,11 @@ module ng { $invalid: bool; } - export interface ModelParser { + interface IModelParser { (value: any): any; } - export interface ModelFormatter { + interface IModelFormatter { (value: any): any; } @@ -139,40 +141,40 @@ module ng { // Scope // see http://docs.angularjs.org/api/ng.$rootScope.Scope /////////////////////////////////////////////////////////////////////////// - export interface Scope { + interface IScope { // Documentation says exp is optional, but actual implementaton counts on it $apply(exp: string): any; - $apply(exp: (scope: Scope) => any): any; + $apply(exp: (scope: IScope) => any): any; - $broadcast(name: string, ...args: any[]): AngularEvent; + $broadcast(name: string, ...args: any[]): IAngularEvent; $destroy(): void; $digest(): void; - $emit(name: string, ...args: any[]): AngularEvent; + $emit(name: string, ...args: any[]): IAngularEvent; // Documentation says exp is optional, but actual implementaton counts on it $eval(expression: string): any; - $eval(expression: (scope: Scope) => any): any; + $eval(expression: (scope: IScope) => any): any; // Documentation says exp is optional, but actual implementaton counts on it $evalAsync(expression: string): void; - $evalAsync(expression: (scope: Scope) => any): void; + $evalAsync(expression: (scope: IScope) => any): void; // Defaults to false by the implementation checking strategy - $new(isolate?: bool): Scope; + $new(isolate?: bool): IScope; - $on(name: string, listener: (event: AngularEvent, ...args: any[]) => any): Function; + $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: bool): Function; - $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: Scope) => any, objectEquality?: bool): Function; - $watch(watchExpression: (scope: Scope) => any, listener?: string, objectEquality?: bool): Function; - $watch(watchExpression: (scope: Scope) => any, listener?: (newValue: any, oldValue: any, scope: Scope) => any, objectEquality?: bool): Function; + $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: bool): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: bool): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: bool): Function; $id: number; } - export interface AngularEvent { - targetScope: Scope; - currentScope: Scope; + interface IAngularEvent { + targetScope: IScope; + currentScope: IScope; name: string; preventDefault: Function; defaultPrevented: bool; @@ -185,21 +187,21 @@ module ng { // WindowService // see http://docs.angularjs.org/api/ng.$window /////////////////////////////////////////////////////////////////////////// - export interface WindowService extends Window {} + interface IWindowService extends Window {} /////////////////////////////////////////////////////////////////////////// // BrowserService // TODO undocumented, so we need to get it from the source code /////////////////////////////////////////////////////////////////////////// - export interface BrowserService {} + interface IBrowserService {} /////////////////////////////////////////////////////////////////////////// // TimeoutService // see http://docs.angularjs.org/api/ng.$timeout /////////////////////////////////////////////////////////////////////////// - export interface TimeoutService { - (func: Function, delay?: number, invokeApply?: bool): Promise; - cancel(promise: Promise): bool; + interface ITimeoutService { + (func: Function, delay?: number, invokeApply?: bool): IPromise; + cancel(promise: IPromise): bool; } /////////////////////////////////////////////////////////////////////////// @@ -207,36 +209,36 @@ module ng { // see http://docs.angularjs.org/api/ng.$filter // see http://docs.angularjs.org/api/ng.$filterProvider /////////////////////////////////////////////////////////////////////////// - export interface FilterService { + interface IFilterService { (name: string): Function; } - export interface FilterProvider extends ServiceProvider { - register(name: string, filterFactory: Function): ServiceProvider; + interface IFilterProvider extends IServiceProvider { + register(name: string, filterFactory: Function): IServiceProvider; } /////////////////////////////////////////////////////////////////////////// // LocaleService // see http://docs.angularjs.org/api/ng.$locale /////////////////////////////////////////////////////////////////////////// - export interface LocaleService { + interface ILocaleService { id: string; // These are not documented // Check angular's i18n files for exemples - NUMBER_FORMATS: LocaleNumberFormatDescriptor; + NUMBER_FORMATS: ILocaleNumberFormatDescriptor; DATETIME_FORMATS: any; pluralCat: (num: any) => string; } - export interface LocaleNumberFormatDescriptor { + interface ILocaleNumberFormatDescriptor { DECIMAL_SEP: string; GROUP_SEP: string; - PATTERNS: LocaleNumberPatternDescriptor[]; + PATTERNS: ILocaleNumberPatternDescriptor[]; CURRENCY_SYM: string; } - export interface LocaleNumberPatternDescriptor { + interface ILocaleNumberPatternDescriptor { minInt: number; minFrac: number; maxFrac: number; @@ -248,7 +250,7 @@ module ng { lgSize: number; } - export interface LacaleDateTimeFormatDescriptor { + interface ILacaleDateTimeFormatDescriptor { MONTH: string[]; SHORTMONTH: string[]; DAY: string[]; @@ -268,16 +270,16 @@ module ng { // LogService // see http://docs.angularjs.org/api/ng.$log /////////////////////////////////////////////////////////////////////////// - export interface LogService { - error: LogCall; - info: LogCall; - log: LogCall; - warn: LogCall; + interface ILogService { + error: ILogCall; + info: ILogCall; + log: ILogCall; + warn: ILogCall; } // We define this as separete interface so we can reopen it later for // the ngMock module. - interface LogCall { + interface ILogCall { (...args: any[]): void; } @@ -285,11 +287,11 @@ module ng { // ParseService // see http://docs.angularjs.org/api/ng.$parse /////////////////////////////////////////////////////////////////////////// - export interface ParseService { - (expression: string): CompiledExpression; + interface IParseService { + (expression: string): ICompiledExpression; } - export interface CompiledExpression { + interface ICompiledExpression { (context: any, locals?: any): any; // If value is not provided, undefined is gonna be used since the implementation @@ -304,45 +306,45 @@ module ng { // see http://docs.angularjs.org/api/ng.$locationProvider // see http://docs.angularjs.org/guide/dev_guide.services.$location /////////////////////////////////////////////////////////////////////////// - export interface LocationService { + interface ILocationService { absUrl(): string; hash(): string; - hash(newHash: string): LocationService; + hash(newHash: string): ILocationService; host(): string; path(): string; - path(newPath: string): LocationService; + path(newPath: string): ILocationService; port(): number; protocol(): string; - replace(): LocationService; + replace(): ILocationService; search(): string; - search(parametersMap: any): LocationService; - search(parameter: string, parameterValue: any): LocationService; + search(parametersMap: any): ILocationService; + search(parameter: string, parameterValue: any): ILocationService; url(): string; - url(url: string): LocationService; + url(url: string): ILocationService; } - export interface LocationProvider extends ServiceProvider { + interface ILocationProvider extends IServiceProvider { hashPrefix(): string; - hashPrefix(prefix: string): LocationProvider; + hashPrefix(prefix: string): ILocationProvider; html5Mode(): bool; // Documentation states that parameter is string, but // implementation tests it as boolean, which makes more sense // since this is a toggler - html5Mode(active: bool): LocationProvider; + html5Mode(active: bool): ILocationProvider; } /////////////////////////////////////////////////////////////////////////// // DocumentService // see http://docs.angularjs.org/api/ng.$document /////////////////////////////////////////////////////////////////////////// - export interface DocumentService extends Document {} + interface IDocumentService extends Document {} /////////////////////////////////////////////////////////////////////////// // ExceptionHandlerService // see http://docs.angularjs.org/api/ng.$exceptionHandler /////////////////////////////////////////////////////////////////////////// - export interface ExceptionHandlerService { + interface IExceptionHandlerService { (exception: Error, cause?: string): void; } @@ -350,24 +352,24 @@ module ng { // RootElementService // see http://docs.angularjs.org/api/ng.$rootElement /////////////////////////////////////////////////////////////////////////// - export interface RootElementService extends JQLiteOrBetter {} + interface IRootElementService extends IJQLiteOrBetter {} /////////////////////////////////////////////////////////////////////////// // QService // see http://docs.angularjs.org/api/ng.$q /////////////////////////////////////////////////////////////////////////// - export interface QService { - all(promises: Promise[]): Promise; - defer(): Deferred; - reject(reason?: any): Promise; - when(value: any): Promise; + interface IQService { + all(promises: IPromise[]): IPromise; + defer(): IDeferred; + reject(reason?: any): IPromise; + when(value: any): IPromise; } - export interface Promise { - then(successCallback: Function, errorCallback?: Function): Promise; + interface IPromise { + then(successCallback: Function, errorCallback?: Function): IPromise; } - export interface Deferred { + interface IDeferred { resolve(value?: any): void; reject(reason?: string): void; } @@ -376,11 +378,11 @@ module ng { // AnchorScrollService // see http://docs.angularjs.org/api/ng.$anchorScroll /////////////////////////////////////////////////////////////////////////// - export interface AnchorScrollService { + interface IAnchorScrollService { (): void; } - export interface AnchorScrollProvider extends ServiceProvider { + interface IAnchorScrollProvider extends IServiceProvider { disableAutoScrolling(): void; } @@ -388,19 +390,19 @@ module ng { // CacheFactoryService // see http://docs.angularjs.org/api/ng.$cacheFactory /////////////////////////////////////////////////////////////////////////// - export interface CacheFactoryService { + interface ICacheFactoryService { // Lets not foce the optionsMap to have the capacity member. Even though // it's the ONLY option considered by the implementation today, a consumer // might find it useful to associate some other options to the cache object. //(cacheId: string, optionsMap?: { capacity: number; }): CacheObject; - (cacheId: string, optionsMap?: { capacity: number; }): CacheObject; + (cacheId: string, optionsMap?: { capacity: number; }): ICacheObject; // Methods bellow are not documented info(): any; - get(cacheId: string): CacheObject; + get(cacheId: string): ICacheObject; } - export interface CacheObject { + interface ICacheObject { info(): { id: string; size: number; @@ -420,22 +422,22 @@ module ng { // see http://docs.angularjs.org/api/ng.$compile // see http://docs.angularjs.org/api/ng.$compileProvider /////////////////////////////////////////////////////////////////////////// - export interface CompileService { - (element: string, transclude?: TemplateLinkingFunction, maxPriority?: number): TemplateLinkingFunction; - (element: Element, transclude?: TemplateLinkingFunction, maxPriority?: number): TemplateLinkingFunction; - (element: JQLiteOrBetter, transclude?: TemplateLinkingFunction, maxPriority?: number): TemplateLinkingFunction; + interface ICompileService { + (element: string, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: Element, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: IJQLiteOrBetter, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; } - export interface CompileProvider extends ServiceProvider { - directive(name: string, directiveFactory: Function): CompileProvider; + interface ICompileProvider extends IServiceProvider { + directive(name: string, directiveFactory: Function): ICompileProvider; // Undocumented, but it is there... - directive(directivesMap: any): CompileProvider; + directive(directivesMap: any): ICompileProvider; } - export interface TemplateLinkingFunction { + interface ITemplateLinkingFunction { // Let's hint but not force cloneAttachFn's signature - (scope: Scope, cloneAttachFn?: (clonedElement?: JQLiteOrBetter, scope?: Scope) => any): JQLiteOrBetter; + (scope: IScope, cloneAttachFn?: (clonedElement?: IJQLiteOrBetter, scope?: IScope) => any): IJQLiteOrBetter; } /////////////////////////////////////////////////////////////////////////// @@ -443,13 +445,13 @@ module ng { // see http://docs.angularjs.org/api/ng.$controller // see http://docs.angularjs.org/api/ng.$controllerProvider /////////////////////////////////////////////////////////////////////////// - export interface ControllerService { + interface IControllerService { // Although the documentation doesn't state this, locals are optional (controllerConstructor: Function, locals?: any): any; (controllerName: string, locals?: any): any; } - export interface ControlerPovider extends ServiceProvider { + interface IControlerPovider extends IServiceProvider { register(name: string, controllerConstructor: Function): void; register(name: string, dependencyAnnotadedConstructor: any[]): void; } @@ -458,16 +460,16 @@ module ng { // HttpService // see http://docs.angularjs.org/api/ng.$http /////////////////////////////////////////////////////////////////////////// - export interface HttpService { + interface IHttpService { // At least moethod and url must be provided... - (config: RequestConfig): HttpPromise; - get(url: string, RequestConfig?: any): HttpPromise; - delete(url: string, RequestConfig?: any): HttpPromise; - head(url: string, RequestConfig?: any): HttpPromise; - jsonp(url: string, RequestConfig?: any): HttpPromise; - post(url: string, data: any, RequestConfig?: any): HttpPromise; - put(url: string, data: any, RequestConfig?: any): HttpPromise; - defaults: RequestConfig; + (config: IRequestConfig): IHttpPromise; + get(url: string, RequestConfig?: any): IHttpPromise; + delete(url: string, RequestConfig?: any): IHttpPromise; + head(url: string, RequestConfig?: any): IHttpPromise; + jsonp(url: string, RequestConfig?: any): IHttpPromise; + post(url: string, data: any, RequestConfig?: any): IHttpPromise; + put(url: string, data: any, RequestConfig?: any): IHttpPromise; + defaults: IRequestConfig; // For debugging, BUT it is documented as public, so... pendingRequests: any[]; @@ -476,7 +478,7 @@ module ng { // This is just for hinting. // Some opetions might not be available depending on the request. // see http://docs.angularjs.org/api/ng.$http#Usage for options explanations - export interface RequestConfig { + interface IRequestConfig { method: string; url: string; params?: any; @@ -494,20 +496,20 @@ module ng { transformResponse?: any; } - export interface HttpPromise extends Promise { - success(callback: (response: DestructuredResponse) => any): HttpPromise; - error(callback: (response: DestructuredResponse) => any): HttpPromise; + interface IHttpPromise extends IPromise { + success(callback: (response: IDestructuredResponse) => any): IHttpPromise; + error(callback: (response: IDestructuredResponse) => any): IHttpPromise; } - export interface DestructuredResponse { + interface IDestructuredResponse { data: any; status: number; headers: (headerName: string) => string; - config: RequestConfig; + config: IRequestConfig; } - export interface HttpProvider extends ServiceProvider { - defaults: RequestConfig; + interface IHttpProvider extends IServiceProvider { + defaults: IRequestConfig; } /////////////////////////////////////////////////////////////////////////// @@ -515,7 +517,7 @@ module ng { // see http://docs.angularjs.org/api/ng.$httpBackend // You should never need to use this service directly. /////////////////////////////////////////////////////////////////////////// - export interface HttpBackendService { + interface IHttpBackendService { // XXX Perhaps define callback signature in the future (method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: bool); void; } @@ -525,57 +527,57 @@ module ng { // see http://docs.angularjs.org/api/ng.$interpolate // see http://docs.angularjs.org/api/ng.$interpolateProvider /////////////////////////////////////////////////////////////////////////// - export interface InterpolateService { - (text: string, mustHaveExpression?: bool): InterpolationFunction; + interface IInterpolateService { + (text: string, mustHaveExpression?: bool): IInterpolationFunction; endSymbol(): string; startSymbol(): string; } - export interface InterpolationFunction { + interface IInterpolationFunction { (context: any): string; } - export interface InterpolateProvider extends ServiceProvider { + interface IInterpolateProvider extends IServiceProvider { startSymbol(): string; - startSymbol(value: string): InterpolateProvider; + startSymbol(value: string): IInterpolateProvider; endSymbol(): string; - endSymbol(value: string): InterpolateProvider; + endSymbol(value: string): IInterpolateProvider; } /////////////////////////////////////////////////////////////////////////// // RouteParamsService // see http://docs.angularjs.org/api/ng.$routeParams /////////////////////////////////////////////////////////////////////////// - export interface RouteParamsService {} + interface IRouteParamsService {} /////////////////////////////////////////////////////////////////////////// // TemplateCacheService // see http://docs.angularjs.org/api/ng.$templateCache /////////////////////////////////////////////////////////////////////////// - export interface TemplateCacheService extends CacheObject {} + interface ITemplateCacheService extends ICacheObject {} /////////////////////////////////////////////////////////////////////////// // RootScopeService // see http://docs.angularjs.org/api/ng.$rootScope /////////////////////////////////////////////////////////////////////////// - export interface RootScopeService extends Scope {} + interface IRootScopeService extends IScope {} /////////////////////////////////////////////////////////////////////////// // RouteService // see http://docs.angularjs.org/api/ng.$route // see http://docs.angularjs.org/api/ng.$routeProvider /////////////////////////////////////////////////////////////////////////// - export interface RouteService { + interface IRouteService { reload(): void; routes: any; // May not always be available. For instance, current will not be available // to a controller that was not initialized as a result of a route maching. - current?: CurrentRoute; + current?: ICurrentRoute; } // see http://docs.angularjs.org/api/ng.$routeProvider#when for options explanations - export interface Route { + interface IRoute { controller?: any; template?: string; templateUrl?: string; @@ -585,28 +587,28 @@ module ng { } // see http://docs.angularjs.org/api/ng.$route#current - export interface CurrentRoute extends Route { + interface ICurrentRoute extends IRoute { locals: { - $scope: Scope; + $scope: IScope; $template: string; }; } - export interface RouteProviderProvider extends ServiceProvider { - otherwise(params: any): RouteProviderProvider; - when(path: string, route: Route): RouteProviderProvider; + interface IRouteProviderProvider extends IServiceProvider { + otherwise(params: any): IRouteProviderProvider; + when(path: string, route: IRoute): IRouteProviderProvider; } /////////////////////////////////////////////////////////////////////////// // AUTO module (angular.js) /////////////////////////////////////////////////////////////////////////// - module auto { + export module auto { /////////////////////////////////////////////////////////////////////// // InjectorService // see http://docs.angularjs.org/api/AUTO.$injector /////////////////////////////////////////////////////////////////////// - export interface InjectorService { + interface IInjectorService { annotate(fn: Function): string[]; annotate(inlineAnnotadedFunction: any[]): string[]; get(name: string): any; @@ -618,18 +620,18 @@ module ng { // ProvideService // see http://docs.angularjs.org/api/AUTO.$provide /////////////////////////////////////////////////////////////////////// - export interface ProvideService { + interface IProvideService { // Documentation says it returns the registered instance, but actual // implementation does not return anything. // constant(name: string, value: any): any; constant(name: string, value: any): void; decorator(name: string, decorator: Function): void; - factory(name: string, serviceFactoryFunction: Function): ng.ServiceProvider; - provider(name: string, provider: ng.ServiceProvider): ng.ServiceProvider; - provider(name: string, serviceProviderConstructor: Function): ng.ServiceProvider; - service(name: string, constructor: Function): ng.ServiceProvider; - value(name: string, value: any): ng.ServiceProvider; + factory(name: string, serviceFactoryFunction: Function): ng.IServiceProvider; + provider(name: string, provider: ng.IServiceProvider): ng.IServiceProvider; + provider(name: string, serviceProviderConstructor: Function): ng.IServiceProvider; + service(name: string, constructor: Function): ng.IServiceProvider; + value(name: string, value: any): ng.IServiceProvider; } } diff --git a/Definitions/angular-cookies-1.0.2.d.ts b/Definitions/angular-cookies-1.0.2.d.ts index 876ae5f2e..d3f2f85f7 100644 --- a/Definitions/angular-cookies-1.0.2.d.ts +++ b/Definitions/angular-cookies-1.0.2.d.ts @@ -14,13 +14,13 @@ module ng.cookies { // CookieService // see http://docs.angularjs.org/api/ngCookies.$cookies /////////////////////////////////////////////////////////////////////////// - export interface CookiesService {} + interface ICookiesService {} /////////////////////////////////////////////////////////////////////////// // CookieStoreService // see http://docs.angularjs.org/api/ngCookies.$cookieStore /////////////////////////////////////////////////////////////////////////// - export interface CookieStoreService { + interface ICookieStoreService { get(key: string): any; put(key: string, value: any): void; remove(key: string): void; diff --git a/Definitions/angular-mocks-1.0.2.d.ts b/Definitions/angular-mocks-1.0.2.d.ts index cbadc152b..04702f022 100644 --- a/Definitions/angular-mocks-1.0.2.d.ts +++ b/Definitions/angular-mocks-1.0.2.d.ts @@ -14,11 +14,11 @@ module ng { // AngularStatic // We reopen it to add the MockStatic definition /////////////////////////////////////////////////////////////////////////// - export interface AngularStatic { - mock: MockStatic; + interface IAngularStatic { + mock: IMockStatic; } - interface MockStatic { + interface IMockStatic { // see http://docs.angularjs.org/api/angular.mock.debug debug(obj: any): string; @@ -38,7 +38,7 @@ module ng { // see http://docs.angularjs.org/api/ngMock.$exceptionHandler // see http://docs.angularjs.org/api/ngMock.$exceptionHandlerProvider /////////////////////////////////////////////////////////////////////////// - export interface ExceptionHandlerProvider extends ServiceProvider { + interface IExceptionHandlerProvider extends IServiceProvider { mode(mode: string): void; } @@ -47,7 +47,7 @@ module ng { // see http://docs.angularjs.org/api/ngMock.$timeout // Augments the original service /////////////////////////////////////////////////////////////////////////// - export interface TimeoutService { + interface ITimeoutService { flush(): void; } @@ -56,7 +56,7 @@ module ng { // see http://docs.angularjs.org/api/ngMock.$log // Augments the original service /////////////////////////////////////////////////////////////////////////// - export interface LogService { + interface ILogService { assertEmpty(): void; reset(): void; } @@ -69,77 +69,77 @@ module ng { // HttpBackendService // see http://docs.angularjs.org/api/ngMock.$httpBackend /////////////////////////////////////////////////////////////////////////// - export interface HttpBackendService { + interface IHttpBackendService { flush(count: number): void; resetExpectations(): void; verifyNoOutstandingExpectation(): void; verifyNoOutstandingRequest(): void; - expect(method: string, url: string, data?: string, headers?: any): mock.RequestHandler; - expect(method: string, url: RegExp, data?: string, headers?: any): mock.RequestHandler; - expect(method: string, url: string, data?: RegExp, headers?: any): mock.RequestHandler; - expect(method: string, url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; - expect(method: RegExp, url: string, data?: string, headers?: any): mock.RequestHandler; - expect(method: RegExp, url: RegExp, data?: string, headers?: any): mock.RequestHandler; - expect(method: RegExp, url: string, data?: RegExp, headers?: any): mock.RequestHandler; - expect(method: RegExp, url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + expect(method: string, url: string, data?: string, headers?: any): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + expect(method: string, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + expect(method: RegExp, url: string, data?: string, headers?: any): mock.IRequestHandler; + expect(method: RegExp, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + expect(method: RegExp, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + expect(method: RegExp, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; - when(method: string, url: string, data?: string, headers?: any): mock.RequestHandler; - when(method: string, url: RegExp, data?: string, headers?: any): mock.RequestHandler; - when(method: string, url: string, data?: RegExp, headers?: any): mock.RequestHandler; - when(method: string, url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; - when(method: RegExp, url: string, data?: string, headers?: any): mock.RequestHandler; - when(method: RegExp, url: RegExp, data?: string, headers?: any): mock.RequestHandler; - when(method: RegExp, url: string, data?: RegExp, headers?: any): mock.RequestHandler; - when(method: RegExp, url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + when(method: string, url: string, data?: string, headers?: any): mock.IRequestHandler; + when(method: string, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + when(method: string, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + when(method: string, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + when(method: RegExp, url: string, data?: string, headers?: any): mock.IRequestHandler; + when(method: RegExp, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + when(method: RegExp, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + when(method: RegExp, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; - expectDELETE(url: string, headers?: any): mock.RequestHandler; - expectDELETE(url: RegExp, headers?: any): mock.RequestHandler; - expectGET(url: string, headers?: any): mock.RequestHandler; - expectGET(url: RegExp, headers?: any): mock.RequestHandler; - expectHEAD(url: string, headers?: any): mock.RequestHandler; - expectHEAD(url: RegExp, headers?: any): mock.RequestHandler; - expectJSONP(url: string): mock.RequestHandler; - expectJSONP(url: RegExp): mock.RequestHandler; - expectPATCH(url: string, data?: string, headers?: any): mock.RequestHandler; - expectPATCH(url: RegExp, data?: string, headers?: any): mock.RequestHandler; - expectPATCH(url: string, data?: RegExp, headers?: any): mock.RequestHandler; - expectPATCH(url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; - expectPOST(url: string, data?: string, headers?: any): mock.RequestHandler; - expectPOST(url: RegExp, data?: string, headers?: any): mock.RequestHandler; - expectPOST(url: string, data?: RegExp, headers?: any): mock.RequestHandler; - expectPOST(url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; - expectPUT(url: string, data?: string, headers?: any): mock.RequestHandler; - expectPUT(url: RegExp, data?: string, headers?: any): mock.RequestHandler; - expectPUT(url: string, data?: RegExp, headers?: any): mock.RequestHandler; - expectPUT(url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + expectDELETE(url: string, headers?: any): mock.IRequestHandler; + expectDELETE(url: RegExp, headers?: any): mock.IRequestHandler; + expectGET(url: string, headers?: any): mock.IRequestHandler; + expectGET(url: RegExp, headers?: any): mock.IRequestHandler; + expectHEAD(url: string, headers?: any): mock.IRequestHandler; + expectHEAD(url: RegExp, headers?: any): mock.IRequestHandler; + expectJSONP(url: string): mock.IRequestHandler; + expectJSONP(url: RegExp): mock.IRequestHandler; + expectPATCH(url: string, data?: string, headers?: any): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + expectPATCH(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + expectPOST(url: string, data?: string, headers?: any): mock.IRequestHandler; + expectPOST(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + expectPOST(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + expectPOST(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + expectPUT(url: string, data?: string, headers?: any): mock.IRequestHandler; + expectPUT(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + expectPUT(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + expectPUT(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; - whenDELETE(url: string, headers?: any): mock.RequestHandler; - whenDELETE(url: RegExp, headers?: any): mock.RequestHandler; - whenGET(url: string, headers?: any): mock.RequestHandler; - whenGET(url: RegExp, headers?: any): mock.RequestHandler; - whenHEAD(url: string, headers?: any): mock.RequestHandler; - whenHEAD(url: RegExp, headers?: any): mock.RequestHandler; - whenJSONP(url: string): mock.RequestHandler; - whenJSONP(url: RegExp): mock.RequestHandler; - whenPATCH(url: string, data?: string, headers?: any): mock.RequestHandler; - whenPATCH(url: RegExp, data?: string, headers?: any): mock.RequestHandler; - whenPATCH(url: string, data?: RegExp, headers?: any): mock.RequestHandler; - whenPATCH(url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; - whenPOST(url: string, data?: string, headers?: any): mock.RequestHandler; - whenPOST(url: RegExp, data?: string, headers?: any): mock.RequestHandler; - whenPOST(url: string, data?: RegExp, headers?: any): mock.RequestHandler; - whenPOST(url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; - whenPUT(url: string, data?: string, headers?: any): mock.RequestHandler; - whenPUT(url: RegExp, data?: string, headers?: any): mock.RequestHandler; - whenPUT(url: string, data?: RegExp, headers?: any): mock.RequestHandler; - whenPUT(url: RegExp, data?: RegExp, headers?: any): mock.RequestHandler; + whenDELETE(url: string, headers?: any): mock.IRequestHandler; + whenDELETE(url: RegExp, headers?: any): mock.IRequestHandler; + whenGET(url: string, headers?: any): mock.IRequestHandler; + whenGET(url: RegExp, headers?: any): mock.IRequestHandler; + whenHEAD(url: string, headers?: any): mock.IRequestHandler; + whenHEAD(url: RegExp, headers?: any): mock.IRequestHandler; + whenJSONP(url: string): mock.IRequestHandler; + whenJSONP(url: RegExp): mock.IRequestHandler; + whenPATCH(url: string, data?: string, headers?: any): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + whenPATCH(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPOST(url: string, data?: string, headers?: any): mock.IRequestHandler; + whenPOST(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + whenPOST(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPOST(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPUT(url: string, data?: string, headers?: any): mock.IRequestHandler; + whenPUT(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + whenPUT(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPUT(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; } export module mock { // returned interface by the the mocked HttpBackendService expect/when methods - export interface RequestHandler { + interface IRequestHandler { respond(func: Function): void; respond(status: number, data?: any, headers?: any): void; respond(data: any, headers?: any): void; diff --git a/Definitions/angular-resource-1.0.2.d.ts b/Definitions/angular-resource-1.0.2.d.ts index 0ae67e1b0..bfa071a03 100644 --- a/Definitions/angular-resource-1.0.2.d.ts +++ b/Definitions/angular-resource-1.0.2.d.ts @@ -17,12 +17,12 @@ module ng.resource { // actual implementation, since the documentation doesn't seem to cover // that deeply. /////////////////////////////////////////////////////////////////////////// - export interface ResourceService { - (url: string, paramDefaults?: any, actionDescriptors?: any): ResourceClass; + interface IResourceService { + (url: string, paramDefaults?: any, actionDescriptors?: any): IResourceClass; } // Just a reference to facilitate describing new actions - export interface ActionDescriptor { + interface IActionDescriptor { method: string; isArray?: bool; params?: any; @@ -32,34 +32,34 @@ module ng.resource { // Baseclass for everyresource with default actions. // If you define your new actions for the resource, you will need // to extend this interface and typecast the ResourceClass to it. - export interface ResourceClass { - get: ActionCall; - save: ActionCall; - query: ActionCall; - remove: ActionCall; - delete: ActionCall; + interface IResourceClass { + get: IActionCall; + save: IActionCall; + query: IActionCall; + remove: IActionCall; + delete: IActionCall; } // In case of passing the first argument as anything but a function, // it's gonna be considered data if the action method is POST, PUT or // PATCH (in other words, methods with body). Otherwise, it's going // to be considered as parameters to the request. - export interface ActionCall { - (): Resource; - (dataOrParams: any): Resource; - (dataOrParams: any, success: Function): Resource; - (success: Function, error?: Function): Resource; - (params: any, data: any, success?: Function, error?: Function): Resource; + interface IActionCall { + (): IResource; + (dataOrParams: any): IResource; + (dataOrParams: any, success: Function): IResource; + (success: Function, error?: Function): IResource; + (params: any, data: any, success?: Function, error?: Function): IResource; } - export interface Resource { - $save: ActionCall; - $remove: ActionCall; - $delete: ActionCall; + interface IResource { + $save: IActionCall; + $remove: IActionCall; + $delete: IActionCall; // No documented, but they are there, just as any custom action will be - $query: ActionCall; - $get: ActionCall; + $query: IActionCall; + $get: IActionCall; } } diff --git a/Definitions/angular-sanitize-1.0.2.d.ts b/Definitions/angular-sanitize-1.0.2.d.ts index 105a9d5ca..61885ae5e 100644 --- a/Definitions/angular-sanitize-1.0.2.d.ts +++ b/Definitions/angular-sanitize-1.0.2.d.ts @@ -14,7 +14,7 @@ module ng.sanitize { // SanitizeService // see http://docs.angularjs.org/api/ngSanitize.$sanitize /////////////////////////////////////////////////////////////////////////// - export interface SanitizeService { + interface ISanitizeService { (html: string): string; } From ed74ea087a2c882eee4be7f2e1c0ef39b277028a Mon Sep 17 00:00:00 2001 From: Diego Vilar Date: Thu, 25 Oct 2012 03:16:21 -0200 Subject: [PATCH 012/107] Moved AngularJS to the Complete section --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 805439189..fb57cb782 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ The project aims to provide *high quality* definitions for the most popular libr Complete -------- +* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) * [async](https://github.com/caolan/async) * [Backbone.js](http://backbonejs.org/) * [Bootstrap](http://twitter.github.com/bootstrap/) @@ -35,7 +36,6 @@ Complete Next ---- * Knockout.Mapping -* Angular.js * Facebook SDK * jQuery.Validate * jQuery Mobile From 7d669ccec8457c15fd666a62f92030d646e244eb Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Thu, 25 Oct 2012 09:01:48 +0300 Subject: [PATCH 013/107] Add AngularJS definitions --- Definitions/angular-1.0.2.d.ts | 639 ++++++++++++++++++++++++ Definitions/angular-cookies-1.0.2.d.ts | 29 ++ Definitions/angular-mocks-1.0.2.d.ts | 153 ++++++ Definitions/angular-resource-1.0.2.d.ts | 65 +++ Definitions/angular-sanitize-1.0.2.d.ts | 21 + README.md | 2 +- 6 files changed, 908 insertions(+), 1 deletion(-) create mode 100644 Definitions/angular-1.0.2.d.ts create mode 100644 Definitions/angular-cookies-1.0.2.d.ts create mode 100644 Definitions/angular-mocks-1.0.2.d.ts create mode 100644 Definitions/angular-resource-1.0.2.d.ts create mode 100644 Definitions/angular-sanitize-1.0.2.d.ts diff --git a/Definitions/angular-1.0.2.d.ts b/Definitions/angular-1.0.2.d.ts new file mode 100644 index 000000000..d5f9980c4 --- /dev/null +++ b/Definitions/angular-1.0.2.d.ts @@ -0,0 +1,639 @@ +// Type definitions for Angular JS 1.0.2 +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare var angular: ng.IAngularStatic; + +/////////////////////////////////////////////////////////////////////////////// +// ng module (angular.js) +/////////////////////////////////////////////////////////////////////////////// +module ng { + + // For the sake of simplicity, let's assume jQuery is always preferred + interface IJQLiteOrBetter extends JQuery { } + + // All service providers extend this interface + interface IServiceProvider { + $get(): any; + } + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // see http://docs.angularjs.org/api + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + bind(context: any, fn: Function, ...args: any[]): Function; + bootstrap(element: string, modules?: any[]): auto.IInjectorService; + bootstrap(element: IJQLiteOrBetter, modules?: any[]): auto.IInjectorService; + bootstrap(element: Element, modules?: any[]): auto.IInjectorService; + copy(source: any, destination?: any): any; + element: IJQLiteOrBetter; + equals(value1: any, value2: any): bool; + extend(destination: any, ...sources: any[]): any; + forEach(obj: any, iterator: (value, key) => any, context?: any): any; + fromJson(json: string): any; + identity(arg?: any): any; + injector(modules?: any[]): auto.IInjectorService; + isArray(value: any): bool; + isDate(value: any): bool; + isDefined(value: any): bool; + isElement(value: any): bool; + isFunction(value: any): bool; + isNumber(value: any): bool; + isObject(value: any): bool; + isString(value: any): bool; + isUndefined(value: any): bool; + lowercase(str: string): string; + module(name: string, requires?: string[], configFunction?: Function): IModule; + noop(...args: any[]): void; + toJson(obj: any, pretty?: bool): string; + uppercase(str: string): string; + version: { + full: string; + major: number; + minor: number; + dot: number; + codename: string; + }; + } + + /////////////////////////////////////////////////////////////////////////// + // Module + // see http://docs.angularjs.org/api/angular.Module + /////////////////////////////////////////////////////////////////////////// + interface IModule { + config(configFn: Function): IModule; + constant(name: string, value: any): IModule; + controller(name: string, controllerConstructor: Function): IModule; + controller(name: string, inlineAnnotadedConstructor: any[]): IModule; + directive(name: string, directiveFactory: Function): IModule; + factory(name: string, serviceFactoryFunction: Function): IModule; + filter(name: string, filterFactoryFunction: Function): IModule; + provider(name: string, serviceProviderConstructor: Function): IModule; + run(initializationFunction: Function): IModule; + service(name: string, serviceConstructor: Function): IModule; + value(name: string, value: any): IModule; + + // Properties + name: string; + requires: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // Attributes + // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes + /////////////////////////////////////////////////////////////////////////// + interface IAttributes { + $set(name: string, value: any): void; + $attr: any; + } + + /////////////////////////////////////////////////////////////////////////// + // FormController + // see http://docs.angularjs.org/api/ng.directive:form.FormController + /////////////////////////////////////////////////////////////////////////// + interface IFormController { + $pristine: bool; + $dirty: bool; + $valid: bool; + $invalid: bool; + $error: any; + } + + /////////////////////////////////////////////////////////////////////////// + // NgModelController + // see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController + /////////////////////////////////////////////////////////////////////////// + interface INgModelController { + $render(): void; + $setValidity(validationErrorKey: string, isValid: bool): void; + $setViewValue(value: string): void; + + // XXX Not sure about the types here. Documentation states it's a string, but + // I've seen it receiving other types throughout the code. + // Falling back to any for now. + $viewValue: any; + + // XXX Same as avove + $modelValue: any; + + $parsers: IModelParser[]; + $formatters: IModelFormatter[]; + $error: any; + $pristine: bool; + $dirty: bool; + $valid: bool; + $invalid: bool; + } + + interface IModelParser { + (value: any): any; + } + + interface IModelFormatter { + (value: any): any; + } + + /////////////////////////////////////////////////////////////////////////// + // Scope + // see http://docs.angularjs.org/api/ng.$rootScope.Scope + /////////////////////////////////////////////////////////////////////////// + interface IScope { + // Documentation says exp is optional, but actual implementaton counts on it + $apply(exp: string): any; + $apply(exp: (scope: IScope) => any): any; + + $broadcast(name: string, ...args: any[]): IAngularEvent; + $destroy(): void; + $digest(): void; + $emit(name: string, ...args: any[]): IAngularEvent; + + // Documentation says exp is optional, but actual implementaton counts on it + $eval(expression: string): any; + $eval(expression: (scope: IScope) => any): any; + + // Documentation says exp is optional, but actual implementaton counts on it + $evalAsync(expression: string): void; + $evalAsync(expression: (scope: IScope) => any): void; + + // Defaults to false by the implementation checking strategy + $new(isolate?: bool): IScope; + + $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + + $watch(watchExpression: string, listener?: string, objectEquality?: bool): Function; + $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: bool): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: bool): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: bool): Function; + + $id: number; + } + + interface IAngularEvent { + targetScope: IScope; + currentScope: IScope; + name: string; + preventDefault: Function; + defaultPrevented: bool; + + // Available only events that were $emit-ted + stopPropagation?: Function; + } + + /////////////////////////////////////////////////////////////////////////// + // WindowService + // see http://docs.angularjs.org/api/ng.$window + /////////////////////////////////////////////////////////////////////////// + interface IWindowService extends Window {} + + /////////////////////////////////////////////////////////////////////////// + // BrowserService + // TODO undocumented, so we need to get it from the source code + /////////////////////////////////////////////////////////////////////////// + interface IBrowserService {} + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ng.$timeout + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + (func: Function, delay?: number, invokeApply?: bool): IPromise; + cancel(promise: IPromise): bool; + } + + /////////////////////////////////////////////////////////////////////////// + // FilterService + // see http://docs.angularjs.org/api/ng.$filter + // see http://docs.angularjs.org/api/ng.$filterProvider + /////////////////////////////////////////////////////////////////////////// + interface IFilterService { + (name: string): Function; + } + + interface IFilterProvider extends IServiceProvider { + register(name: string, filterFactory: Function): IServiceProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // LocaleService + // see http://docs.angularjs.org/api/ng.$locale + /////////////////////////////////////////////////////////////////////////// + interface ILocaleService { + id: string; + + // These are not documented + // Check angular's i18n files for exemples + NUMBER_FORMATS: ILocaleNumberFormatDescriptor; + DATETIME_FORMATS: any; + pluralCat: (num: any) => string; + } + + interface ILocaleNumberFormatDescriptor { + DECIMAL_SEP: string; + GROUP_SEP: string; + PATTERNS: ILocaleNumberPatternDescriptor[]; + CURRENCY_SYM: string; + } + + interface ILocaleNumberPatternDescriptor { + minInt: number; + minFrac: number; + maxFrac: number; + posPre: string; + posSuf: string; + negPre: string; + negSuf: string; + gSize: number; + lgSize: number; + } + + interface ILacaleDateTimeFormatDescriptor { + MONTH: string[]; + SHORTMONTH: string[]; + DAY: string[]; + SHORTDAY: string[]; + AMPMS: string[]; + medium: string; + short: string; + fullDate: string; + longDate: string; + mediumDate: string; + shortDate: string; + mediumTime: string; + shortTime: string; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ng.$log + /////////////////////////////////////////////////////////////////////////// + interface ILogService { + error: ILogCall; + info: ILogCall; + log: ILogCall; + warn: ILogCall; + } + + // We define this as separete interface so we can reopen it later for + // the ngMock module. + interface ILogCall { + (...args: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // ParseService + // see http://docs.angularjs.org/api/ng.$parse + /////////////////////////////////////////////////////////////////////////// + interface IParseService { + (expression: string): ICompiledExpression; + } + + interface ICompiledExpression { + (context: any, locals?: any): any; + + // If value is not provided, undefined is gonna be used since the implementation + // does not check the parameter. Let's force a value for consistency. If consumer + // whants to undefine it, pass the undefined value explicitly. + assign(context: any, value: any): any; + } + + /////////////////////////////////////////////////////////////////////////// + // LocationService + // see http://docs.angularjs.org/api/ng.$location + // see http://docs.angularjs.org/api/ng.$locationProvider + // see http://docs.angularjs.org/guide/dev_guide.services.$location + /////////////////////////////////////////////////////////////////////////// + interface ILocationService { + absUrl(): string; + hash(): string; + hash(newHash: string): ILocationService; + host(): string; + path(): string; + path(newPath: string): ILocationService; + port(): number; + protocol(): string; + replace(): ILocationService; + search(): string; + search(parametersMap: any): ILocationService; + search(parameter: string, parameterValue: any): ILocationService; + url(): string; + url(url: string): ILocationService; + } + + interface ILocationProvider extends IServiceProvider { + hashPrefix(): string; + hashPrefix(prefix: string): ILocationProvider; + html5Mode(): bool; + + // Documentation states that parameter is string, but + // implementation tests it as boolean, which makes more sense + // since this is a toggler + html5Mode(active: bool): ILocationProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // DocumentService + // see http://docs.angularjs.org/api/ng.$document + /////////////////////////////////////////////////////////////////////////// + interface IDocumentService extends Document {} + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ng.$exceptionHandler + /////////////////////////////////////////////////////////////////////////// + interface IExceptionHandlerService { + (exception: Error, cause?: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // RootElementService + // see http://docs.angularjs.org/api/ng.$rootElement + /////////////////////////////////////////////////////////////////////////// + interface IRootElementService extends IJQLiteOrBetter {} + + /////////////////////////////////////////////////////////////////////////// + // QService + // see http://docs.angularjs.org/api/ng.$q + /////////////////////////////////////////////////////////////////////////// + interface IQService { + all(promises: IPromise[]): IPromise; + defer(): IDeferred; + reject(reason?: any): IPromise; + when(value: any): IPromise; + } + + interface IPromise { + then(successCallback: Function, errorCallback?: Function): IPromise; + } + + interface IDeferred { + resolve(value?: any): void; + reject(reason?: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // AnchorScrollService + // see http://docs.angularjs.org/api/ng.$anchorScroll + /////////////////////////////////////////////////////////////////////////// + interface IAnchorScrollService { + (): void; + } + + interface IAnchorScrollProvider extends IServiceProvider { + disableAutoScrolling(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CacheFactoryService + // see http://docs.angularjs.org/api/ng.$cacheFactory + /////////////////////////////////////////////////////////////////////////// + interface ICacheFactoryService { + // Lets not foce the optionsMap to have the capacity member. Even though + // it's the ONLY option considered by the implementation today, a consumer + // might find it useful to associate some other options to the cache object. + //(cacheId: string, optionsMap?: { capacity: number; }): CacheObject; + (cacheId: string, optionsMap?: { capacity: number; }): ICacheObject; + + // Methods bellow are not documented + info(): any; + get(cacheId: string): ICacheObject; + } + + interface ICacheObject { + info(): { + id: string; + size: number; + + // Not garanteed to have, since it's a non-mandatory option + //capacity: number; + }; + put(key: string, value?: any): void; + get(key: string): any; + remove(key: string): void; + removeAll(): void; + destroy(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CompileService + // see http://docs.angularjs.org/api/ng.$compile + // see http://docs.angularjs.org/api/ng.$compileProvider + /////////////////////////////////////////////////////////////////////////// + interface ICompileService { + (element: string, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: Element, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: IJQLiteOrBetter, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; + } + + interface ICompileProvider extends IServiceProvider { + directive(name: string, directiveFactory: Function): ICompileProvider; + + // Undocumented, but it is there... + directive(directivesMap: any): ICompileProvider; + } + + interface ITemplateLinkingFunction { + // Let's hint but not force cloneAttachFn's signature + (scope: IScope, cloneAttachFn?: (clonedElement?: IJQLiteOrBetter, scope?: IScope) => any): IJQLiteOrBetter; + } + + /////////////////////////////////////////////////////////////////////////// + // ControllerService + // see http://docs.angularjs.org/api/ng.$controller + // see http://docs.angularjs.org/api/ng.$controllerProvider + /////////////////////////////////////////////////////////////////////////// + interface IControllerService { + // Although the documentation doesn't state this, locals are optional + (controllerConstructor: Function, locals?: any): any; + (controllerName: string, locals?: any): any; + } + + interface IControlerPovider extends IServiceProvider { + register(name: string, controllerConstructor: Function): void; + register(name: string, dependencyAnnotadedConstructor: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpService + // see http://docs.angularjs.org/api/ng.$http + /////////////////////////////////////////////////////////////////////////// + interface IHttpService { + // At least moethod and url must be provided... + (config: IRequestConfig): IHttpPromise; + get(url: string, RequestConfig?: any): IHttpPromise; + delete(url: string, RequestConfig?: any): IHttpPromise; + head(url: string, RequestConfig?: any): IHttpPromise; + jsonp(url: string, RequestConfig?: any): IHttpPromise; + post(url: string, data: any, RequestConfig?: any): IHttpPromise; + put(url: string, data: any, RequestConfig?: any): IHttpPromise; + defaults: IRequestConfig; + + // For debugging, BUT it is documented as public, so... + pendingRequests: any[]; + } + + // This is just for hinting. + // Some opetions might not be available depending on the request. + // see http://docs.angularjs.org/api/ng.$http#Usage for options explanations + interface IRequestConfig { + method: string; + url: string; + params?: any; + + // XXX it has it's own structure... perhaps we should define it in the future + headers?: any; + + cache?: any; + timeout?: number; + withCredentials?: bool; + + // These accept multiple types, so let's defile them as any + data?: any; + transformRequest?: any; + transformResponse?: any; + } + + interface IHttpPromise extends IPromise { + success(callback: (response: IDestructuredResponse) => any): IHttpPromise; + error(callback: (response: IDestructuredResponse) => any): IHttpPromise; + } + + interface IDestructuredResponse { + data: any; + status: number; + headers: (headerName: string) => string; + config: IRequestConfig; + } + + interface IHttpProvider extends IServiceProvider { + defaults: IRequestConfig; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ng.$httpBackend + // You should never need to use this service directly. + /////////////////////////////////////////////////////////////////////////// + interface IHttpBackendService { + // XXX Perhaps define callback signature in the future + (method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: bool); void; + } + + /////////////////////////////////////////////////////////////////////////// + // InterpolateService + // see http://docs.angularjs.org/api/ng.$interpolate + // see http://docs.angularjs.org/api/ng.$interpolateProvider + /////////////////////////////////////////////////////////////////////////// + interface IInterpolateService { + (text: string, mustHaveExpression?: bool): IInterpolationFunction; + endSymbol(): string; + startSymbol(): string; + } + + interface IInterpolationFunction { + (context: any): string; + } + + interface IInterpolateProvider extends IServiceProvider { + startSymbol(): string; + startSymbol(value: string): IInterpolateProvider; + endSymbol(): string; + endSymbol(value: string): IInterpolateProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // RouteParamsService + // see http://docs.angularjs.org/api/ng.$routeParams + /////////////////////////////////////////////////////////////////////////// + interface IRouteParamsService {} + + /////////////////////////////////////////////////////////////////////////// + // TemplateCacheService + // see http://docs.angularjs.org/api/ng.$templateCache + /////////////////////////////////////////////////////////////////////////// + interface ITemplateCacheService extends ICacheObject {} + + /////////////////////////////////////////////////////////////////////////// + // RootScopeService + // see http://docs.angularjs.org/api/ng.$rootScope + /////////////////////////////////////////////////////////////////////////// + interface IRootScopeService extends IScope {} + + /////////////////////////////////////////////////////////////////////////// + // RouteService + // see http://docs.angularjs.org/api/ng.$route + // see http://docs.angularjs.org/api/ng.$routeProvider + /////////////////////////////////////////////////////////////////////////// + interface IRouteService { + reload(): void; + routes: any; + + // May not always be available. For instance, current will not be available + // to a controller that was not initialized as a result of a route maching. + current?: ICurrentRoute; + } + + // see http://docs.angularjs.org/api/ng.$routeProvider#when for options explanations + interface IRoute { + controller?: any; + template?: string; + templateUrl?: string; + resolve?: any; + redirectTo?: any; + reloadOnSearch?: bool; + } + + // see http://docs.angularjs.org/api/ng.$route#current + interface ICurrentRoute extends IRoute { + locals: { + $scope: IScope; + $template: string; + }; + } + + interface IRouteProviderProvider extends IServiceProvider { + otherwise(params: any): IRouteProviderProvider; + when(path: string, route: IRoute): IRouteProviderProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // AUTO module (angular.js) + /////////////////////////////////////////////////////////////////////////// + export module auto { + + /////////////////////////////////////////////////////////////////////// + // InjectorService + // see http://docs.angularjs.org/api/AUTO.$injector + /////////////////////////////////////////////////////////////////////// + interface IInjectorService { + annotate(fn: Function): string[]; + annotate(inlineAnnotadedFunction: any[]): string[]; + get(name: string): any; + instantiate(typeConstructor: Function, locals?: any): any; + invoke(func: Function, context?: any, locals?: any): any; + } + + /////////////////////////////////////////////////////////////////////// + // ProvideService + // see http://docs.angularjs.org/api/AUTO.$provide + /////////////////////////////////////////////////////////////////////// + interface IProvideService { + // Documentation says it returns the registered instance, but actual + // implementation does not return anything. + // constant(name: string, value: any): any; + constant(name: string, value: any): void; + + decorator(name: string, decorator: Function): void; + factory(name: string, serviceFactoryFunction: Function): ng.IServiceProvider; + provider(name: string, provider: ng.IServiceProvider): ng.IServiceProvider; + provider(name: string, serviceProviderConstructor: Function): ng.IServiceProvider; + service(name: string, constructor: Function): ng.IServiceProvider; + value(name: string, value: any): ng.IServiceProvider; + } + + } + +} diff --git a/Definitions/angular-cookies-1.0.2.d.ts b/Definitions/angular-cookies-1.0.2.d.ts new file mode 100644 index 000000000..39e878efc --- /dev/null +++ b/Definitions/angular-cookies-1.0.2.d.ts @@ -0,0 +1,29 @@ +// Type definitions for Angular JS 1.0.2 (ngCookies module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/////////////////////////////////////////////////////////////////////////////// +// ngCookies module (angular-cookies.js) +/////////////////////////////////////////////////////////////////////////////// +module ng.cookies { + + /////////////////////////////////////////////////////////////////////////// + // CookieService + // see http://docs.angularjs.org/api/ngCookies.$cookies + /////////////////////////////////////////////////////////////////////////// + interface ICookiesService {} + + /////////////////////////////////////////////////////////////////////////// + // CookieStoreService + // see http://docs.angularjs.org/api/ngCookies.$cookieStore + /////////////////////////////////////////////////////////////////////////// + interface ICookieStoreService { + get(key: string): any; + put(key: string, value: any): void; + remove(key: string): void; + } + +} diff --git a/Definitions/angular-mocks-1.0.2.d.ts b/Definitions/angular-mocks-1.0.2.d.ts new file mode 100644 index 000000000..55f0e951b --- /dev/null +++ b/Definitions/angular-mocks-1.0.2.d.ts @@ -0,0 +1,153 @@ +// Type definitions for Angular JS 1.0.2 (ngMock, ngMockE2E module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/////////////////////////////////////////////////////////////////////////////// +// ngMock module (angular-mocks.js) +/////////////////////////////////////////////////////////////////////////////// +module ng { + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // We reopen it to add the MockStatic definition + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + mock: IMockStatic; + } + + interface IMockStatic { + // see http://docs.angularjs.org/api/angular.mock.debug + debug(obj: any): string; + + // see http://docs.angularjs.org/api/angular.mock.inject + inject(...fns: Function[]): void; + + // see http://docs.angularjs.org/api/angular.mock.module + module(...modules: any[]): any; + + // see http://docs.angularjs.org/api/angular.mock.TzDate + TzDate(offset: number, timestamp: number): Date; + TzDate(offset: number, timestamp: string): Date; + } + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ngMock.$exceptionHandler + // see http://docs.angularjs.org/api/ngMock.$exceptionHandlerProvider + /////////////////////////////////////////////////////////////////////////// + interface IExceptionHandlerProvider extends IServiceProvider { + mode(mode: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ngMock.$timeout + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + flush(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ngMock.$log + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface ILogService { + assertEmpty(): void; + reset(): void; + } + + interface LogCall { + logs: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ngMock.$httpBackend + /////////////////////////////////////////////////////////////////////////// + interface IHttpBackendService { + flush(count: number): void; + resetExpectations(): void; + verifyNoOutstandingExpectation(): void; + verifyNoOutstandingRequest(): void; + + expect(method: string, url: string, data?: string, headers?: any): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + expect(method: string, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + expect(method: RegExp, url: string, data?: string, headers?: any): mock.IRequestHandler; + expect(method: RegExp, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + expect(method: RegExp, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + expect(method: RegExp, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + + when(method: string, url: string, data?: string, headers?: any): mock.IRequestHandler; + when(method: string, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + when(method: string, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + when(method: string, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + when(method: RegExp, url: string, data?: string, headers?: any): mock.IRequestHandler; + when(method: RegExp, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + when(method: RegExp, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + when(method: RegExp, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + + expectDELETE(url: string, headers?: any): mock.IRequestHandler; + expectDELETE(url: RegExp, headers?: any): mock.IRequestHandler; + expectGET(url: string, headers?: any): mock.IRequestHandler; + expectGET(url: RegExp, headers?: any): mock.IRequestHandler; + expectHEAD(url: string, headers?: any): mock.IRequestHandler; + expectHEAD(url: RegExp, headers?: any): mock.IRequestHandler; + expectJSONP(url: string): mock.IRequestHandler; + expectJSONP(url: RegExp): mock.IRequestHandler; + expectPATCH(url: string, data?: string, headers?: any): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + expectPATCH(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + expectPOST(url: string, data?: string, headers?: any): mock.IRequestHandler; + expectPOST(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + expectPOST(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + expectPOST(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + expectPUT(url: string, data?: string, headers?: any): mock.IRequestHandler; + expectPUT(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + expectPUT(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + expectPUT(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + + whenDELETE(url: string, headers?: any): mock.IRequestHandler; + whenDELETE(url: RegExp, headers?: any): mock.IRequestHandler; + whenGET(url: string, headers?: any): mock.IRequestHandler; + whenGET(url: RegExp, headers?: any): mock.IRequestHandler; + whenHEAD(url: string, headers?: any): mock.IRequestHandler; + whenHEAD(url: RegExp, headers?: any): mock.IRequestHandler; + whenJSONP(url: string): mock.IRequestHandler; + whenJSONP(url: RegExp): mock.IRequestHandler; + whenPATCH(url: string, data?: string, headers?: any): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + whenPATCH(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPOST(url: string, data?: string, headers?: any): mock.IRequestHandler; + whenPOST(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + whenPOST(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPOST(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPUT(url: string, data?: string, headers?: any): mock.IRequestHandler; + whenPUT(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + whenPUT(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPUT(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + } + + export module mock { + + // returned interface by the the mocked HttpBackendService expect/when methods + interface IRequestHandler { + respond(func: Function): void; + respond(status: number, data?: any, headers?: any): void; + respond(data: any, headers?: any): void; + + // Available wehn ngMockE2E is loaded + passThrough(): void; + } + + } + +} diff --git a/Definitions/angular-resource-1.0.2.d.ts b/Definitions/angular-resource-1.0.2.d.ts new file mode 100644 index 000000000..1e18c0ae1 --- /dev/null +++ b/Definitions/angular-resource-1.0.2.d.ts @@ -0,0 +1,65 @@ +// Type definitions for Angular JS 1.0.2 (ngResource module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/////////////////////////////////////////////////////////////////////////////// +// ngResource module (angular-resource.js) +/////////////////////////////////////////////////////////////////////////////// +module ng.resource { + + /////////////////////////////////////////////////////////////////////////// + // ResourceService + // see http://docs.angularjs.org/api/ngResource.$resource + // Most part of the following definitions were achieved by analyzing the + // actual implementation, since the documentation doesn't seem to cover + // that deeply. + /////////////////////////////////////////////////////////////////////////// + interface IResourceService { + (url: string, paramDefaults?: any, actionDescriptors?: any): IResourceClass; + } + + // Just a reference to facilitate describing new actions + interface IActionDescriptor { + method: string; + isArray?: bool; + params?: any; + headers?: any; + } + + // Baseclass for everyresource with default actions. + // If you define your new actions for the resource, you will need + // to extend this interface and typecast the ResourceClass to it. + interface IResourceClass { + get: IActionCall; + save: IActionCall; + query: IActionCall; + remove: IActionCall; + delete: IActionCall; + } + + // In case of passing the first argument as anything but a function, + // it's gonna be considered data if the action method is POST, PUT or + // PATCH (in other words, methods with body). Otherwise, it's going + // to be considered as parameters to the request. + interface IActionCall { + (): IResource; + (dataOrParams: any): IResource; + (dataOrParams: any, success: Function): IResource; + (success: Function, error?: Function): IResource; + (params: any, data: any, success?: Function, error?: Function): IResource; + } + + interface IResource { + $save: IActionCall; + $remove: IActionCall; + $delete: IActionCall; + + // No documented, but they are there, just as any custom action will be + $query: IActionCall; + $get: IActionCall; + } + +} diff --git a/Definitions/angular-sanitize-1.0.2.d.ts b/Definitions/angular-sanitize-1.0.2.d.ts new file mode 100644 index 000000000..3d1ef40bd --- /dev/null +++ b/Definitions/angular-sanitize-1.0.2.d.ts @@ -0,0 +1,21 @@ +// Type definitions for Angular JS 1.0.2 (ngSanitize module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/////////////////////////////////////////////////////////////////////////////// +// ngSanitize module (angular-sanitize.js) +/////////////////////////////////////////////////////////////////////////////// +module ng.sanitize { + + /////////////////////////////////////////////////////////////////////////// + // SanitizeService + // see http://docs.angularjs.org/api/ngSanitize.$sanitize + /////////////////////////////////////////////////////////////////////////// + interface ISanitizeService { + (html: string): string; + } + +} diff --git a/README.md b/README.md index 304086ecc..96045e042 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ The project aims to provide *high quality* definitions for the most popular libr Complete -------- +* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) * [async](https://github.com/caolan/async) * [Backbone.js](http://backbonejs.org/) * [Bootstrap](http://twitter.github.com/bootstrap/) @@ -38,7 +39,6 @@ Next ---- * Knockout.Mapping * Chosen -* Angular.js * Facebook SDK * jQuery.Validate * google.visualization From 8f55214b52e999b4d7dec9d2bc77da1178af981d Mon Sep 17 00:00:00 2001 From: Diego Vilar Date: Thu, 25 Oct 2012 12:07:00 -0300 Subject: [PATCH 014/107] Added promise property for the ng.IDeferred interface Signed-off-by: Diego Vilar --- Definitions/angular-1.0.2.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/Definitions/angular-1.0.2.d.ts b/Definitions/angular-1.0.2.d.ts index 73d491507..d91dea74b 100644 --- a/Definitions/angular-1.0.2.d.ts +++ b/Definitions/angular-1.0.2.d.ts @@ -372,6 +372,7 @@ module ng { interface IDeferred { resolve(value?: any): void; reject(reason?: string): void; + promise: IPromise; } /////////////////////////////////////////////////////////////////////////// From 44d6bdc5ee402fe60f9a364a2e165333696c7e9a Mon Sep 17 00:00:00 2001 From: Diego Vilar Date: Thu, 25 Oct 2012 13:10:27 -0200 Subject: [PATCH 015/107] Added link for AngularJS definitions wiki page --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fb57cb782..cdfddcfcb 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ The project aims to provide *high quality* definitions for the most popular libr Complete -------- -* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) +* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](wiki/AngularJS-Definitions-Usage-Notes)) * [async](https://github.com/caolan/async) * [Backbone.js](http://backbonejs.org/) * [Bootstrap](http://twitter.github.com/bootstrap/) From 81b81c1e63504c4fea8cf02e9680de352328c0fd Mon Sep 17 00:00:00 2001 From: Diego Vilar Date: Thu, 25 Oct 2012 13:11:56 -0200 Subject: [PATCH 016/107] Relative wiki link was not a good idea --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cdfddcfcb..157804e36 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ The project aims to provide *high quality* definitions for the most popular libr Complete -------- -* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](wiki/AngularJS-Definitions-Usage-Notes)) +* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes)) * [async](https://github.com/caolan/async) * [Backbone.js](http://backbonejs.org/) * [Bootstrap](http://twitter.github.com/bootstrap/) From 50138dabc41a3643f3657d893a725ca9f3735d78 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Thu, 25 Oct 2012 22:07:30 +0300 Subject: [PATCH 017/107] Add Knockout.mapping --- .../{knockout-2.1.d.ts => knockout-2.2.d.ts} | 0 Definitions/knockoutmapping-2.0.d.ts | 29 +++++++++++++++++++ README.md | 2 +- 3 files changed, 30 insertions(+), 1 deletion(-) rename Definitions/{knockout-2.1.d.ts => knockout-2.2.d.ts} (100%) create mode 100644 Definitions/knockoutmapping-2.0.d.ts diff --git a/Definitions/knockout-2.1.d.ts b/Definitions/knockout-2.2.d.ts similarity index 100% rename from Definitions/knockout-2.1.d.ts rename to Definitions/knockout-2.2.d.ts diff --git a/Definitions/knockoutmapping-2.0.d.ts b/Definitions/knockoutmapping-2.0.d.ts new file mode 100644 index 000000000..2b3b412f9 --- /dev/null +++ b/Definitions/knockoutmapping-2.0.d.ts @@ -0,0 +1,29 @@ +// Type definitions for Knockout.Mapping 2.0 +// Project: https://github.com/SteveSanderson/knockout.mapping +// https://github.com/borisyankov/DefinitelyTyped + +interface KnockoutMappingOptions { + ignore; + include; + copy; + mappedProperties; + deferEvaluation; +} + +interface KnockoutMapping { + isMapped(viewModel: any): bool; + fromJS(jsObject: any): any; + fromJS(jsObject: any, targetOrOptions: any): any; + fromJS(jsObject: any, inputOptions: any, target: any): any; + fromJSON(jsonString: string): any; + toJS(rootObject: any, options?: KnockoutMappingOptions): any; + toJSON(rootObject: any, options?: KnockoutMappingOptions): any; + defaultOptions(): KnockoutMappingOptions; + resetDefaultOptions(): void; + getType(x: any): any; + visitModel(rootObject: any, callback: Function, options?: { visitedObjects?; parentName?; ignore?; copy?; include?; } ): any; +} + +interface KnockoutStatic { + mapping: KnockoutMapping; +} \ No newline at end of file diff --git a/README.md b/README.md index 96045e042..46fec6a23 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ Complete * [jQuery Mobile](http://jquerymobile.com) * [jQuery UI](http://jqueryui.com/) * [Knockout.js](http://knockoutjs.com/) +* [Knockout.Mapping](https://github.com/SteveSanderson/knockout.mapping) * [Modernizr](http://modernizr.com/) * [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) * [Mustache.js](https://github.com/janl/mustache.js) @@ -37,7 +38,6 @@ Complete Next ---- -* Knockout.Mapping * Chosen * Facebook SDK * jQuery.Validate From be38ab26f90776b8ab9071e51e464b1bd2028a44 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Thu, 25 Oct 2012 22:07:42 +0300 Subject: [PATCH 018/107] Update Knockout definitons and file version + tests --- Definitions/knockout-2.2.d.ts | 161 +++++++---- Tests/knockout-tests.ts | 517 ++++++++++++++++++++++++++++++++++ 2 files changed, 626 insertions(+), 52 deletions(-) create mode 100644 Tests/knockout-tests.ts diff --git a/Definitions/knockout-2.2.d.ts b/Definitions/knockout-2.2.d.ts index 639aa4159..cf346a778 100644 --- a/Definitions/knockout-2.2.d.ts +++ b/Definitions/knockout-2.2.d.ts @@ -1,6 +1,12 @@ -// Type definitions for Knockout 2.1.0 +// Type definitions for Knockout 2.2 +// Project: http://knockoutjs.com // https://github.com/borisyankov/DefinitelyTyped + +interface KnockoutSubscription { + dispose(): void; +} + interface KnockoutObservableArrayFunctions { // General Array functions indexOf(searchElement, fromIndex?: number): number; @@ -26,23 +32,33 @@ interface KnockoutObservableArrayFunctions { } interface KnockoutObservableArray extends KnockoutObservableArrayFunctions { - (): any[]; - (value: any[]): void; -} -interface KnockoutObservableArrayStatic { - (): KnockoutObservableArray; fn: KnockoutObservableArrayFunctions; + + (): KnockoutObservableArray; + (value: any[]): KnockoutObservableArray; } interface KnockoutObservable { + + fn; + (): any; (value): void; - subscribe(func: Function): void; + extend(source); + subscribe(func: Function): KnockoutSubscription; } interface KnockoutComputed extends KnockoutObservable { + (): KnockoutComputed; + (func: Function, context?: any): KnockoutComputed; + (def: KnockoutComputedDefine): KnockoutComputed; + (options?: any): KnockoutComputed; + + subscribe(callback: (newValue: number) => void ): KnockoutSubscription; + getDependenciesCount(): number; + hasWriteFunction(): bool; } interface KnockoutComputedDefine { @@ -50,12 +66,6 @@ interface KnockoutComputedDefine { write(any); } -interface KnockoutComputedStatic { - (): KnockoutComputed; - (func: Function): KnockoutComputed; - (def: KnockoutComputedDefine) : KnockoutComputed; -} - interface KnockoutBindingContext { $parent: any; $parents: any[]; @@ -72,55 +82,102 @@ interface KnockoutBindingHandler { //update(element: any, valueAccessor: any, allBindingsAccessor: any, viewModel: any, bindingContext: KnockoutBindingContext) : void; init: any; update: any; + options: any; } interface KnockoutBindingHandlers { value: KnockoutBindingHandler; } -interface KnockoutStatic { - utils: KnockoutUtilsStatic; - bindingHandlers: KnockoutBindingHandlers; - applyBindings(viewModel, rootNode?); - computed : KnockoutComputedStatic; - observableArray: KnockoutObservableArrayStatic; - observable(intial?): KnockoutObservable; +interface KnockoutMemoization { + memoize(callback); + unmemoize(memoId, callbackParams); + unmemoizeDomNodeAndDescendants(domNode, extraCallbackParamsArray); + parseMemoText(memoText); } -interface KnockoutUtilsStatic { - arrayForEach(array: any[], action); - arrayIndexOf(array: any[], item); - arrayFirst(array: any[], predicate, predicateOwner?); - arrayRemoveItem(array: any[], itemToRemove); - arrayGetDistinctValues(array: any[]); - arrayMap(array: any[], mapping); - arrayFilter(array: any[], predicate); - arrayPushAll(array: any[], valuesToPush); +interface KnockoutVirtualElements { + allowedBindings; + emptyNode; + firstChild; + insertAfter; + nextSibling; + prepend; + setDomNodeChildren; +} + +interface KnockoutExtenders { + throttle(target: any, timeout: number): KnockoutComputed; + notify(target: any, notifyWhen: string): any; +} + +interface KnockoutUtils { + + fieldsIncludedWithJsonPost: any[]; + + arrayForEach(array: any[], action: (any) => void ): void; + arrayIndexOf(array: any[], item: any): number; + arrayFirst(array: any[], predicate: (item) => bool, predicateOwner?: any): any; + arrayRemoveItem(array: any[], itemToRemove: any): void; + arrayGetDistinctValues(array: any[]): any[]; + arrayMap(array: any[], mapping: (item) => any): any[]; + arrayFilter(array: any[], predicate: (item) => bool): any[]; + arrayPushAll(array: any[], valuesToPush: any[]): any[]; + extend(target, source); - emptyDomNode(domNode); - moveCleanedNodesToContainerElement(nodes); - setDomNodeChildren(domNode, childNodes); - replaceDomNodes(nodeToReplaceOrNodeArray, newNodesArray); - setOptionNodeSelectionState(optionNode, isSelected); - stringTrim(str: string); - stringTokenize(str: string, delimiter); - stringStartsWith(str: string, startsWith); - buildEvalWithinScopeFunction(expression, scopeLevels); - domNodeIsContainedBy(node, containedByNode); - domNodeIsAttachedToDocument(node); - tagNameLower(element); - registerEventHandler(element, eventType, handler); - triggerEvent(element, eventType); - unwrapObservable(value); - toggleDomNodeCssClass(node, className, shouldHaveClass); - setTextContent(element, textContent); + + emptyDomNode(domNode): void; + moveCleanedNodesToContainerElement(nodes: any[]): HTMLElement; + cloneNodes(nodesArray: any[], shouldCleanNodes: bool): any[]; + setDomNodeChildren(domNode: any, childNodes: any[]): void; + replaceDomNodes(nodeToReplaceOrNodeArray: any, newNodesArray: any[]): void; + setOptionNodeSelectionState(optionNode: any, isSelected: bool): void; + stringTrim(str: string): string; + stringTokenize(str: string, delimiter: string): string; + stringStartsWith(str: string, startsWith: string): string; + domNodeIsContainedBy(node: any, containedByNode: any): bool; + domNodeIsAttachedToDocument(node: any): bool; + tagNameLower(element: any): string; + registerEventHandler(element: any, eventType: any, handler: Function): void; + triggerEvent(element: any, eventType: any): void; + unwrapObservable(value: any): any; + toggleDomNodeCssClass(node: any, className: string, shouldHaveClass: bool): void; + setTextContent(element: any, textContent: string): void; + setElementName(element: any, name: string): void; ensureSelectElementIsRenderedCorrectly(selectElement); - range(min, max); - makeArray(arrayLikeObject); - getFormFields(form, fieldName); - parseJson(jsonString); - stringifyJson(data, replacer, space); - postJson(urlOrForm, data, options); + forceRefresh(node: any): void; + ensureSelectElementIsRenderedCorrectly(selectElement: any): void; + range(min: any, max: any): any; + makeArray(arrayLikeObject: any): any[]; + getFormFields(form: any, fieldName: string): any[]; + parseJson(jsonString: string): any; + stringifyJson(data: any, replacer: Function, space: string): string; + postJson(urlOrForm: any, data: any, options: any): void; + + domNodeDisposal; +} + + +interface KnockoutStatic { + utils: KnockoutUtils; + memoization: KnockoutMemoization; + bindingHandlers: KnockoutBindingHandlers; + + computed: KnockoutComputed; + observableArray: KnockoutObservableArray; + virtualElements: KnockoutVirtualElements; + extenders: KnockoutExtenders; + + applyBindings(viewModel: any, rootNode?: any): void; + applyBindingsToDescendants(viewModel: any, rootNode: any): void; + observable(intial? ): KnockoutObservable; + contextFor(node: any): any; + isSubscribable(instance: any): bool; + subscribable(): void; + toJSON(viewModel: any, replacer?: Function, space?: any): string; + toJS(viewModel: any): any; + isObservable(instance: any): bool; + dataFor(node: any): any; } declare var ko: KnockoutStatic; \ No newline at end of file diff --git a/Tests/knockout-tests.ts b/Tests/knockout-tests.ts new file mode 100644 index 000000000..a2c7e8d8d --- /dev/null +++ b/Tests/knockout-tests.ts @@ -0,0 +1,517 @@ +/// +/// + +declare var $; + +function test_creatingVMs() { + var myViewModel = { + personName: ko.observable('Bob'), + personAge: ko.observable(123) + }; + ko.applyBindings(myViewModel); + ko.applyBindings(myViewModel, document.getElementById('someElementId')); + + myViewModel.personName(); + myViewModel.personName('Mary'); + myViewModel.personName('Mary').personAge(50); + + myViewModel.personName.subscribe(function (newValue) { + alert("The person's new name is " + newValue); + }); + + var subscription = myViewModel.personName.subscribe(function (newValue) { }); + subscription.dispose(); +} + +function test_computed() { + function AppViewModel() { + var self = this; + + self.firstName = ko.observable('Bob'); + self.lastName = ko.observable('Smith'); + self.fullName = ko.computed(function () { + return self.firstName() + " " + self.lastName(); + }); + } + + function MyViewModel() { + this.firstName = ko.observable('Planet'); + this.lastName = ko.observable('Earth'); + + this.fullName = ko.computed({ + read: function () { + return this.firstName() + " " + this.lastName(); + }, + write: function (value) { + var lastSpacePos = value.lastIndexOf(" "); + if (lastSpacePos > 0) { + this.firstName(value.substring(0, lastSpacePos)); + this.lastName(value.substring(lastSpacePos + 1)); + } + }, + owner: this + }); + } + + function MyViewModel() { + this.price = ko.observable(25.99); + + this.formattedPrice = ko.computed({ + read: function () { + return '$' + this.price().toFixed(2); + }, + write: function (value) { + value = parseFloat(value.replace(/[^\.\d]/g, "")); + this.price(isNaN(value) ? 0 : value); + }, + owner: this + }); + } + + function MyViewModel() { + this.acceptedNumericValue = ko.observable(123); + this.lastInputWasValid = ko.observable(true); + + this.attemptedValue = ko.computed({ + read: this.acceptedNumericValue, + write: function (value) { + if (isNaN(value)) + this.lastInputWasValid(false); + else { + this.lastInputWasValid(true); + this.acceptedNumericValue(value); + } + }, + owner: this + }); + } + + ko.applyBindings(new MyViewModel()); +} + + +function test_observableArrays() { + var myObservableArray = ko.observableArray(); + myObservableArray.push('Some value'); + var anotherObservableArray = ko.observableArray([ + { name: "Bungle", type: "Bear" }, + { name: "George", type: "Hippo" }, + { name: "Zippy", type: "Unknown" } + ]); + + myObservableArray().length; + myObservableArray()[0]; + + myObservableArray.indexOf('Blah'); + myObservableArray.push('Some new value'); + myObservableArray.pop(); + myObservableArray.unshift('Some new value'); + myObservableArray.shift(); + myObservableArray.reverse(); + myObservableArray.sort(function (left, right) { return left.lastName == right.lastName ? 0 : (left.lastName < right.lastName ? -1 : 1) }); + myObservableArray.splice(1, 3); + + var someItem: KnockoutObservableArray; + myObservableArray.remove(someItem); + myObservableArray.remove(function (item) { return item.age < 18 }); + myObservableArray.removeAll(['Chad', 132, undefined]); + myObservableArray.removeAll(); + myObservableArray.destroy(someItem); + myObservableArray.destroy(function (someItem) { return someItem.age < 18 }); + myObservableArray.destroyAll(['Chad', 132, undefined]); + myObservableArray.destroyAll(); +} + +function test_bindings() { + var currentProfit = ko.observable(150000); + ko.applyBindings({ + people: [ + { firstName: 'Bert', lastName: 'Bertington' }, + { firstName: 'Charles', lastName: 'Charlesforth' }, + { firstName: 'Denise', lastName: 'Dentiste' } + ] + }); + var viewModel = { availableCountries: ko.observableArray(['France', 'Germany', 'Spain']) }; + viewModel.availableCountries.push('China'); + + ko.bindingHandlers.yourBindingName = { + init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + }, + update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + } + }; + ko.bindingHandlers.slideVisible = { + update: function (element, valueAccessor, allBindingsAccessor) { + var value = valueAccessor(), allBindings = allBindingsAccessor(); + var valueUnwrapped = ko.utils.unwrapObservable(value); + var duration = allBindings.slideDuration || 400; + if (valueUnwrapped == true) + $(element).slideDown(duration); + else + $(element).slideUp(duration); + }, + init: function (element, valueAccessor) { + var value = ko.utils.unwrapObservable(valueAccessor()); + $(element).toggle(value); + }, + update: function (element, valueAccessor, allBindingsAccessor) { + } + }; + ko.bindingHandlers.hasFocus = { + init: function (element, valueAccessor) { + $(element).focus(function () { + var value = valueAccessor(); + value(true); + }); + $(element).blur(function () { + var value = valueAccessor(); + value(false); + }); + }, + update: function (element, valueAccessor) { + var value = valueAccessor(); + if (ko.utils.unwrapObservable(value)) + element.focus(); + else + element.blur(); + } + }; + ko.bindingHandlers.allowBindings = { + init: function (elem, valueAccessor) { + var shouldAllowBindings = ko.utils.unwrapObservable(valueAccessor()); + return { controlsDescendantBindings: !shouldAllowBindings }; + } + }; + ko.bindingHandlers.withProperties = { + init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var newProperties = valueAccessor(), + innerBindingContext = bindingContext.extend(newProperties); + ko.applyBindingsToDescendants(innerBindingContext, element); + return { controlsDescendantBindings: true }; + } + }; + ko.bindingHandlers.withProperties = { + init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var newProperties = valueAccessor(), + childBindingContext = bindingContext.createChildContext(viewModel); + ko.utils.extend(childBindingContext, newProperties); + ko.applyBindingsToDescendants(childBindingContext, element); + return { controlsDescendantBindings: true }; + } + }; + ko.bindingHandlers.randomOrder = { + init: function (elem, valueAccessor) { + var child = ko.virtualElements.firstChild(elem), + childElems = []; + while (child) { + childElems.push(child); + child = ko.virtualElements.nextSibling(child); + } + ko.virtualElements.emptyNode(elem); + while (childElems.length) { + var randomIndex = Math.floor(Math.random() * childElems.length), + chosenChild = childElems.splice(randomIndex, 1); + ko.virtualElements.prepend(elem, chosenChild[0]); + } + } + }; + + var node, containerElem, nodeToInsert, insertAfter, nodeToPrepend, arrayOfNodes; + ko.virtualElements.allowedBindings.mySuperBinding = true; + ko.virtualElements.emptyNode(containerElem); + ko.virtualElements.firstChild(containerElem); + ko.virtualElements.insertAfter(containerElem, nodeToInsert, insertAfter); + ko.virtualElements.nextSibling(node); + ko.virtualElements.prepend(containerElem, nodeToPrepend); + ko.virtualElements.setDomNodeChildren(containerElem, arrayOfNodes); +} + +function test_more() { + var viewModel = { + firstName: ko.observable("Bert"), + lastName: ko.observable("Smith"), + pets: ko.observableArray(["Cat", "Dog", "Fish"]), + type: "Customer", + hasALotOfPets: any + }; + viewModel.hasALotOfPets = ko.computed(function () { + return this.pets().length > 2 + }, viewModel); + var plainJs = ko.toJS(viewModel); + + ko.extenders.logChange = function (target, option) { + target.subscribe(function (newValue) { + console.log(option + ": " + newValue); + }); + return target; + }; + + ko.extenders.numeric = function (target, precision) { + var result = ko.computed({ + read: target, + write: function (newValue) { + var current = target(), + roundingMultiplier = Math.pow(10, precision), + newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue), + valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier; + + if (valueToWrite !== current) { + target(valueToWrite); + } else { + if (newValue !== current) { + target.notifySubscribers(valueToWrite); + } + } + } + }); + + result(target()); + + return result; + }; + + function AppViewModel(one, two) { + this.myNumberOne = ko.observable(one).extend({ numeric: 0 }); + this.myNumberTwo = ko.observable(two).extend({ numeric: 2 }); + } + + ko.applyBindings(new AppViewModel(221.2234, 123.4525)); + + ko.extenders.required = function (target, overrideMessage) { + + target.hasError = ko.observable(); + target.validationMessage = ko.observable(); + + function validate(newValue) { + target.hasError(newValue ? false : true); + target.validationMessage(newValue ? "" : overrideMessage || "This field is required"); + } + + validate(target()); + + target.subscribe(validate); + + return target; + }; + + function AppViewModel(first, last) { + this.firstName = ko.observable(first).extend({ required: "Please enter a first name" }); + this.lastName = ko.observable(last).extend({ required: "" }); + } + + ko.applyBindings(new AppViewModel("Bob", "Smith")); + + var first; + this.firstName = ko.observable(first).extend({ required: "Please enter a first name", logChange: "first name" }); + + var upperCaseName = ko.computed(function () { + return name().toUpperCase(); + }).extend({ throttle: 500 }); + + function AppViewModel() { + this.instantaneousValue = ko.observable(); + this.throttledValue = ko.computed(this.instantaneousValue) + .extend({ throttle: 400 }); + + this.loggedValues = ko.observableArray([]); + this.throttledValue.subscribe(function (val) { + if (val !== '') + this.loggedValues.push(val); + }, this); + } + + function GridViewModel() { + this.pageSize = ko.observable(20); + this.pageIndex = ko.observable(1); + this.currentPageData = ko.observableArray(); + + ko.computed(function () { + var params = { page: this.pageIndex(), size: this.pageSize() }; + $.getJSON('/Some/Json/Service', params, this.currentPageData); + }, this); + } + this.setPageSize = function (newPageSize) { + this.pageSize(newPageSize); + this.pageIndex(1); + } + + ko.computed(function () { + var params = { page: this.pageIndex(), size: this.pageSize() }; + $.getJSON('/Some/Json/Service', params, this.currentPageData); + }, this).extend({ throttle: 1 }); + + $(".remove").click(function () { + viewModel.items.remove(ko.dataFor(this)); + }); + $(".remove").live("click", function () { + viewModel.items.remove(ko.dataFor(this)); + }); + + $("#people").delegate(".remove", "click", function () { + + var context = ko.contextFor(this), + parentArray = context.$parent.people || context.$parent.children; + + parentArray.remove(context.$data); + + return false; + }); + $("#people").delegate(".add", "click", function () { + var context = ko.contextFor(this), + childName = context.$data.name() + " child", + parentArray = context.$data.people || context.$data.children; + + context.$root.addChild(childName, parentArray); + + return false; + }); + ko.observableArray.fn.filterByProperty = function (propName, matchValue) { + return ko.computed(function () { + var allItems = this(), matchingItems = []; + for (var i = 0; i < allItems.length; i++) { + var current = allItems[i]; + if (ko.utils.unwrapObservable(current[propName]) === matchValue) + matchingItems.push(current); + } + return matchingItems; + }, this); + } + function Task(title, done) { + this.title = ko.observable(title); + this.done = ko.observable(done); + } + + function AppViewModel() { + this.tasks = ko.observableArray([ + new Task('Find new desktop background', true), + new Task('Put shiny stickers on laptop', false), + new Task('Request more reggae music in the office', true) + ]); + + this.doneTasks = this.tasks.filterByProperty("done", true); + } + + ko.applyBindings(new AppViewModel()); + this.doneTasks = ko.computed(function () { + var all = this.tasks(), done = []; + for (var i = 0; i < all.length; i++) + if (all[i].done()) + done.push(all[i]); + return done; + }, this); +} + +function test_mappingplugin() { + var viewModel = { + serverTime: ko.observable(), + numUsers: ko.observable() + } + var data = { + serverTime: '2010-01-07', + numUsers: 3 + }; + viewModel.serverTime(data.serverTime); + viewModel.numUsers(data.numUsers); + + var viewModel = ko.mapping.fromJS(data); + ko.mapping.fromJS(data, viewModel); + var unmapped = ko.mapping.toJS(viewModel); + + var viewModel = ko.mapping.fromJS(data); + ko.mapping.fromJS(data, viewModel); + + var myChildModel = function (data) { + ko.mapping.fromJS(data, {}, this); + + this.nameLength = ko.computed(function () { + return this.name().length; + }, this); + } + + var oldOptions = ko.mapping.defaultOptions().include; + ko.mapping.defaultOptions().include = ["alwaysIncludeThis"]; + + var oldOptions = ko.mapping.defaultOptions().copy; + ko.mapping.defaultOptions().copy = ["alwaysCopyThis"]; + + var someObject; + ko.mapping.fromJS(data, {}, someObject); + ko.mapping.fromJS(data, {}, this); + + var alice, aliceMappingOptions, bob, bobMappingOptions; + var viewModel = ko.mapping.fromJS(alice, aliceMappingOptions); + ko.mapping.fromJS(bob, bobMappingOptions, viewModel); + + var obj; + var result = ko.mapping.fromJS(obj, { + key: function (item) { + return ko.utils.unwrapObservable(item.id); + } + }); + + result.mappedRemove({ id: 2 }); + var newItem = result.mappedCreate({ id: 3 }); +} + +function test_misc() { + var postbox = new ko.subscribable(); + postbox.subscribe(callback, target, topic); + + postbox.subscribe(function (newValue) { + this.latestTopic(newValue); + }, vm, "mytopic"); + postbox.notifySubscribers(value, "mytopic"); + + ko.subscribable.fn.publishOn = function (topic) { + this.subscribe(function (newValue) { + postbox.notifySubscribers(newValue, topic); + }); + + return this; + }; + + this.myObservable = ko.observable("myValue").publishOn("myTopic"); + + ko.subscribable.fn.subscribeTo = function (topic) { + postbox.subscribe(this, null, topic); + + return this; + }; + + this.observableFromAnotherVM = ko.observable().subscribeTo("myTopic"); + + postbox.subscribe(function (newValue) { + this(newValue); + }, this, topic); + + ko.bindingHandlers.isolatedOptions = { + init: function (element, valueAccessor) { + var args = arguments; + ko.computed({ + read: function () { + ko.utils.unwrapObservable(valueAccessor()); + ko.bindingHandlers.options.update.apply(this, args); + }, + owner: this, + disposeWhenNodeIsRemoved: element + }); + } + }; + + ko.subscribable.fn.publishOn = function (topic) { + this.subscribe(function (newValue) { + postbox.notifySubscribers(newValue, topic); + }); + + return this; + }; + + this.myObservable = ko.observable("myValue").publishOn("myTopic"); + + var x = ko.observableArray([1, 2, 3]); + + var element; + ko.utils.domNodeDisposal.addDisposeCallback(element, function () { + $(element).datepicker("destroy"); + }); +} \ No newline at end of file From f3fe394a6aa2c449c08e5592909f87b49790c501 Mon Sep 17 00:00:00 2001 From: Blake Niemyjski Date: Thu, 25 Oct 2012 14:45:34 -0500 Subject: [PATCH 019/107] Update Definitions/knockout-2.2.d.ts Added subscribe method to the ko observablearray. --- Definitions/knockout-2.2.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Definitions/knockout-2.2.d.ts b/Definitions/knockout-2.2.d.ts index cf346a778..598669a24 100644 --- a/Definitions/knockout-2.2.d.ts +++ b/Definitions/knockout-2.2.d.ts @@ -21,6 +21,8 @@ interface KnockoutObservableArrayFunctions { sort(): void; sort(compareFunction): void; + subscribe(callback: (newValue: any[]) => void ): KnockoutSubscription; + // Ko specific remove(item): any[]; removeAll(items: any[]): any[]; From 106ba3b252d803240f997ea968ae823412c9a5a9 Mon Sep 17 00:00:00 2001 From: Esben Nepper Date: Fri, 26 Oct 2012 08:48:05 +0200 Subject: [PATCH 020/107] Added definition for Google Maps v3 Almost complete only missing a few of the add on libraries. --- Definitions/google.maps.d.ts | 1253 ++++++++++++++++++++++++++++++++++ 1 file changed, 1253 insertions(+) create mode 100644 Definitions/google.maps.d.ts diff --git a/Definitions/google.maps.d.ts b/Definitions/google.maps.d.ts new file mode 100644 index 000000000..8ca60c205 --- /dev/null +++ b/Definitions/google.maps.d.ts @@ -0,0 +1,1253 @@ +declare module google.maps { + + /***** MVC *****/ + export class MVCObject { + constructor (); + bindTo(key: string, target: MVCObject, targetKey?: string, noNotify?: bool): void; + changed(key: string): void; + get(key: string): any; + notify(key: string): void; + set(key: string, value: any): void; + setValues(values: any): void; + unbind(key: string): void; + unbindAll(): void; + } + + export class MVCArray { + constructor (array?: any[]); + clear(): void; + forEach(callback: (elem: any, index: number) => void ): void; + getArray(): any[]; + getAt(i: number): any; + getLength(): number; + insertAt(i: number, elem: any): void; + pop(): void; + push(elem: any): number; + removeAt(i: number): any; + setAt(i: number, elem: any): void; + } + + /***** Map *****/ + export class Map extends MVCObject { + constructor (mapDiv: Element, opts?: MapOptions); + fitBounds(bounds: LatLngBounds); + getBounds(): LatLngBounds; + getCenter(): LatLng; + getDiv(): Element; + getHeading(): number; + getMapTypeId(): MapTypeId; + getProjection(): Projection; + getStreetView(): StreetViewPanorama; + getTilt(): number; + getZoom(): number; + panBy(x: number, y: number): void; + panTo(latLng: LatLng): void; + panToBounds(latLngBounds: LatLngBounds): void; + setCenter(latlng: LatLng): void; + setHeading(heading: number): void; + setMapTypeId(mapTypeId: MapTypeId): void; + setOptions(options: MapOptions): void; + setStreetView(panorama: StreetViewPanorama): void; + setTilt(tilt: number): void; + setZoom(zoom: number): void; + } + + export interface MapOptions { + backgroundColor?: string; + center?: LatLng; + disableDefaultUI?: bool; + disableDoubleClickZoom?: bool; + draggable?: bool; + draggableCursor?: string; + draggingCursor?: string; + heading?: number; + keyboardShortcuts?: bool; + mapMaker?: bool; + mapTypeControl?: bool; + mapTypeControlOptions?: MapTypeControlOptions; + mapTypeId?: MapTypeId; + maxZoom?: number; + minZoom?: number; + noClear?: bool; + overviewMapControl?: bool; + overviewMapControlOptions?: OverviewMapControlOptions; + panControl?: bool; + panControlOptions?: PanControlOptions; + rotateControl?: bool; + rotateControlOptions?: RotateControlOptions; + scaleControl?: bool; + scaleControlOptions?: ScaleControlOptions; + scrollwheel?: bool; + streetView?: bool; + streetViewControlOptions?: StreetViewControlOptions; + styles?: MapTypeStyle[]; + tilt?: number; + zoom?: number; + zoomControl?: bool; + zoomControlOptions?: ZoomControlOptions; + } + + export enum MapTypeId { + HYBRID, + ROADMAP, + SATELLITE, + TERRAIN + } + + /***** Controls *****/ + export interface MapTypeControlOptions { + mapTypeIds?: MapTypeId[]; + position?: ControlPosition; + style?: MapTypeControlStyle; + } + + export enum MapTypeControlStyle { + DEFAULT, + DROPDOWN_MENU, + HORIZONTAL_BAR + } + + export interface OverviewMapControlOptions { + opened?: bool; + } + + export interface PanControlOptions { + position: ControlPosition; + } + + export interface RotateControlOptions { + position: ControlPosition; + } + + export interface ScaleControlOptions { + position?: ControlPosition; + style?: ScaleControlStyle; + } + + export enum ScaleControlStyle { + DEFAULT + } + + export interface StreetViewControlOptions { + position: ControlPosition; + } + + export interface ZoomControlOptions { + position?: ControlPosition; + style?: ZoomControlStyle; + } + + export enum ZoomControlStyle { + DEFAULT, + LARGE, + SMALL + } + + export enum ControlPosition { + BOTTOM_CENTER, + BOTTOM_LEFT, + BOTTOM_RIGHT, + LEFT_BOTTOM, + LEFT_CENTER, + LEFT_TOP, + RIGHT_BOTTOM, + RIGHT_CENTER, + RIGHT_TOP, + TOP_CENTER, + TOP_LEFT, + TOP_RIGHT + } + + /***** Overlays *****/ + export class Marker extends MVCObject { + constructor (opts?: MarkerOptions); + getAnimation(): Animation; + getClickable(): bool; + getCursor(): string; + getDraggable(): bool; + getFlat(): bool; + getIcon(): MarkerImage; + getMap(): Map; + getMap(): StreetViewPanorama; + getPosition(): LatLng; + getShadow(): MarkerImage; + getShape(): MarkerShape; + getTitle(): string; + getVisible(): bool; + getZIndex(): number; + setAnimation(animation: Animation): void; + setClickable(flag: bool): void; + setCursor(cursor: string): void; + setDraggable(flag: bool): void; + setFlat(flag: bool): void; + setIcon(icon: MarkerImage): void; + setIcon(icon: string): void; + setMap(map: Map): void; + setMap(map: StreetViewPanorama): void; + setOptions(options: MarkerOptions): void; + setPosition(latlng: LatLng): void; + setShadow(shadow: MarkerImage): void; + setShadow(shadow: string): void; + setShape(shape: MarkerShape): void; + setTitle(title: string): void; + setVisible(visible: bool): void; + setZIndex(zIndex: number): void; + } + + export interface MarkerOptions { + animation?: Animation; + clickable?: bool; + cursor?: string; + draggable?: bool; + flat?: bool; + icon?: any; + map?: any; + optimized?: bool; + position?: LatLng; + raiseOnDrag?: bool; + shadow?: any; + shape?: MarkerShape; + title?: string; + visible?: bool; + zIndex?: number; + } + + export class MarkerImage { + constructor (url: string, size?: Size, origin?: Point, anchor?: Point, scaledSize?: Size); + anchor: Point; + origin: Point; + scaledSize: Size; + size: Size; + url: string; + } + + export interface MarkerShape { + coords?: number[]; + type?: string; + } + + export interface Symbol { + anchor?: Point; + fillColor?: string; + fillOpacity?: number; + path?: any; + rotation?: number; + scale?: number; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + } + + export enum SymbolPath { + BACKWARD_CLOSED_ARROW, + BACKWARD_OPEN_ARROW, + CIRCLE, + FORWARD_CLOSED_ARROW, + FORWARD_OPEN_ARROW + } + + export enum Animation { + BOUNCE, + DROP + } + + export class InfoWindow extends MVCObject { + constructor (opts?: InfoWindowOptions); + close(): void; + getContent(): string; + getContent(): Element; + getPosition(): LatLng; + getZIndex(): number; + open(map?: Map, anchor?: MVCObject): void; + open(map?: StreetViewPanorama, anchor?: MVCObject): void; + setContent(content: Node): void; + setContent(content: string): void; + setOptions(options: InfoWindowOptions): void; + setPosition(position: LatLng): void; + setZIndex(zIndex: number): void; + } + + export interface InfoWindowOptions { + content?: any; + disableAutoPan?: bool; + maxWidth?: number; + pixelOffset?: Size; + position?: LatLng; + zIndex?: number; + } + + export class Polyline extends MVCObject { + constructor (opts?: PolylineOptions); + getEditable(): bool; + getMap(): Map; + getPath(): MVCArray[]; + getVisible(): bool; + setEditable(editable: bool): void; + setMap(map: Map): void; + setOptions(options: PolylineOptions): void; + setPath(path: MVCArray[]): void; + setPath(path: LatLng[]): void; + setVisible(visible: bool): void; + } + + export interface PolylineOptions { + clickable?: bool; + editable?: bool; + geodesic?: bool; + icons?: IconSequence[]; + map?: Map; + path?: any[]; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + visible?: bool; + zIndex?: number; + } + + export interface IconSequence { + icon?: Symbol; + offset?: string; + repeat?: string; + } + + export class Polygon extends MVCObject { + constructor (opts?: PolygonOptions); + getEditable(): bool; + getMap(): Map; + getPath(): MVCArray[]; + getPaths(): MVCArray[][]; + getVisible(): bool; + setEditable(editable: bool): void; + setMap(map: Map): void; + setOptions(options: PolygonOptions): void; + setPath(path: MVCArray[]): void; + setPath(path: LatLng[]): void; + setPaths(paths: MVCArray[]): void; + setPaths(paths: MVCArray[][]): void; + setPaths(path: LatLng[]): void; + setPaths(path: LatLng[][]): void; + setVisible(visible: bool): void; + } + + export interface PolygonOptions { + clickable?: bool; + editable?: bool; + fillColor?: string; + fillOpacity?: number; + geodesic?: bool; + map?: Map; + paths?: any[]; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + visible?: bool; + zIndex?: number; + } + + export interface PolyMouseEvent { + edge?: number; + path?: number; + vertex?: number; + } + + export class Rectangle extends MVCObject { + constructor (opts?: RectangleOptions); + getBounds(): LatLngBounds; + getEditable(): bool; + getMap(): Map; + getVisible(): bool; + setBounds(bounds: LatLngBounds): void; + setEditable(editable: bool): void; + setMap(map: Map): void; + setOptions(options: RectangleOptions): void; + setVisible(visible: bool): void; + } + + export interface RectangleOptions { + bounds?: LatLngBounds; + clickable?: bool; + editable?: bool; + fillColor?: string; + fillOpacity?: number; + map?: Map; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + visible?: bool; + zIndex?: number; + } + + export class Circle extends MVCObject { + constructor (opts?: CircleOptions); + getBounds(): LatLngBounds; + getCenter(): LatLng; + getEditable(): bool; + getMap(): Map; + getRadius(): number; + getVisible(): bool; + setCenter(center: LatLng): void; + setEditable(editable: bool): void; + setMap(map: Map): void; + setOptions(options: CircleOptions): void; + setRadius(radius: number): void; + setVisible(visible: bool): void; + } + + export interface CircleOptions { + center?: LatLng; + clickable?: bool; + editable?: bool; + fillColor?: string; + fillOpacity?: number; + map?: Map; + radius?: number; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + visible?: bool; + zIndex?: number; + } + + export class GroundOverlay extends MVCObject { + constructor (url: string, bounds: LatLngBounds, opts?: GroundOverlayOptions); + getBounds(): LatLngBounds; + getMap(): Map; + getOpacity(): number; + getUrl(): string; + setMap(map: Map): void; + setOpacity(opacity: number): void; + } + + export interface GroundOverlayOptions { + clickable?: bool; + map?: Map; + opacity?: number; + } + + export class OverlayView extends MVCObject { + draw(): void; + getMap(): Map; + getPanes(): MapPanes; + getProjection(): MapCanvasProjection; + onAdd(): void; + onRemove(): void; + setMap(map: Map): void; + setMap(map: StreetViewPanorama): void; + } + + export interface MapPanes { + floatPane: Element; + floatShadow: Element; + mapPane: Element; + overlayImage: Element; + overlayLayer: Element; + overlayMouseTarget: Element; + overlayShadow: Element; + } + + export class MapCanvasProjection extends MVCObject { + fromContainerPixelToLatLng(pixel: Point, nowrap?: bool): LatLng; + fromDivPixelToLatLng(pixel: Point, nowrap?: bool): LatLng; + fromLatLngToContainerPixel(latLng: LatLng): Point; + fromLatLngToDivPixel(latLng: LatLng): Point; + getWorldWidth(): number; + } + + /***** Services *****/ + export class Geocoder { + constructor (); + geocode(request: GeocoderRequest, callback: (results: GeocoderResult[], status: GeocoderStatus) => void ): void; + } + + export interface GeocoderRequest { + address: string; + bounds?: LatLngBounds; + location?: LatLng; + region?: string; + } + + export enum GeocoderStatus { + ERROR, + INVALID_REQUEST, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + export interface GeocoderResult { + address_components: GeocoderAddressComponent[]; + formatted_address: string; + geometry: GeocoderGeometry; + types: string[]; + } + + export interface GeocoderAddressComponent { + long_name: string; + short_name: string; + types: string[]; + } + + export interface GeocoderGeometry { + bounds: LatLngBounds; + location: LatLng; + location_type: GeocoderLocationType; + viewport: LatLngBounds; + } + + export enum GeocoderLocationType { + APPROXIMATE, + GEOMETRIC_CENTER, + RANGE_INTERPOLATED, + ROOFTOP + } + + export class DirectionsRenderer extends MVCObject { + constructor (opts?: DirectionsRendererOptions); + getDirections(): DirectionsResult; + getMap(): Map; + getPanel(): Element; + getRouteIndex(): number; + setDirections(directions: DirectionsResult): void; + setMap(map: Map): void; + setOptions(options: DirectionsRendererOptions): void; + setPanel(panel: Element): void; + setRouteIndex(routeIndex: number): void; + } + + export interface DirectionsRendererOptions { + directions?: DirectionsResult; + draggable?: bool; + hideRouteList?: bool; + infoWindow?: InfoWindow; + map?: Map; + markerOptions?: MarkerOptions; + panel?: Element; + polylineOptions?: PolylineOptions; + preserveViewport?: bool; + routeIndex?: number; + suppressBicyclingLayer?: bool; + suppressInfoWindows?: bool; + suppressMarkers?: bool; + suppressPolylines?: bool; + } + + export class DirectionsService { + constructor (); + route(request: DirectionsRequest, callback: (result: DirectionsResult, status: DirectionsStatus) => void ): void; + } + + export interface DirectionsRequest { + avoidHighways?: bool; + avoidTolls?: bool; + destination?: any; + optimizeWaypoints?: bool; + origin?: any; + provideRouteAlternatives?: bool; + region?: string; + transitOptions?: TransitOptions; + travelMode?: TravelMode; + unitSystem?: UnitSystem; + waypoints?: DirectionsWaypoint[]; + } + + export enum TravelMode { + BICYCLING, + DRIVING, + TRANSIT, + WALKING + } + + export enum UnitSystem { + IMPERIAL, + METRIC + } + + export interface TransitOptions { + arrivalTime?: Date; + departureTime?: Date; + } + + export interface DirectionsWaypoint { + location: any; + stopover: bool; + } + + export enum DirectionsStatus { + INVALID_REQUEST, + MAX_WAYPOINTS_EXCEEDED, + NOT_FOUND, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + export interface DirectionsResult { + routes: DirectionsRoute[]; + } + + export interface DirectionsRoute { + bounds: LatLngBounds; + copyrights: string; + legs: DirectionsLeg[]; + overview_path: LatLng[]; + warnings: string[]; + waypoint_order: number[]; + } + + export interface DirectionsLeg { + arrival_time: Distance; + departure_time: Duration; + distance: Distance; + duration: Duration; + end_address: string; + end_location: LatLng; + start_address: string; + start_location: LatLng; + steps: DirectionsStep[]; + via_waypoints: LatLng[]; + } + + export interface DirectionsStep { + distance: Distance; + duration: Duration; + end_location: LatLng; + instructions: string; + path: LatLng[]; + start_location: LatLng; + steps: DirectionsStep; + transit: TransitDetails; + travel_mode: TravelMode; + } + + export interface Distance { + text: string; + value: number; + } + + export interface Duration { + text: string; + value: number; + } + + export interface Time { + text: string; + time_zone: string; + value: Date; + } + + export interface TransitDetails { + arrival_stop: TransitStop; + arrival_time: Time; + departure_stop: TransitStop; + departure_time: Time; + headsign: string; + headway: number; + line: TransitLine; + num_stops: number; + } + + export interface TransitStop { + location: LatLng; + name: string; + } + + export interface TransitLine { + agencies: TransitAgency[]; + color: string; + icon: string; + name: string; + short_name: string; + text_color: string; + url: string; + vehicle: TransitVehicle; + } + + export interface TransitAgency { + name: string; + phone: string; + url: string; + } + + export interface TransitVehicle { + icon: string; + local_icon: string; + name: string; + type: string; + } + + export class ElevationService { + constructor (); + getElevationAlongPath(request: PathElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; + getElevationForLocations(request: LocationElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; + } + + export interface LocationElevationRequest { + locations: LatLng[]; + } + + export interface PathElevationRequest { + path?: LatLng[]; + samples?: number; + } + + export interface ElevationResult { + elevation: number; + location: LatLng; + resolution: number; + } + + export enum ElevationStatus { + INVALID_REQUEST, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR + } + + export class MaxZoomService { + constructor (); + getMaxZoomAtLatLng(latlng: LatLng, callback: (result: MaxZoomResult) => void ): void; + } + + export interface MaxZoomResult { + status: MaxZoomStatus; + zoom: number; + } + + export enum MaxZoomStatus { + ERROR, + OK + } + + export class DistanceMatrixService { + constructor (); + getDistanceMatrix(request: DistanceMatrixRequest, callback: (response: DistanceMatrixResponse, status: DistanceMatrixStatus) => void ): void; + } + + export interface DistanceMatrixRequest { + avoidHighways?: bool; + avoidTolls?: bool; + destinations?: any[]; + origins?: any[]; + region?: string; + travelMode?: TravelMode; + unitSystem?: UnitSystem; + } + + export interface DistanceMatrixResponse { + destinationAddresses: string[]; + originAddresses: string[]; + rows: DistanceMatrixResponseRow[]; + } + + export interface DistanceMatrixResponseRow { + elements: DistanceMatrixResponseElement[]; + } + + export interface DistanceMatrixResponseElement { + distance: Distance; + duration: Duration; + status: DistanceMatrixElementStatus; + } + + export enum DistanceMatrixStatus { + INVALID_REQUEST, + MAX_DIMENSIONS_EXCEEDED, + MAX_ELEMENTS_EXCEEDED, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR + } + + export enum DistanceMatrixElementStatus { + NOT_FOUND, + OK, + ZERO_RESULTS + } + + /***** Map Types *****/ + export interface MapType { + getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; + releaseTile(tile: Element): void; + alt?: string; + maxZoom?: number; + minZoom?: number; + name?: string; + projection?: Projection; + radius?: number; + tileSize?: Size; + } + + export class MapTypeRegistry extends MVCObject { + constructor (); + set(id: string, mapType: MapType): void; + } + + export interface Projection { + fromLatLngToPoint(latLng: LatLng, point?: Point): Point; + fromPointToLatLng(pixel: Point, noWrap?: bool): LatLng; + } + + export class ImageMapType { + constructor (opts: ImageMapTypeOptions); + getOpacity(): number; + setOpacity(opacity: number): void; + } + + export interface ImageMapTypeOptions { + alt?: string; + getTileUrl: (Point, number) => string; + maxZoom?: number; + minZoom?: number; + name?: string; + opacity?: number; + tileSize?: Size; + } + + export class StyledMapType { + constructor (styles: MapTypeStyle[], options?: StyledMapTypeOptions); + } + + export interface StyledMapTypeOptions { + alt?: string; + maxZoom?: number; + minZoom?: number; + name?: string; + } + + export interface MapTypeStyle { + elementType?: MapTypeStyleElementType; + featureType?: MapTypeStyleFeatureType; + stylers?: MapTypeStyler[]; + } + + export interface MapTypeStyleFeatureType { + administrative?: { + country?: string; + land_parcel?: string; + locality?: string; + neighborhood?: string; + province?: string; + }; + all?: string; + landscape?: { + man_made?: string; + natural?: string; + }; + poi?: { + attraction?: string; + business?: string; + government?: string; + medical?: string; + park?: string; + place_of_worship?: string; + school?: string; + sports_complex?: string; + }; + road?: { + arterial?: string; + highway?: { + controlled_access?: string; + }; + local?: string; + }; + transit?: { + line?: string; + station?: { + airport?: string; + bus?: string; + rail?: string; + }; + }; + water?: string; + } + + export enum MapTypeStyleElementType { + all, + geometry, + labels + } + + export interface MapTypeStyler { + gamma?: number; + hue?: string; + invert_lightness?: bool; + lightness?: number; + saturation?: number; + visibility?: string; + } + + /***** Layers *****/ + export class BicyclingLayer extends MVCObject { + constructor (); + getMap(): Map; + setMap(map: Map): void; + } + + export class FusionTablesLayer extends MVCObject { + constructor (options: FusionTablesLayerOptions); + getMap(): Map; + setMap(map: Map): void; + setOptions(options: FusionTablesLayerOptions): void; + } + + export interface FusionTablesLayerOptions { + clickable?: bool; + heatmap?: FusionTablesHeatmap; + map?: Map; + query?: FusionTablesQuery; + styles?: FusionTablesStyle[]; + suppressInfoWindows?: bool; + } + + export interface FusionTablesQuery { + from?: string; + limit?: number; + offset?: number; + orderBy?: string; + select?: string; + where?: string; + } + + export interface FusionTablesStyle { + markerOptions?: FusionTablesMarkerOptions; + polygonOptions?: FusionTablesPolygonOptions; + polylineOptions?: FusionTablesPolylineOptions; + where?: string; + } + + export interface FusionTablesHeatmap { + enabled: bool; + } + + export interface FusionTablesMarkerOptions { + iconName: string; + } + + export interface FusionTablesPolygonOptions { + fillColor?: string; + fillOpacity?: number; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + } + + export interface FusionTablesPolylineOptions { + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + } + + export interface FusionTablesMouseEvent { + infoWindowHtml: string; + latLng: LatLng; + pixelOffset: Size; + row: Object; + } + + export interface FusionTablesCell { + columnName: string; + value: string; + } + + export class KmlLayer extends MVCObject { + constructor (url: string, opts?: KmlLayerOptions); + getDefaultViewport(): LatLngBounds; + getMap(): Map; + getMetadata(): KmlLayerMetadata; + getStatus(): KmlLayerStatus; + getUrl(): string; + setMap(map: Map): void; + } + + export interface KmlLayerOptions { + clickable?: bool; + map?: Map; + preserveViewport?: bool; + suppressInfoWindows?: bool; + } + + export interface KmlLayerMetadata { + author: KmlAuthor; + description: string; + name: string; + snippet: string; + } + + export enum KmlLayerStatus { + DOCUMENT_NOT_FOUND, + DOCUMENT_TOO_LARGE, + FETCH_ERROR, + INVALID_DOCUMENT, + INVALID_REQUEST, + LIMITS_EXCEEDED, + OK, + TIMED_OUT, + UNKNOWN + } + + export interface KmlMouseEvent { + featureData: KmlFeatureData; + latLng: LatLng; + pixelOffset: Size; + } + + export interface KmlFeatureData { + author: KmlAuthor; + description: string; + id: string; + infoWindowHtml: string; + name: string; + snippet: string; + } + + export interface KmlAuthor { + email: string; + name: string; + uri: string; + } + + export class TrafficLayer extends MVCObject { + constructor (); + getMap(): void; + setMap(map: Map): void; + } + + export class TransitLayer extends MVCObject { + constructor (); + getMap(): void; + setMap(map: Map): void; + } + + /***** Street View *****/ + export class StreetViewPanorama { + constructor (container: Element, opts?: StreetViewPanoramaOptions); + controls: MVCArray[]; + getLinks(): StreetViewLink[]; + getPano(): string; + getPosition(): LatLng; + getPov(): StreetViewPov; + getVisible(): bool; + registerPanoProvider(provider: (input: string) => StreetViewPanoramaData); + setPano(pano: string): void; + setPosition(latLng: LatLng): void; + setPov(pov: StreetViewPov): void; + setVisible(flag: bool): void; + + } + + export interface StreetViewPanoramaOptions { + addressControl?: bool; + addressControlOptions?: StreetViewAddressControlOptions; + clickToGo?: bool; + disableDoubleClickZoom?: bool; + enableCloseButton?: bool; + imageDateControl?: bool; + linksControl?: bool; + panControl?: bool; + panControlOptions?: PanControlOptions; + pano?: string; + panoProvider?: (input: string) => StreetViewPanoramaData; + position?: LatLng; + pov?: StreetViewPov; + scrollwheel?: bool; + visible?: bool; + zoomControl?: bool; + zoomControlOptions?: ZoomControlOptions; + } + + export interface StreetViewAddressControlOptions { + position: ControlPosition; + } + + export interface StreetViewLink { + description?: string; + heading?: number; + pano?: string; + } + + export interface StreetViewPov { + heading?: number; + picth?: number; + zoom?: number; + } + + export interface StreetViewPanoramaData { + opyright?: string; + imageDate?: string; + links?: StreetViewLink[]; + location?: StreetViewLocation; + tiles?: StreetViewTileData; + } + + export interface StreetViewLocation { + description?: string; + latLng?: LatLng; + pano?: string; + } + + export interface StreetViewTileData { + centerHeading?: number; + tileSize?: Size; + worldSize?: Size; + } + + export interface StreetViewService { + getPanoramaById(pano: string, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void ); + getPanoramaByLocation(latlng: LatLng, radius: number, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void ); + } + + export enum StreetViewStatus { + OK, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + /***** Base *****/ + export class LatLng { + constructor (lat: number, lng: number, noWrap?: bool); + equals(other: LatLng): bool; + lat(): number; + lng(): number; + toString(): string; + toUrlValue(precision?: number): string; + + } + + export class LatLngBounds { + constructor (sw?: LatLng, ne?: LatLng); + contains(latLng: LatLng): bool; + equals(other: LatLngBounds): bool; + extend(point: LatLng): LatLngBounds; + getCenter(): LatLng; + getNorthEast(): LatLng; + getSouthWest(): LatLng; + intersects(other: LatLngBounds): bool; + isEmpty(): bool; + toSpan(): LatLng; + toString(): string; + toUrlValue(precision?: number): string; + union(other: LatLngBounds): LatLngBounds; + } + + export class Point { + constructor (x: number, y: number); + x: number; + y: number; + equals(other: Point): bool; + toString(): string; + } + + export class Size { + constructor (width: number, height: number, widthUnit?: string, heightUnit?: string); + height: number; + width: number; + equals(other: Size): bool; + toString(): string; + } + + /***** Geometry Library *****/ + export module geometry { + export class encoding { + static decodePath(encodedPath: string): LatLng; + static encodePath(path: any[]): string; + } + + export class spherical { + static computeArea(path: any[], radius?: number): number; + static computeDistanceBetween(from: LatLng, to: LatLng, radius?: number): number; + static computeHeading(from: LatLng, to: LatLng): number; + static computeLength(path: any[], radius?: number): number; + static computeOffset(from: LatLng, distance: number, heading: number, radius?: number): LatLng; + static computeSignedArea(loop: any[], radius?: number): number; + static interpolate(from: LatLng, to: LatLng, fraction: number): LatLng; + } + + export class poly { + containsLocation(point: LatLng, polygon: Polygon): bool; + isLocationOnEdge(point: LatLng, poly: any, tolerance?: number): bool; + } + } + + /***** AdSense Library *****/ + export module adsense { + export class AdUnit extends MVCObject { + constructor (container: Element, opts: AdUnitOptions); + getChannelNumber(): string; + getContainer(): Element; + getFormat(): AdFormat; + getMap(): Map; + getPosition(): ControlPosition; + getPublisherId(): string; + setChannelNumber(channelNumber: string): void; + setFormat(format: AdFormat): void; + setMap(map: Map): void; + setPosition(position: ControlPosition): void; + } + + export interface AdUnitOptions { + channelNumber?: string; + format?: AdFormat; + map?: Map; + position?: ControlPosition; + publisherId?: string; + } + + export enum AdFormat { + BANNER, + BUTTON, + HALF_BANNER, + LARGE_RECTANGLE, + LEADERBOARD, + MEDIUM_RECTANGLE, + SKYSCRAPER, + SMALL_RECTANGLE, + SMALL_SQUARE, + SQUARE, + VERTICAL_BANNER, + WIDE_SKYSCRAPER + } + } + + /***** Panoramio Library *****/ + export module panoramio { + export class PanoramioLayer extends MVCObject { + constructor (opts?: PanoramioLayerOptions); + getMap(): Map; + getTag(): string; + getUserId(): string; + setMap(map: Map): void; + setOptions(options: PanoramioLayerOptions): void; + setTag(tag: string): void; + setUserId(userId: string): void; + } + + export interface PanoramioLayerOptions { + map?: Map; + suppressInfoWindows?: bool; + tag?: string; + userId?: string; + } + + export interface PanoramioFeature { + author: string; + photoId: string; + title: string; + url: string; + userId: string; + } + + export interface PanoramioMouseEvent { + featureDetails: PanoramioFeature; + infoWindowHtml: string; + latLng: LatLng; + pixelOffset: Size; + } + } +} + From 5fa268fa1a8d7f6e52c3e90a82ff31153aa1be2c Mon Sep 17 00:00:00 2001 From: Esben Nepper Date: Fri, 26 Oct 2012 09:01:00 +0200 Subject: [PATCH 021/107] Added license to Google Maps definition --- Definitions/google.maps.d.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Definitions/google.maps.d.ts b/Definitions/google.maps.d.ts index 8ca60c205..d547eba76 100644 --- a/Definitions/google.maps.d.ts +++ b/Definitions/google.maps.d.ts @@ -1,3 +1,27 @@ +/* +The MIT License + +Copyright (c) 2012 Folia A/S. http://www.folia.dk + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + declare module google.maps { /***** MVC *****/ From c02fecfcefb25282b2865ac6c61660220a146531 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Fri, 26 Oct 2012 10:23:00 +0300 Subject: [PATCH 022/107] Express definitions complete rework and update to 3.0 --- Definitions/express-2.d.ts | 124 ---------------- Definitions/express-3.0.d.ts | 187 ++++++++++++++++++++++++ Tests/express-tests.ts | 266 +++++++++++++++++++++++++++++------ 3 files changed, 410 insertions(+), 167 deletions(-) delete mode 100644 Definitions/express-2.d.ts create mode 100644 Definitions/express-3.0.d.ts diff --git a/Definitions/express-2.d.ts b/Definitions/express-2.d.ts deleted file mode 100644 index 187019640..000000000 --- a/Definitions/express-2.d.ts +++ /dev/null @@ -1,124 +0,0 @@ -/// - -declare module "express" { - export function createServer(): ExpressServer; - export function static(path: string): any; - import http = module("http"); - export var listen; - - // Connect middleware - export function bodyParser(options?:any): (req: ExpressServerRequest, res: ExpressServerResponse, next) =>void; - export function errorHandler(opts?:any): (req: ExpressServerRequest, res: ExpressServerResponse, next) =>void; - export function methodOverride(): (req: ExpressServerRequest, res: ExpressServerResponse, next) =>void; - - export interface ExpressSettings { - env?: string; - views?: string; - } - - export interface ExpressServer { - set(name: string): any; - set(name: string, val: any): any; - enable(name: string): ExpressServer; - disable(name: string): ExpressServer; - enabled(name: string): bool; - disabled(name: string): bool; - configure(env: string, callback: () => void): ExpressServer; - configure(env: string, env2: string, callback: () => void ): ExpressServer; - configure(callback: () => void): ExpressServer; - settings: ExpressSettings; - engine(ext: string, callback: any): void; - param(param: Function): ExpressServer; - param(name: string, callback: Function): ExpressServer; - param(name: string, expressParam: any): ExpressServer; - param(name: any[], callback: Function): ExpressServer; - get(name: string): any; - get(path: string, handler: (req: ExpressServerRequest, res: ExpressServerResponse) => void ): void; - get(path: RegExp, handler: (req: ExpressServerRequest, res: ExpressServerResponse) => void ): void; - get(path: string, callbacks: any, callback: () => void ): void; - post(path: string, handler: (req: ExpressServerRequest, res: ExpressServerResponse) => void ): void; - post(path: RegExp, handler: (req: ExpressServerRequest, res: ExpressServerResponse) => void ): void; - post(path: string, callbacks: any, callback: () => void ): void; - all(path: string, callback: Function): void; - all(path: string, callback: Function, callback2: Function): void; - locals: any; - render(view: string, callback: (err: Error, html) => void ): void; - render(view: string, opts: any, callback: (err: Error, html) => void ): void; - routes: any; - listen(port: number, hostname: string, backlog: number, callback: Function): void; - listen(port: number, callback: Function): void; - listen(path: string, callback?: Function): void; - listen(handle: any, listeningListener?: Function): void; - use(route: string, callback: Function): ExpressServer; - use(route: string, server: ExpressServer): ExpressServer; - use(callback: Function): ExpressServer; - use(server: ExpressServer): ExpressServer; - } - - export interface ExpressServerRequest extends http.ServerRequest { - params: any; - query: any; - body: any; - files: any; - param(name: string): any; - route: any; - cookies: any; - signedCookies: any; - get(field: string): string; - accepts(types: string): any; - accepts(types: string[]): any; - accepted: any; - is(type: string): bool; - ip: string; - ips: string[]; - path: string; - host: string; - fresh: bool; - stale: bool; - xhr: bool; - protocol: string; - secure: bool; - subdomains: string[]; - acceptedLanguages: string[]; - acceptedCharsets: string[]; - acceptsCharset(charset: string): bool; - acceptsLanguage(lang: string): bool; - } - - export interface ExpressServerResponse extends http.ServerResponse { - status(code: number): any; - set(field: any): void; - set(field: string, value: string): void; - header(field: any): void; - header(field: string, value: string): void; - get(field: string): any; - cookie(name: string, value: any, options?: any): void; - clearcookie(name: string, options?: any): void; - redirect(status: number, url: string): void; - redirect(url: string): void; - charset: string; - send(bodyOrStatus: any); - send(body: any, status: any); - send(body: any, headers: any, status: number); - json(bodyOrStatus: any); - json(body: any, status: any); - json(body: any, headers: any, status: number); - jsonp(bodyOrStatus: any); - jsonp(body: any, status: any); - jsonp(body: any, headers: any, status: number); - type(type: string): void; - format(object: any): void; - attachment(filename?: string); - sendfile(path: string): void; - sendfile(path: string, options: any): void; - sendfile(path: string, options: any, fn: (err: Error) =>void ): void; - download(path: string): void; - download(path: string, filename: string): void; - download(path: string, filename: string, fn: (err: Error) =>void ): void; - links(links: any): void; - locals: any; - render(view: string, locals: any): void; - render(view: string, callback: (err: Error, html: any) =>void ): void; - render(view: string, locals: any, callback: (err: Error, html: any) =>void ): void; - } -} diff --git a/Definitions/express-3.0.d.ts b/Definitions/express-3.0.d.ts new file mode 100644 index 000000000..00a3f1ce2 --- /dev/null +++ b/Definitions/express-3.0.d.ts @@ -0,0 +1,187 @@ +// Type definitions for Express 3.0 +// Project: http://expressjs.com +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare module "express" { + export function createServer(): ServerApplication; + export function static(path: string): any; + import http = module("http"); + export var listen; + + interface ReqResNext { + (req: ServerRequest, res: ServerResponse, next: Function): void; + } + + interface Errback { (err: Error): void; } + + interface CookieOptions { + maxAge?: number; + signed?: bool; + expires?: Date; + httpOnly?: bool; + path?: string; + domain?: string; + secure?: bool; + } + + // Connect middleware + export function bodyParser(options?: any): ReqResNext; + export function errorHandler(opts?: any): ReqResNext; + export function methodOverride(): ReqResNext; + + export interface ExpressSettings { + env?: string; + views?: string; + } + + export interface ServerApplication { + + settings: ExpressSettings; + locals: any; + routes: any; + + (): ServerApplication; + + router: ReqResNext; + + use(route: string, callback: Function): ServerApplication; + use(route: string, server: ServerApplication): ServerApplication; + use(callback: Function): ServerApplication; + use(server: ServerApplication): ServerApplication; + + engine(ext: string, callback: Function): ServerApplication; + + param(param: Function): ServerApplication; + param(name: string, callback: Function): ServerApplication; + param(name: string, expressParam: any): ServerApplication; + param(name: any[], callback: Function): ServerApplication; + + set(name: string): ServerApplication; + set(name: string, val: any): ServerApplication; + + enabled(name: string): bool; + disabled(name: string): bool; + + enable(name: string): ServerApplication; + disable(name: string): ServerApplication; + + configure(env: string, callback: () => void ): ServerApplication; + configure(...params: any[]): ServerApplication; // covering this case: (...env: string[], callback: () => void) + configure(callback: () => void ): ServerApplication; + + all(path: string, ...callbacks: Function[]): void; + + render(view: string, callback: (err: Error, html) => void ): void; + render(view: string, optionss: any, callback: (err: Error, html) => void ): void; + + listen(port: number, hostname: string, backlog: number, callback: Function): void; + listen(port: number, callback: Function): void; + listen(path: string, callback?: Function): void; + listen(handle: any, listeningListener?: Function): void; + + get(name: string): any; + get(path: string, handler: (req: ServerRequest, res: ServerResponse) => void ): void; + get(path: RegExp, handler: (req: ServerRequest, res: ServerResponse) => void ): void; + get(path: string, callbacks: any, callback: () => void ): void; + + post(path: string, handler: (req: ServerRequest, res: ServerResponse) => void ): void; + post(path: RegExp, handler: (req: ServerRequest, res: ServerResponse) => void ): void; + post(path: string, callbacks: any, callback: () => void ): void; + } + + export interface ServerRequest extends http.ServerRequest { + + accepted: any[]; + acceptedLanguages: string[]; + acceptedCharsets: string[]; + + params: any; + query: any; + body: any; + files: any; + + route: any; + cookies: any; + signedCookies: any; + + get(field: string): string; + header(field: string): string; + + accepts(types: string): any; + accepts(types: string[]): any; + acceptsCharset(charset: string): bool; + acceptsLanguage(lang: string): bool; + + range(size: number): number[]; + + param(name: string, defaultValue?: any): string; + is(type: string): bool; + + protocol: string; + secure: bool; + ip: string; + ips: string[]; + auth: any; + subdomains: string[]; + path: string; + host: string; + fresh: bool; + stale: bool; + xhr: bool; + } + + export interface ServerResponse extends http.ServerResponse { + + charset: string; + locals: any; + + status(code: number): ServerResponse; + links(links: any): ServerResponse; + + send(status: number): ServerResponse; + send(bodyOrStatus: any): ServerResponse; + send(status: number, body: any): ServerResponse; + json(status: number): ServerResponse; + json(bodyOrStatus: any): ServerResponse; + json(status: number, body: any): ServerResponse; + jsonp(status: number): ServerResponse; + jsonp(bodyOrStatus: any): ServerResponse; + jsonp(status: number, body: any): ServerResponse; + + sendfile(path: string): void; + sendfile(path: string, options: any): void; + sendfile(path: string, fn: Errback): void; + sendfile(path: string, options: any, fn: Errback): void; + download(path: string): void; + download(path: string, filename: string): void; + download(path: string, fn: Errback): void; + download(path: string, filename: string, fn: Errback): void; + + type(type: string): ServerResponse; + contentType(type: string): ServerResponse; + + format(object: any): ServerResponse; + attachment(filename?: string): ServerResponse; + + set(field: any): void; + set(field: string, value: string): void; + header(field: any): void; + header(field: string, value: string): void; + + get(field: string): string; + + clearCookie(name: string, options?: any): ServerResponse; + cookie(name: string, value: any, options?: CookieOptions): ServerResponse; + + redirect(url: string): void; + redirect(status: number, url: string): void; + redirect(url: string, status: number): void; + + render(view: string, options: any): void; + render(view: string, callback: (err: Error, html: any) => void ): void; + render(view: string, options: any, callback: (err: Error, html: any) => void ): void; + } +} \ No newline at end of file diff --git a/Tests/express-tests.ts b/Tests/express-tests.ts index b67728450..585ab4e22 100644 --- a/Tests/express-tests.ts +++ b/Tests/express-tests.ts @@ -1,61 +1,241 @@ -/// +/// declare var _, $; -declare function require(name:string); -var express = require('express'); -var app = express(); +import Express = module('express'); +var express: Express; +var app: Express.ServerApplication; -app.get('/', function (req, res) { - res.send('hello world'); -}); +function test_general() { -app.listen(3000); + app.use(function (err, req, res, next) { + console.error(err.stack); + res.send(500, 'Something broke!'); + }); + app.use(express.bodyParser()); + app.use(express.methodOverride()); + app.use(app.router); + app.use(function (err, req, res, next) { }); + app.use(express.bodyParser()); + app.use(express.methodOverride()); + app.use(app.router); -app.set('title', 'My Site'); -app.get('title'); + app.get('/', function (req, res) { + res.send('hello world'); + }); -app.enable('trust proxy'); -app.get('trust proxy'); + app.listen(3000); -app.disable('trust proxy'); -app.get('trust proxy'); + app.set('title', 'My Site'); + app.get('title'); -app.enabled('trust proxy'); + app.enable('trust proxy'); + app.get('trust proxy'); -app.configure(function () => { - app.set('title', 'My Application'); -}); + app.disable('trust proxy'); + app.get('trust proxy'); -app.configure('development', () => { - app.set('db uri', 'localhost/dev'); -}); + app.enabled('trust proxy'); -app.use(function (req, res, next) { - res.send('Hello World'); -}); + app.configure(function () => { + app.set('title', 'My Application'); + }); -app.engine('jade', require('jade').__express); + app.configure('development', () => { + app.set('db uri', 'localhost/dev'); + }); -var User; -app.param('user', (req, res, next, id) => { - User.find(id, (err, user) =>{ - if (err) { - next(err); - } else if (user) { - req.user = user; - next(); - } else { - next(new Error('failed to load user')); + app.configure('stage', 'production', function () { }); + + app.configure('1', '2', '3', function () { }); + + app.use(function (req, res, next) { + res.send('Hello World'); + }); + + app.engine('jade', require('jade').__express); + + var User; + app.param('user', (req, res, next, id) => { + User.find(id, (err, user) =>{ + if (err) { + next(err); + } else if (user) { + req.user = user; + next(); + } else { + next(new Error('failed to load user')); + } + }); + }); + + app.get(/^\/commits\/(\d+)(?:\.\.(\d+))?$/, (req, res) => { + var from = req.params[0]; + var to = req.params[1] || 'HEAD'; + res.send('commit range ' + from + '..' + to); + }); + + app.locals.title = 'My App'; + app.locals.strftime = require('strftime'); + + var requireAuthentication; + var loadUser = function () { }; + app.all('*', requireAuthentication, loadUser); + app.all('*', loadUser); + app.all('*', loadUser, loadUser, loadUser); + + app.locals.title = 'My App'; + app.locals.strftime = require('strftime'); + app.locals({ + title: 'My App', + phone: '1-250-858-9990', + email: 'me@myapp.com' + }); + app.render('email', function (err, html) { }); + + app.render('email', { name: 'Tobi' }, function (err, html) { }); +} + +function test_request() { + var req: Express.ServerRequest; + req.params.name; + req.params[0]; + req.query.q; + req.body.user.name; + app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/my/files' })); + req.param('name'); + req.route; + req.cookies.name; + req.signedCookies; + req.get('Content-Type'); + req.accepts('html'); + req.accepts(['html', 'json']); + req.is('html'); + req.ip; + req.path; + req.host; + req.fresh; + req.stale; + req.xhr; + req.protocol; + req.subdomains; + req.originalUrl; + req.acceptedLanguages; + req.acceptedCharsets; + var charset; + req.acceptsCharset(charset); + var lang; + req.acceptsLanguage(lang); + req.session = null; +} + +function test_response() { + var res: Express.ServerResponse; + res.status(404).sendfile('path/to/404.png'); + res.set('Content-Type', 'text/plain'); + res.set({ + 'Content-Type': 'text/plain', + 'Content-Length': '123', + 'ETag': '12345' + }); + res.get('Content-Type'); + res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }); + res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }); + res.cookie('cart', { items: [1, 2, 3] }); + res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 });; + res.cookie('name', 'tobi', { signed: true }); + res.cookie('name', 'tobi', { path: '/admin' }); + res.clearCookie('name', { path: '/admin' }); + res.redirect('/foo/bar'); + res.redirect('http://example.com'); + res.redirect(301, 'http://example.com'); + res.charset = 'value'; + res.send('some html'); + res.send(new Buffer('whoop')); + res.send({ some: 'json' }); + res.send('some html'); + res.send(404, 'Sorry, we cannot find that!'); + res.send(500, { error: 'something blew up' }); + res.send(200); + res.set('Content-Type', 'text/html'); + res.send(new Buffer('some html')); + res.send('some html'); + res.send({ user: 'tobi' }); + res.send([1, 2, 3]); + res.json(null); + res.json({ user: 'tobi' }); + res.json(500, { error: 'message' }); + res.jsonp(null); + res.jsonp({ user: 'tobi' }); + res.jsonp(500, { error: 'message' }); + res.jsonp({ user: 'tobi' }); + res.type('application/json'); + + res.format({ + 'text/plain': function () { + res.send('hey'); + }, + 'text/html': function () { + res.send('hey'); + }, + 'application/json': function () { + res.send({ message: 'hey' }); } }); -}); -app.get(/^\/commits\/(\d+)(?:\.\.(\d+))?$/, (req, res) => { - var from = req.params[0]; - var to = req.params[1] || 'HEAD'; - res.send('commit range ' + from + '..' + to); -}); + res.attachment(); + res.attachment('path/to/logo.png'); + app.get('/user/:uid/photos/:file', function (req, res) { + var uid = req.params.uid + , file = req.params.file; -app.locals.title = 'My App'; -app.locals.strftime = require('strftime'); + req.user.mayViewFilesFrom(uid, function (yes) { + if (yes) { + res.sendfile('/uploads/' + uid + '/' + file); + } else { + res.send(403, 'Sorry! you cant see that.'); + } + }); + }); + + res.download('/report-12345.pdf'); + res.download('/report-12345.pdf', 'report.pdf'); + res.download('/report-12345.pdf', 'report.pdf', function (err) { + if (err) { } else { } + }); + + res.links({ + next: 'http://api.example.com/users?page=2', + last: 'http://api.example.com/users?page=5' + }); + + app.use(function (req, res, next) { + res.locals.user = req.user; + res.locals.authenticated = !req.user.anonymous; + next(); + }); + res.render('index', function (err, html) { }); + res.render('user', { name: 'Tobi' }, function (err, html) { }); + +} + +function test_middleware() { + app.use(express.basicAuth('username', 'password')); + app.use(express.basicAuth(function (user, pass) { + return 'tj' == user && 'wahoo' == pass; + })); + app.use(express.bodyParser()); + app.use(express.json()); + app.use(express.urlencoded()); + app.use(express.multipart()); + app.use(express.logger()); + app.use(express.compress()); + app.use(express.methodOverride()); + app.use(express.bodyParser()); + app.use(express.cookieParser()); + app.use(express.cookieParser('some secret')); + app.use(express.cookieSession()); + app.use(express.directory('public')); + app.use(express.static('public')); +} \ No newline at end of file From 991120d8a7ecd3c4655ebcf5eb1b86915e60a46f Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Fri, 26 Oct 2012 10:36:39 +0300 Subject: [PATCH 023/107] Readme update --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ce10a6ae9..a92d08c42 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,9 @@ Complete * [CodeMirror](http://codemirror.net) (by [Franois de Campredon](https://github.com/fdecampredon)) * [dynatree](http://code.google.com/p/dynatree/) (by [Franois de Campredon](https://github.com/fdecampredon)) * [ember.js](http://emberjs.com/) -* [Express](http://expressjs.com/) (from TypeScript samples) -* [Fancybox](http://fancybox.net/) +* [Express](http://expressjs.com/) +* [Fancybox](http://fancybox.net/) +* [GoogleMaps](https://developers.google.com/maps/) (by [Esben Nepper](https://github.com/eNepper)) * [Handlebars](http://handlebarsjs.com/) * [History.js](https://github.com/balupton/History.js/) * [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac)) From 4209993771040100b3590654125cbdd45e62aa8a Mon Sep 17 00:00:00 2001 From: Esben Nepper Date: Fri, 26 Oct 2012 11:48:18 +0200 Subject: [PATCH 024/107] google.maps.d.ts is now complete Signed-off-by: Esben Nepper --- Definitions/google.maps.d.ts | 237 ++++++++++++++++++++++++++++++++++- 1 file changed, 236 insertions(+), 1 deletion(-) diff --git a/Definitions/google.maps.d.ts b/Definitions/google.maps.d.ts index d547eba76..8fdbf19d1 100644 --- a/Definitions/google.maps.d.ts +++ b/Definitions/google.maps.d.ts @@ -33,11 +33,12 @@ declare module google.maps { notify(key: string): void; set(key: string, value: any): void; setValues(values: any): void; + setValues(values: undefined); unbind(key: string): void; unbindAll(): void; } - export class MVCArray { + export class MVCArray extends MVCObject { constructor (array?: any[]); clear(): void; forEach(callback: (elem: any, index: number) => void ): void; @@ -1273,5 +1274,239 @@ declare module google.maps { pixelOffset: Size; } } + + export module places { + + export class Autocomplete extends MVCObject { + constructor (inputField: HTMLInputElement, opts?: AutocompleteOptions); + getBounds(): LatLngBounds; + getPlace(): PlaceResult; + setBounds(bounds: LatLngBounds): void; + setComponentRestrictions(restrictions: ComponentRestrictions): void; + setTypes(types: string[]): void; + } + + export interface AutocompleteOptions { + bounds: LatLngBounds; + componentRestrictions: ComponentRestrictions; + types: string[]; + } + + export interface ComponentRestrictions { + country: string; + } + + export interface PlaceDetailsRequest { + reference: string; + } + + export interface PlaceGeometry { + location: LatLng; + viewport: LatLngBounds; + } + + export interface PlaceResult { + address_components: GeocoderAddressComponent[]; + formatted_address: string; + formatted_phone_number: string; + geometry: PlaceGeometry; + html_attributions: string[]; + icon: string; + id: string; + international_phone_number: string; + name: string; + rating: number; + reference: string; + types: string[]; + url: string; + vicinity: string; + website: string; + } + + export interface PlaceSearchRequest { + bounds: LatLngBounds; + keyword: string; + location: LatLng; + name: string; + radius: number; + rankBy: RankBy; + types: string[]; + } + + export interface PlaceSearchPagination { + nextPage(): void; + hasNextPage: bool; + } + + export class PlacesService { + constructor (attrContainer: HTMLDivElement); + constructor (attrContainer: Map); + getDetails(request: PlaceDetailsRequest, callback: (result: PlaceResult, status: PlacesServiceStatus) => void ): void; + nearbySearch(request: PlaceSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus, pagination: PlaceSearchPagination) => void ): void; + textSearch(request: TextSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void ): void; + } + + export enum PlacesServiceStatus { + INVALID_REQUEST, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + export enum RankBy { + DISTANCE, + PROMINENCE + } + + export interface TextSearchRequest { + bounds: LatLngBounds; + location: LatLng; + query: string; + radius: number; + } + } + + export module drawing { + export class DrawingManager extends MVCObject { + constructor (options?: DrawingManagerOptions); + getDrawingMode(): OverlayType; + getMap(): Map; + setDrawingMode(drawingMode: OverlayType): void; + setMap(map: Map): void; + setOptions(options: DrawingManagerOptions): void; + } + + export interface DrawingManagerOptions { + circleOptions: CircleOptions; + drawingControl: bool; + drawingControlOptions: DrawingControlOptions; + drawingMode: OverlayType; + map: Map; + markerOptions: MarkerOptions; + polygonOptions: PolygonOptions; + polylineOptions: PolylineOptions; + rectangleOptions: RectangleOptions; + } + + export interface DrawingControlOptions { + drawingModes: OverlayType[]; + position: ControlPosition; + } + + export interface OverlayCompleteEvent { + overlay: MVCObject; + type: OverlayType; + } + + export enum OverlayType { + CIRCLE, + MARKER, + POLYGON, + POLYLINE, + RECTANGLE + } + } + + export module weather { + export class CloudLayer extends MVCObject { + constructor (); + getMap(): Map; + setMap(map: Map): void; + } + export class WeatherLayer extends MVCObject { + constructor (opts?: WeatherLayerOptions); + getMap(): Map; + setMap(map: Map): void; + setOptions(options: WeatherLayerOptions): void; + } + + export interface WeatherLayerOptions { + clickable: bool; + labelColor: LabelColor; + map: Map; + suppressInfoWindows: bool; + temperatureUnits: TemperatureUnit; + windSpeedUnits: WindSpeedUnit; + } + + export enum TemperatureUnit { + CELSIUS, + FAHRENHEIT + } + + export enum WindSpeedUnit { + KILOMETERS_PER_HOUR, + METERS_PER_SECOND, + MILES_PER_HOUR + } + + export enum LabelColor { + BLACK, + WHITE + } + + export interface WeatherMouseEvent { + featureDetails: WeatherFeature; + infoWindowHtml: string; + latLng: LatLng; + pixelOffset: Size; + } + + export interface WeatherFeature { + current: WeatherConditions; + forecast: WeatherForecast[]; + location: string; + temperatureUnit: TemperatureUnit; + windSpeedUnit: WindSpeedUnit; + } + + export interface WeatherConditions { + day: string; + description: string; + high: number; + humidity: number; + low: number; + shortDay: string; + temperature: number; + windDirection: string; + windSpeed: number; + } + + export interface WeatherForecast { + day: string; + description: string; + high: number; + low: number; + shortDay: string; + } + } + export module visualization { + export class HeatmapLayer extends MVCObject { + constructor (opts?: HeatmapLayerOptions); + getData(): MVCArray; + getMap(): Map; + setData(data: MVCArray): void; + setData(data: LatLng[]): void; + setData(data: WeightedLocation[]): void; + setMap(map: Map): void; + } + + export interface HeatmapLayerOptions { + data: LatLng[]; + dissipating: bool; + gradient: string[]; + map: Map; + maxIntensity: number; + opacity: number; + radius: number; + } + + export interface WeightedLocation { + location: LatLng; + weight: number; + } + } } From 6ba7bc02abcab0a63d1fa0b3b3a9d0f91d615e38 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Sat, 27 Oct 2012 01:04:23 +0300 Subject: [PATCH 025/107] Fix for Mustache definitions --- Definitions/mustache-0.7.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Definitions/mustache-0.7.d.ts b/Definitions/mustache-0.7.d.ts index 83dcb26ea..9c5b9263b 100644 --- a/Definitions/mustache-0.7.d.ts +++ b/Definitions/mustache-0.7.d.ts @@ -43,7 +43,7 @@ interface MustacheStatic { compile(template: string, tags): MustacheWriter; compilePartial(name: string, template: string, tags): MustacheWriter; compileTokens(tokens, template: string): MustacheWriter; - render(template: string, view: any, partials?: any): MustacheWriter; + render(template: string, view: any, partials?: any): string; to_html(template: string, view: any, partials?: any, send?): string; } From 9b81539810801f8d1ed3ffc01b438f42d6c1750b Mon Sep 17 00:00:00 2001 From: MarcinNajder Date: Mon, 29 Oct 2012 09:11:26 +0100 Subject: [PATCH 026/107] add linq.js library --- Definitions/linq-2.2.0.2.d.ts | 220 ++++++++++++++++++++++++++++++++++ Tests/linq-tests.ts | 39 ++++++ 2 files changed, 259 insertions(+) create mode 100644 Definitions/linq-2.2.0.2.d.ts create mode 100644 Tests/linq-tests.ts diff --git a/Definitions/linq-2.2.0.2.d.ts b/Definitions/linq-2.2.0.2.d.ts new file mode 100644 index 000000000..0cf528287 --- /dev/null +++ b/Definitions/linq-2.2.0.2.d.ts @@ -0,0 +1,220 @@ +// http://linqjs.codeplex.com/ +// 2.2.0.2 + +// todo: jQuery plugin, RxJS Binding + +module linq { + + interface EnumerableStatic { + Choice(...contents: any[]): Enumerable; + Choice(contents: any[]): Enumerable; + Cycle(...contents: any[]): Enumerable; + Cycle(contents: any[]): Enumerable; + Empty(): Enumerable; + From(obj: any[]): Enumerable; + From(obj: any): Enumerable; + Return(element: any): Enumerable; + Matches(input: string, pattern: RegExp): Enumerable; + Matches(input: string, pattern: string, flags?: string): Enumerable; + Range(start: number, count: number, step?: number): Enumerable; + RangeDown(start: number, count: number, step?: number): Enumerable; + RangeTo(start: number, to: number, step?: number): Enumerable; + Repeat(obj: any, count?: number): Enumerable; + RepeatWithFinalize(initializer: () => any, finalizer: (resource: any) =>void ): Enumerable; + Generate(func: () => any, count?: number): Enumerable; + Generate(func: string, count?: number): Enumerable; + ToInfinity(start?: number, step?: number): Enumerable; + ToNegativeInfinity(start?: number, step?: number): Enumerable; + Unfold(seed, func: ($) => any): Enumerable; + Unfold(seed, func: string): Enumerable; + } + + interface Enumerable { + //Projection and Filtering Methods + CascadeBreadthFirst(func: ($) => any[], resultSelector: (v, i: number) => any): Enumerable; + CascadeBreadthFirst(func: string, resultSelector: string): Enumerable; + CascadeDepthFirst(func: ($) => any[], resultSelector: (v, i: number) => any): Enumerable; + CascadeDepthFirst(func: string, resultSelector: string): Enumerable; + Flatten(...items: any[]): Enumerable; + Pairwise(selector: (prev, next) => any): Enumerable; + Pairwise(selector: string): Enumerable; + Scan(func: (a, b) => any): Enumerable; + Scan(func: string): Enumerable; + Scan(seed, func: (a, b) => any, resultSelector?: ($) => any): Enumerable; + Scan(seed, func: string, resultSelector?: string): Enumerable; + Select(selector: ($, i: number) => any): Enumerable; + Select(selector: string): Enumerable; + SelectMany(collectionSelector: ($, i: number) => any[], resultSelector?: ($, item) => any): Enumerable; + SelectMany(collectionSelector: ($, i: number) => Enumerable, resultSelector?: ($, item) => any): Enumerable; + SelectMany(collectionSelector: string, resultSelector?: string): Enumerable; + Where(predicate: ($, i: number) => bool): Enumerable; + Where(predicate: string): Enumerable; + OfType(type: Function): Enumerable; + Zip(second: any[], selector: (v1, v2, i: number) => any): Enumerable; + Zip(second: any[], selector: string): Enumerable; + Zip(second: Enumerable, selector: (v1, v2, i: number) => any): Enumerable; + Zip(second: Enumerable, selector: string): Enumerable; + //Join Methods + Join(inner: any[], outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2) => any, compareSelector?: (v) => any): Enumerable; + Join(inner: any[], outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; + Join(inner: Enumerable, outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2) => any, compareSelector?: (v) => any): Enumerable; + Join(inner: Enumerable, outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; + GroupJoin(inner: any[], outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2: Enumerable) => any, compareSelector?: (v) => any): Enumerable; + GroupJoin(inner: any[], outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; + GroupJoin(inner: Enumerable, outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2: Enumerable) => any, compareSelector?: (v) => any): Enumerable; + GroupJoin(inner: Enumerable, outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; + //Set Methods + All(predicate: ($) => bool): bool; + All(predicate: string): bool; + Any(predicate?: ($) => bool): bool; + Any(predicate?: string): bool; + Concat(second: any[]): Enumerable; + Concat(second: Enumerable): Enumerable; + Insert(index: number, second: any[]): Enumerable; + Insert(index: number, second: Enumerable): Enumerable; + Alternate(value): Enumerable; + Contains(value, compareSelector?: ($) => any): bool; + Contains(value, compareSelector?: string): bool; + DefaultIfEmpty(defaultValue): Enumerable; + Distinct(compareSelector?: ($) => any): Enumerable; + Distinct(compareSelector?: string): Enumerable; + Except(second: any[], compareSelector?: ($) => any): Enumerable; + Except(second: any[], compareSelector?: string): Enumerable; + Except(second: Enumerable, compareSelector?: ($) => any): Enumerable; + Except(second: Enumerable, compareSelector?: string): Enumerable; + Intersect(second: any[], compareSelector?: ($) => any): Enumerable; + Intersect(second: any[], compareSelector?: string): Enumerable; + Intersect(second: Enumerable, compareSelector?: ($) => any): Enumerable; + Intersect(second: Enumerable, compareSelector?: string): Enumerable; + SequenceEqual(second: any[], compareSelector?: ($) => any): bool; + SequenceEqual(second: any[], compareSelector?: string): bool; + SequenceEqual(second: Enumerable, compareSelector?: ($) => any): bool; + SequenceEqual(second: Enumerable, compareSelector?: string): bool; + Union(second: any[], compareSelector?: ($) => any): Enumerable; + Union(second: any[], compareSelector?: string): Enumerable; + Union(second: Enumerable, compareSelector?: ($) => any): Enumerable; + Union(second: Enumerable, compareSelector?: string): Enumerable; + //Ordering Methods + OrderBy(keySelector?: ($) => any): OrderedEnumerable; + OrderBy(keySelector?: string): OrderedEnumerable; + OrderByDescending(keySelector?: ($) => any): OrderedEnumerable; + OrderByDescending(keySelector?: string): OrderedEnumerable; + Reverse(): Enumerable; + Shuffle(): Enumerable; + //Grouping Methods + GroupBy(keySelector: ($) => any, elementSelector?: ($) => any, resultSelector?: (key, e) => any, compareSelector?: ($) =>any): Enumerable; + GroupBy(keySelector: string, elementSelector?: string, resultSelector?: string, compareSelector?: string): Enumerable; + PartitionBy(keySelector: ($) => any, elementSelector?: ($) => any, resultSelector?: (key, e) => any, compareSelector?: ($) =>any): Enumerable; + PartitionBy(keySelector: string, elementSelector?: string, resultSelector?: string, compareSelector?: string): Enumerable; + BufferWithCount(count: number): Enumerable; + // Aggregate Methods + Aggregate(func: (a, b) => any); + Aggregate(seed, func: (a, b) => any, resultSelector?: ($) => any); + Aggregate(func: string); + Aggregate(seed, func: string, resultSelector?: string); + Average(selector?: ($) => number): number; + Average(selector?: string): number; + Count(predicate?: ($) => bool): number; + Count(predicate?: string): number; + Max(selector?: ($) => number): number; + Max(selector?: string): number; + Min(selector?: ($) => number): number; + Min(selector?: string): number; + MaxBy(selector: ($) => number): any; + MaxBy(selector: string): any; + MinBy(selector: ($) => number): any; + MinBy(selector: string): any; + Sum(selector?: ($) => number): number; + Sum(selector?: string): number; + //Paging Methods + ElementAt(index: number): any; + ElementAtOrDefault(index: number, defaultValue): any; + First(predicate?: ($) => bool): any; + First(predicate?: string): any; + FirstOrDefault(defaultValue, predicate?: ($) => bool): any; + FirstOrDefault(defaultValue, predicate?: string): any; + Last(predicate?: ($) => bool): any; + Last(predicate?: string): any; + LastOrDefault(defaultValue, predicate?: ($) => bool): any; + LastOrDefault(defaultValue, predicate?: string): any; + Single(predicate?: ($) => bool): any; + Single(predicate?: string): any; + SingleOrDefault(defaultValue, predicate?: ($) => bool): any; + SingleOrDefault(defaultValue, predicate?: string): any; + Skip(count: number): Enumerable; + SkipWhile(predicate: ($, i: number) => bool): Enumerable; + SkipWhile(predicate: string): Enumerable; + Take(count: number): Enumerable; + TakeWhile(predicate: ($, i: number) => bool): Enumerable; + TakeWhile(predicate: string): Enumerable; + TakeExceptLast(count?: number): Enumerable; + TakeFromLast(count: number): Enumerable; + IndexOf(item): number; + LastIndexOf(item): number; + // Convert Methods + ToArray(): any[]; + ToLookup(keySelector: ($) => any, elementSelector?: ($) => any, compareSelector?: (key) => any): Lookup; + ToLookup(keySelector: string, elementSelector?: string, compareSelector?: string): Lookup; + ToObject(keySelector: ($) => string, elementSelector: ($) => any): any; + ToObject(keySelector: string, elementSelector: string): any; + ToDictionary(keySelector: ($) => any, elementSelector: ($) => any, compareSelector?: (key) => any): Dictionary; + ToDictionary(keySelector: string, elementSelector: string, compareSelector?: string): Dictionary; + ToJSON(replacer?: (key, value) => any, space?: number): string; + ToJSON(replacer?: string, space?: number): string; + ToString(separator?: string, selector?: ($) =>any): string; + ToString(separator?: string, selector?: string): string; + //Action Methods + Do(action: ($, i: number) => void ): Enumerable; + Do(action: string): Enumerable; + ForEach(action: ($, i: number) => void ): void; + ForEach(func: ($, i: number) => bool): void; + ForEach(action_func: string): void; + Write(separator?: string, selector?: ($) =>any): void; + Write(separator?: string, selector?: string): void; + WriteLine(selector?: ($) =>any): void; + Force(): void; + //Functional Methods + Let(func: (e: Enumerable) => Enumerable): Enumerable; + Share(): Enumerable; + MemoizeAll(): Enumerable; + //Error Handling Methods + Catch(handler: (error: Error) => void ): Enumerable; + Catch(handler: string): Enumerable; + Finally(finallyAction: () => void ): Enumerable; + Finally(finallyAction: string): Enumerable; + //For Debug Methods + Trace(message?: string, selector?: ($) =>any): Enumerable; + Trace(message?: string, selector?: string): Enumerable; + } + + interface OrderedEnumerable extends Enumerable { + ThenBy(keySelector: ($) => any): OrderedEnumerable; + ThenBy(keySelector: string): OrderedEnumerable; + ThenByDescending(keySelector: ($) => any): OrderedEnumerable; + ThenByDescending(keySelector: string): OrderedEnumerable; + } + + interface Grouping extends Enumerable { + Key(); + } + + interface Lookup { + Count(): number; + Get(key): Enumerable; + Contains(key): bool; + ToEnumerable(): Enumerable; + } + + interface Dictionary { + Add(key, value): void; + Get(key): any; + Set(key, value): bool; + Contains(key): bool; + Clear(): void; + Remove(key): void; + Count(): number; + ToEnumerable(): Enumerable; + } +} + +declare var Enumerable: linq.EnumerableStatic; \ No newline at end of file diff --git a/Tests/linq-tests.ts b/Tests/linq-tests.ts new file mode 100644 index 000000000..56e36fdab --- /dev/null +++ b/Tests/linq-tests.ts @@ -0,0 +1,39 @@ +/// +/// +// tests were run from VisualStudio + Resharper7 + +describe("Linq.js tests", function () { + it("Projection and Filtering Methods", function () { + expect(Enumerable.From([1,2,3,4]).ToString(",")).toBe("1,2,3,4"); + expect(Enumerable.Range(1, 4).Where((item: number) => item > 2).ToString(",")).toBe("3,4"); + expect(Enumerable.Range(1, 4).Where("(item) => item > 2").ToString(",")).toBe("3,4"); + expect(Enumerable.Range(1, 4).Where("$>2").ToString(",")).toBe("3,4"); + expect(Enumerable.Range(1, 4).Select((item: number,index:number) => item+index).ToString(",")).toBe("1,3,5,7"); + expect(Enumerable.Range(1, 4).Zip(Enumerable.Range(1, 10), (a: number,b:number) => a-b).ToString(",")).toBe("0,0,0,0"); + + }); + it("Join Methods", function () { + expect(Enumerable.Range(1, 4).Join(Enumerable.From(["a", "aaa"]), (l) => l, (r: string) => r.length, (l, r) =>l + ":" + r).ToString(",")).toBe("1:a,3:aaa"); + }); + it("Set Methods", function () { + expect(Enumerable.Range(2, 4, 2).All((item: number) => item % 2 == 0)).toBe(true); + expect(Enumerable.Range(1, 4).Intersect(Enumerable.Range(3, 4)).ToString(",")).toBe("3,4"); + }); + it("Ordering Methods", function () { + expect(Enumerable.From( + [ + { name: "marcin", age:15}, + { name: "albert", age:51}, + { name: "marcin", age:30}, + ]).OrderBy((p) => p.name).ThenByDescending((p) => p.age).Select((p) => p.name+p.age).ToString(",")).toBe("albert51,marcin30,marcin15"); + }); + it("Grouping Methods", function () { + expect(Enumerable.From(["a","aa","aaa","a","a","aaa"]) + .GroupBy((item:string) => item.length) + .Select((g: linq.Grouping) => { return { key: g.Key(), count: g.Count() }; }) + .OrderBy(g => g.key) + .Select(g => g.key+":"+g.count) + .ToString(",")).toBe("1:3,2:1,3:2"); + }); +}); + From 2890e9bf8fae3edc0229446ee96fe0bc4ddeef54 Mon Sep 17 00:00:00 2001 From: Philippe CHARRIERE Date: Mon, 29 Oct 2012 14:02:02 +0100 Subject: [PATCH 027/107] Update Definitions/backbone-0.9.d.ts can't transpile to javascript if `declare module "Backbone"` and then it's ok with `declare module Backbone` --- Definitions/backbone-0.9.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Definitions/backbone-0.9.d.ts b/Definitions/backbone-0.9.d.ts index 46281829f..64a9fe8e3 100644 --- a/Definitions/backbone-0.9.d.ts +++ b/Definitions/backbone-0.9.d.ts @@ -1,7 +1,7 @@ // Type definitions for Backbone 0.9 // https://github.com/borisyankov/DefinitelyTyped -declare module "Backbone" { +declare module Backbone { export class Events { on(events: string, callback: (event) => any, context?: any): any; From ab5c79eae4c48a7ba4ca782e1b2dffa031a8a92e Mon Sep 17 00:00:00 2001 From: Andrey Date: Mon, 29 Oct 2012 18:09:02 +0400 Subject: [PATCH 028/107] google.maps.d.ts add event namespace --- Definitions/google.maps.d.ts | 3043 +++++++++++++++++----------------- 1 file changed, 1531 insertions(+), 1512 deletions(-) diff --git a/Definitions/google.maps.d.ts b/Definitions/google.maps.d.ts index 8fdbf19d1..dffb71eeb 100644 --- a/Definitions/google.maps.d.ts +++ b/Definitions/google.maps.d.ts @@ -1,1512 +1,1531 @@ -/* -The MIT License - -Copyright (c) 2012 Folia A/S. http://www.folia.dk - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -declare module google.maps { - - /***** MVC *****/ - export class MVCObject { - constructor (); - bindTo(key: string, target: MVCObject, targetKey?: string, noNotify?: bool): void; - changed(key: string): void; - get(key: string): any; - notify(key: string): void; - set(key: string, value: any): void; - setValues(values: any): void; - setValues(values: undefined); - unbind(key: string): void; - unbindAll(): void; - } - - export class MVCArray extends MVCObject { - constructor (array?: any[]); - clear(): void; - forEach(callback: (elem: any, index: number) => void ): void; - getArray(): any[]; - getAt(i: number): any; - getLength(): number; - insertAt(i: number, elem: any): void; - pop(): void; - push(elem: any): number; - removeAt(i: number): any; - setAt(i: number, elem: any): void; - } - - /***** Map *****/ - export class Map extends MVCObject { - constructor (mapDiv: Element, opts?: MapOptions); - fitBounds(bounds: LatLngBounds); - getBounds(): LatLngBounds; - getCenter(): LatLng; - getDiv(): Element; - getHeading(): number; - getMapTypeId(): MapTypeId; - getProjection(): Projection; - getStreetView(): StreetViewPanorama; - getTilt(): number; - getZoom(): number; - panBy(x: number, y: number): void; - panTo(latLng: LatLng): void; - panToBounds(latLngBounds: LatLngBounds): void; - setCenter(latlng: LatLng): void; - setHeading(heading: number): void; - setMapTypeId(mapTypeId: MapTypeId): void; - setOptions(options: MapOptions): void; - setStreetView(panorama: StreetViewPanorama): void; - setTilt(tilt: number): void; - setZoom(zoom: number): void; - } - - export interface MapOptions { - backgroundColor?: string; - center?: LatLng; - disableDefaultUI?: bool; - disableDoubleClickZoom?: bool; - draggable?: bool; - draggableCursor?: string; - draggingCursor?: string; - heading?: number; - keyboardShortcuts?: bool; - mapMaker?: bool; - mapTypeControl?: bool; - mapTypeControlOptions?: MapTypeControlOptions; - mapTypeId?: MapTypeId; - maxZoom?: number; - minZoom?: number; - noClear?: bool; - overviewMapControl?: bool; - overviewMapControlOptions?: OverviewMapControlOptions; - panControl?: bool; - panControlOptions?: PanControlOptions; - rotateControl?: bool; - rotateControlOptions?: RotateControlOptions; - scaleControl?: bool; - scaleControlOptions?: ScaleControlOptions; - scrollwheel?: bool; - streetView?: bool; - streetViewControlOptions?: StreetViewControlOptions; - styles?: MapTypeStyle[]; - tilt?: number; - zoom?: number; - zoomControl?: bool; - zoomControlOptions?: ZoomControlOptions; - } - - export enum MapTypeId { - HYBRID, - ROADMAP, - SATELLITE, - TERRAIN - } - - /***** Controls *****/ - export interface MapTypeControlOptions { - mapTypeIds?: MapTypeId[]; - position?: ControlPosition; - style?: MapTypeControlStyle; - } - - export enum MapTypeControlStyle { - DEFAULT, - DROPDOWN_MENU, - HORIZONTAL_BAR - } - - export interface OverviewMapControlOptions { - opened?: bool; - } - - export interface PanControlOptions { - position: ControlPosition; - } - - export interface RotateControlOptions { - position: ControlPosition; - } - - export interface ScaleControlOptions { - position?: ControlPosition; - style?: ScaleControlStyle; - } - - export enum ScaleControlStyle { - DEFAULT - } - - export interface StreetViewControlOptions { - position: ControlPosition; - } - - export interface ZoomControlOptions { - position?: ControlPosition; - style?: ZoomControlStyle; - } - - export enum ZoomControlStyle { - DEFAULT, - LARGE, - SMALL - } - - export enum ControlPosition { - BOTTOM_CENTER, - BOTTOM_LEFT, - BOTTOM_RIGHT, - LEFT_BOTTOM, - LEFT_CENTER, - LEFT_TOP, - RIGHT_BOTTOM, - RIGHT_CENTER, - RIGHT_TOP, - TOP_CENTER, - TOP_LEFT, - TOP_RIGHT - } - - /***** Overlays *****/ - export class Marker extends MVCObject { - constructor (opts?: MarkerOptions); - getAnimation(): Animation; - getClickable(): bool; - getCursor(): string; - getDraggable(): bool; - getFlat(): bool; - getIcon(): MarkerImage; - getMap(): Map; - getMap(): StreetViewPanorama; - getPosition(): LatLng; - getShadow(): MarkerImage; - getShape(): MarkerShape; - getTitle(): string; - getVisible(): bool; - getZIndex(): number; - setAnimation(animation: Animation): void; - setClickable(flag: bool): void; - setCursor(cursor: string): void; - setDraggable(flag: bool): void; - setFlat(flag: bool): void; - setIcon(icon: MarkerImage): void; - setIcon(icon: string): void; - setMap(map: Map): void; - setMap(map: StreetViewPanorama): void; - setOptions(options: MarkerOptions): void; - setPosition(latlng: LatLng): void; - setShadow(shadow: MarkerImage): void; - setShadow(shadow: string): void; - setShape(shape: MarkerShape): void; - setTitle(title: string): void; - setVisible(visible: bool): void; - setZIndex(zIndex: number): void; - } - - export interface MarkerOptions { - animation?: Animation; - clickable?: bool; - cursor?: string; - draggable?: bool; - flat?: bool; - icon?: any; - map?: any; - optimized?: bool; - position?: LatLng; - raiseOnDrag?: bool; - shadow?: any; - shape?: MarkerShape; - title?: string; - visible?: bool; - zIndex?: number; - } - - export class MarkerImage { - constructor (url: string, size?: Size, origin?: Point, anchor?: Point, scaledSize?: Size); - anchor: Point; - origin: Point; - scaledSize: Size; - size: Size; - url: string; - } - - export interface MarkerShape { - coords?: number[]; - type?: string; - } - - export interface Symbol { - anchor?: Point; - fillColor?: string; - fillOpacity?: number; - path?: any; - rotation?: number; - scale?: number; - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - } - - export enum SymbolPath { - BACKWARD_CLOSED_ARROW, - BACKWARD_OPEN_ARROW, - CIRCLE, - FORWARD_CLOSED_ARROW, - FORWARD_OPEN_ARROW - } - - export enum Animation { - BOUNCE, - DROP - } - - export class InfoWindow extends MVCObject { - constructor (opts?: InfoWindowOptions); - close(): void; - getContent(): string; - getContent(): Element; - getPosition(): LatLng; - getZIndex(): number; - open(map?: Map, anchor?: MVCObject): void; - open(map?: StreetViewPanorama, anchor?: MVCObject): void; - setContent(content: Node): void; - setContent(content: string): void; - setOptions(options: InfoWindowOptions): void; - setPosition(position: LatLng): void; - setZIndex(zIndex: number): void; - } - - export interface InfoWindowOptions { - content?: any; - disableAutoPan?: bool; - maxWidth?: number; - pixelOffset?: Size; - position?: LatLng; - zIndex?: number; - } - - export class Polyline extends MVCObject { - constructor (opts?: PolylineOptions); - getEditable(): bool; - getMap(): Map; - getPath(): MVCArray[]; - getVisible(): bool; - setEditable(editable: bool): void; - setMap(map: Map): void; - setOptions(options: PolylineOptions): void; - setPath(path: MVCArray[]): void; - setPath(path: LatLng[]): void; - setVisible(visible: bool): void; - } - - export interface PolylineOptions { - clickable?: bool; - editable?: bool; - geodesic?: bool; - icons?: IconSequence[]; - map?: Map; - path?: any[]; - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - visible?: bool; - zIndex?: number; - } - - export interface IconSequence { - icon?: Symbol; - offset?: string; - repeat?: string; - } - - export class Polygon extends MVCObject { - constructor (opts?: PolygonOptions); - getEditable(): bool; - getMap(): Map; - getPath(): MVCArray[]; - getPaths(): MVCArray[][]; - getVisible(): bool; - setEditable(editable: bool): void; - setMap(map: Map): void; - setOptions(options: PolygonOptions): void; - setPath(path: MVCArray[]): void; - setPath(path: LatLng[]): void; - setPaths(paths: MVCArray[]): void; - setPaths(paths: MVCArray[][]): void; - setPaths(path: LatLng[]): void; - setPaths(path: LatLng[][]): void; - setVisible(visible: bool): void; - } - - export interface PolygonOptions { - clickable?: bool; - editable?: bool; - fillColor?: string; - fillOpacity?: number; - geodesic?: bool; - map?: Map; - paths?: any[]; - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - visible?: bool; - zIndex?: number; - } - - export interface PolyMouseEvent { - edge?: number; - path?: number; - vertex?: number; - } - - export class Rectangle extends MVCObject { - constructor (opts?: RectangleOptions); - getBounds(): LatLngBounds; - getEditable(): bool; - getMap(): Map; - getVisible(): bool; - setBounds(bounds: LatLngBounds): void; - setEditable(editable: bool): void; - setMap(map: Map): void; - setOptions(options: RectangleOptions): void; - setVisible(visible: bool): void; - } - - export interface RectangleOptions { - bounds?: LatLngBounds; - clickable?: bool; - editable?: bool; - fillColor?: string; - fillOpacity?: number; - map?: Map; - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - visible?: bool; - zIndex?: number; - } - - export class Circle extends MVCObject { - constructor (opts?: CircleOptions); - getBounds(): LatLngBounds; - getCenter(): LatLng; - getEditable(): bool; - getMap(): Map; - getRadius(): number; - getVisible(): bool; - setCenter(center: LatLng): void; - setEditable(editable: bool): void; - setMap(map: Map): void; - setOptions(options: CircleOptions): void; - setRadius(radius: number): void; - setVisible(visible: bool): void; - } - - export interface CircleOptions { - center?: LatLng; - clickable?: bool; - editable?: bool; - fillColor?: string; - fillOpacity?: number; - map?: Map; - radius?: number; - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - visible?: bool; - zIndex?: number; - } - - export class GroundOverlay extends MVCObject { - constructor (url: string, bounds: LatLngBounds, opts?: GroundOverlayOptions); - getBounds(): LatLngBounds; - getMap(): Map; - getOpacity(): number; - getUrl(): string; - setMap(map: Map): void; - setOpacity(opacity: number): void; - } - - export interface GroundOverlayOptions { - clickable?: bool; - map?: Map; - opacity?: number; - } - - export class OverlayView extends MVCObject { - draw(): void; - getMap(): Map; - getPanes(): MapPanes; - getProjection(): MapCanvasProjection; - onAdd(): void; - onRemove(): void; - setMap(map: Map): void; - setMap(map: StreetViewPanorama): void; - } - - export interface MapPanes { - floatPane: Element; - floatShadow: Element; - mapPane: Element; - overlayImage: Element; - overlayLayer: Element; - overlayMouseTarget: Element; - overlayShadow: Element; - } - - export class MapCanvasProjection extends MVCObject { - fromContainerPixelToLatLng(pixel: Point, nowrap?: bool): LatLng; - fromDivPixelToLatLng(pixel: Point, nowrap?: bool): LatLng; - fromLatLngToContainerPixel(latLng: LatLng): Point; - fromLatLngToDivPixel(latLng: LatLng): Point; - getWorldWidth(): number; - } - - /***** Services *****/ - export class Geocoder { - constructor (); - geocode(request: GeocoderRequest, callback: (results: GeocoderResult[], status: GeocoderStatus) => void ): void; - } - - export interface GeocoderRequest { - address: string; - bounds?: LatLngBounds; - location?: LatLng; - region?: string; - } - - export enum GeocoderStatus { - ERROR, - INVALID_REQUEST, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR, - ZERO_RESULTS - } - - export interface GeocoderResult { - address_components: GeocoderAddressComponent[]; - formatted_address: string; - geometry: GeocoderGeometry; - types: string[]; - } - - export interface GeocoderAddressComponent { - long_name: string; - short_name: string; - types: string[]; - } - - export interface GeocoderGeometry { - bounds: LatLngBounds; - location: LatLng; - location_type: GeocoderLocationType; - viewport: LatLngBounds; - } - - export enum GeocoderLocationType { - APPROXIMATE, - GEOMETRIC_CENTER, - RANGE_INTERPOLATED, - ROOFTOP - } - - export class DirectionsRenderer extends MVCObject { - constructor (opts?: DirectionsRendererOptions); - getDirections(): DirectionsResult; - getMap(): Map; - getPanel(): Element; - getRouteIndex(): number; - setDirections(directions: DirectionsResult): void; - setMap(map: Map): void; - setOptions(options: DirectionsRendererOptions): void; - setPanel(panel: Element): void; - setRouteIndex(routeIndex: number): void; - } - - export interface DirectionsRendererOptions { - directions?: DirectionsResult; - draggable?: bool; - hideRouteList?: bool; - infoWindow?: InfoWindow; - map?: Map; - markerOptions?: MarkerOptions; - panel?: Element; - polylineOptions?: PolylineOptions; - preserveViewport?: bool; - routeIndex?: number; - suppressBicyclingLayer?: bool; - suppressInfoWindows?: bool; - suppressMarkers?: bool; - suppressPolylines?: bool; - } - - export class DirectionsService { - constructor (); - route(request: DirectionsRequest, callback: (result: DirectionsResult, status: DirectionsStatus) => void ): void; - } - - export interface DirectionsRequest { - avoidHighways?: bool; - avoidTolls?: bool; - destination?: any; - optimizeWaypoints?: bool; - origin?: any; - provideRouteAlternatives?: bool; - region?: string; - transitOptions?: TransitOptions; - travelMode?: TravelMode; - unitSystem?: UnitSystem; - waypoints?: DirectionsWaypoint[]; - } - - export enum TravelMode { - BICYCLING, - DRIVING, - TRANSIT, - WALKING - } - - export enum UnitSystem { - IMPERIAL, - METRIC - } - - export interface TransitOptions { - arrivalTime?: Date; - departureTime?: Date; - } - - export interface DirectionsWaypoint { - location: any; - stopover: bool; - } - - export enum DirectionsStatus { - INVALID_REQUEST, - MAX_WAYPOINTS_EXCEEDED, - NOT_FOUND, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR, - ZERO_RESULTS - } - - export interface DirectionsResult { - routes: DirectionsRoute[]; - } - - export interface DirectionsRoute { - bounds: LatLngBounds; - copyrights: string; - legs: DirectionsLeg[]; - overview_path: LatLng[]; - warnings: string[]; - waypoint_order: number[]; - } - - export interface DirectionsLeg { - arrival_time: Distance; - departure_time: Duration; - distance: Distance; - duration: Duration; - end_address: string; - end_location: LatLng; - start_address: string; - start_location: LatLng; - steps: DirectionsStep[]; - via_waypoints: LatLng[]; - } - - export interface DirectionsStep { - distance: Distance; - duration: Duration; - end_location: LatLng; - instructions: string; - path: LatLng[]; - start_location: LatLng; - steps: DirectionsStep; - transit: TransitDetails; - travel_mode: TravelMode; - } - - export interface Distance { - text: string; - value: number; - } - - export interface Duration { - text: string; - value: number; - } - - export interface Time { - text: string; - time_zone: string; - value: Date; - } - - export interface TransitDetails { - arrival_stop: TransitStop; - arrival_time: Time; - departure_stop: TransitStop; - departure_time: Time; - headsign: string; - headway: number; - line: TransitLine; - num_stops: number; - } - - export interface TransitStop { - location: LatLng; - name: string; - } - - export interface TransitLine { - agencies: TransitAgency[]; - color: string; - icon: string; - name: string; - short_name: string; - text_color: string; - url: string; - vehicle: TransitVehicle; - } - - export interface TransitAgency { - name: string; - phone: string; - url: string; - } - - export interface TransitVehicle { - icon: string; - local_icon: string; - name: string; - type: string; - } - - export class ElevationService { - constructor (); - getElevationAlongPath(request: PathElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; - getElevationForLocations(request: LocationElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; - } - - export interface LocationElevationRequest { - locations: LatLng[]; - } - - export interface PathElevationRequest { - path?: LatLng[]; - samples?: number; - } - - export interface ElevationResult { - elevation: number; - location: LatLng; - resolution: number; - } - - export enum ElevationStatus { - INVALID_REQUEST, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR - } - - export class MaxZoomService { - constructor (); - getMaxZoomAtLatLng(latlng: LatLng, callback: (result: MaxZoomResult) => void ): void; - } - - export interface MaxZoomResult { - status: MaxZoomStatus; - zoom: number; - } - - export enum MaxZoomStatus { - ERROR, - OK - } - - export class DistanceMatrixService { - constructor (); - getDistanceMatrix(request: DistanceMatrixRequest, callback: (response: DistanceMatrixResponse, status: DistanceMatrixStatus) => void ): void; - } - - export interface DistanceMatrixRequest { - avoidHighways?: bool; - avoidTolls?: bool; - destinations?: any[]; - origins?: any[]; - region?: string; - travelMode?: TravelMode; - unitSystem?: UnitSystem; - } - - export interface DistanceMatrixResponse { - destinationAddresses: string[]; - originAddresses: string[]; - rows: DistanceMatrixResponseRow[]; - } - - export interface DistanceMatrixResponseRow { - elements: DistanceMatrixResponseElement[]; - } - - export interface DistanceMatrixResponseElement { - distance: Distance; - duration: Duration; - status: DistanceMatrixElementStatus; - } - - export enum DistanceMatrixStatus { - INVALID_REQUEST, - MAX_DIMENSIONS_EXCEEDED, - MAX_ELEMENTS_EXCEEDED, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR - } - - export enum DistanceMatrixElementStatus { - NOT_FOUND, - OK, - ZERO_RESULTS - } - - /***** Map Types *****/ - export interface MapType { - getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; - releaseTile(tile: Element): void; - alt?: string; - maxZoom?: number; - minZoom?: number; - name?: string; - projection?: Projection; - radius?: number; - tileSize?: Size; - } - - export class MapTypeRegistry extends MVCObject { - constructor (); - set(id: string, mapType: MapType): void; - } - - export interface Projection { - fromLatLngToPoint(latLng: LatLng, point?: Point): Point; - fromPointToLatLng(pixel: Point, noWrap?: bool): LatLng; - } - - export class ImageMapType { - constructor (opts: ImageMapTypeOptions); - getOpacity(): number; - setOpacity(opacity: number): void; - } - - export interface ImageMapTypeOptions { - alt?: string; - getTileUrl: (Point, number) => string; - maxZoom?: number; - minZoom?: number; - name?: string; - opacity?: number; - tileSize?: Size; - } - - export class StyledMapType { - constructor (styles: MapTypeStyle[], options?: StyledMapTypeOptions); - } - - export interface StyledMapTypeOptions { - alt?: string; - maxZoom?: number; - minZoom?: number; - name?: string; - } - - export interface MapTypeStyle { - elementType?: MapTypeStyleElementType; - featureType?: MapTypeStyleFeatureType; - stylers?: MapTypeStyler[]; - } - - export interface MapTypeStyleFeatureType { - administrative?: { - country?: string; - land_parcel?: string; - locality?: string; - neighborhood?: string; - province?: string; - }; - all?: string; - landscape?: { - man_made?: string; - natural?: string; - }; - poi?: { - attraction?: string; - business?: string; - government?: string; - medical?: string; - park?: string; - place_of_worship?: string; - school?: string; - sports_complex?: string; - }; - road?: { - arterial?: string; - highway?: { - controlled_access?: string; - }; - local?: string; - }; - transit?: { - line?: string; - station?: { - airport?: string; - bus?: string; - rail?: string; - }; - }; - water?: string; - } - - export enum MapTypeStyleElementType { - all, - geometry, - labels - } - - export interface MapTypeStyler { - gamma?: number; - hue?: string; - invert_lightness?: bool; - lightness?: number; - saturation?: number; - visibility?: string; - } - - /***** Layers *****/ - export class BicyclingLayer extends MVCObject { - constructor (); - getMap(): Map; - setMap(map: Map): void; - } - - export class FusionTablesLayer extends MVCObject { - constructor (options: FusionTablesLayerOptions); - getMap(): Map; - setMap(map: Map): void; - setOptions(options: FusionTablesLayerOptions): void; - } - - export interface FusionTablesLayerOptions { - clickable?: bool; - heatmap?: FusionTablesHeatmap; - map?: Map; - query?: FusionTablesQuery; - styles?: FusionTablesStyle[]; - suppressInfoWindows?: bool; - } - - export interface FusionTablesQuery { - from?: string; - limit?: number; - offset?: number; - orderBy?: string; - select?: string; - where?: string; - } - - export interface FusionTablesStyle { - markerOptions?: FusionTablesMarkerOptions; - polygonOptions?: FusionTablesPolygonOptions; - polylineOptions?: FusionTablesPolylineOptions; - where?: string; - } - - export interface FusionTablesHeatmap { - enabled: bool; - } - - export interface FusionTablesMarkerOptions { - iconName: string; - } - - export interface FusionTablesPolygonOptions { - fillColor?: string; - fillOpacity?: number; - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - } - - export interface FusionTablesPolylineOptions { - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - } - - export interface FusionTablesMouseEvent { - infoWindowHtml: string; - latLng: LatLng; - pixelOffset: Size; - row: Object; - } - - export interface FusionTablesCell { - columnName: string; - value: string; - } - - export class KmlLayer extends MVCObject { - constructor (url: string, opts?: KmlLayerOptions); - getDefaultViewport(): LatLngBounds; - getMap(): Map; - getMetadata(): KmlLayerMetadata; - getStatus(): KmlLayerStatus; - getUrl(): string; - setMap(map: Map): void; - } - - export interface KmlLayerOptions { - clickable?: bool; - map?: Map; - preserveViewport?: bool; - suppressInfoWindows?: bool; - } - - export interface KmlLayerMetadata { - author: KmlAuthor; - description: string; - name: string; - snippet: string; - } - - export enum KmlLayerStatus { - DOCUMENT_NOT_FOUND, - DOCUMENT_TOO_LARGE, - FETCH_ERROR, - INVALID_DOCUMENT, - INVALID_REQUEST, - LIMITS_EXCEEDED, - OK, - TIMED_OUT, - UNKNOWN - } - - export interface KmlMouseEvent { - featureData: KmlFeatureData; - latLng: LatLng; - pixelOffset: Size; - } - - export interface KmlFeatureData { - author: KmlAuthor; - description: string; - id: string; - infoWindowHtml: string; - name: string; - snippet: string; - } - - export interface KmlAuthor { - email: string; - name: string; - uri: string; - } - - export class TrafficLayer extends MVCObject { - constructor (); - getMap(): void; - setMap(map: Map): void; - } - - export class TransitLayer extends MVCObject { - constructor (); - getMap(): void; - setMap(map: Map): void; - } - - /***** Street View *****/ - export class StreetViewPanorama { - constructor (container: Element, opts?: StreetViewPanoramaOptions); - controls: MVCArray[]; - getLinks(): StreetViewLink[]; - getPano(): string; - getPosition(): LatLng; - getPov(): StreetViewPov; - getVisible(): bool; - registerPanoProvider(provider: (input: string) => StreetViewPanoramaData); - setPano(pano: string): void; - setPosition(latLng: LatLng): void; - setPov(pov: StreetViewPov): void; - setVisible(flag: bool): void; - - } - - export interface StreetViewPanoramaOptions { - addressControl?: bool; - addressControlOptions?: StreetViewAddressControlOptions; - clickToGo?: bool; - disableDoubleClickZoom?: bool; - enableCloseButton?: bool; - imageDateControl?: bool; - linksControl?: bool; - panControl?: bool; - panControlOptions?: PanControlOptions; - pano?: string; - panoProvider?: (input: string) => StreetViewPanoramaData; - position?: LatLng; - pov?: StreetViewPov; - scrollwheel?: bool; - visible?: bool; - zoomControl?: bool; - zoomControlOptions?: ZoomControlOptions; - } - - export interface StreetViewAddressControlOptions { - position: ControlPosition; - } - - export interface StreetViewLink { - description?: string; - heading?: number; - pano?: string; - } - - export interface StreetViewPov { - heading?: number; - picth?: number; - zoom?: number; - } - - export interface StreetViewPanoramaData { - opyright?: string; - imageDate?: string; - links?: StreetViewLink[]; - location?: StreetViewLocation; - tiles?: StreetViewTileData; - } - - export interface StreetViewLocation { - description?: string; - latLng?: LatLng; - pano?: string; - } - - export interface StreetViewTileData { - centerHeading?: number; - tileSize?: Size; - worldSize?: Size; - } - - export interface StreetViewService { - getPanoramaById(pano: string, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void ); - getPanoramaByLocation(latlng: LatLng, radius: number, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void ); - } - - export enum StreetViewStatus { - OK, - UNKNOWN_ERROR, - ZERO_RESULTS - } - - /***** Base *****/ - export class LatLng { - constructor (lat: number, lng: number, noWrap?: bool); - equals(other: LatLng): bool; - lat(): number; - lng(): number; - toString(): string; - toUrlValue(precision?: number): string; - - } - - export class LatLngBounds { - constructor (sw?: LatLng, ne?: LatLng); - contains(latLng: LatLng): bool; - equals(other: LatLngBounds): bool; - extend(point: LatLng): LatLngBounds; - getCenter(): LatLng; - getNorthEast(): LatLng; - getSouthWest(): LatLng; - intersects(other: LatLngBounds): bool; - isEmpty(): bool; - toSpan(): LatLng; - toString(): string; - toUrlValue(precision?: number): string; - union(other: LatLngBounds): LatLngBounds; - } - - export class Point { - constructor (x: number, y: number); - x: number; - y: number; - equals(other: Point): bool; - toString(): string; - } - - export class Size { - constructor (width: number, height: number, widthUnit?: string, heightUnit?: string); - height: number; - width: number; - equals(other: Size): bool; - toString(): string; - } - - /***** Geometry Library *****/ - export module geometry { - export class encoding { - static decodePath(encodedPath: string): LatLng; - static encodePath(path: any[]): string; - } - - export class spherical { - static computeArea(path: any[], radius?: number): number; - static computeDistanceBetween(from: LatLng, to: LatLng, radius?: number): number; - static computeHeading(from: LatLng, to: LatLng): number; - static computeLength(path: any[], radius?: number): number; - static computeOffset(from: LatLng, distance: number, heading: number, radius?: number): LatLng; - static computeSignedArea(loop: any[], radius?: number): number; - static interpolate(from: LatLng, to: LatLng, fraction: number): LatLng; - } - - export class poly { - containsLocation(point: LatLng, polygon: Polygon): bool; - isLocationOnEdge(point: LatLng, poly: any, tolerance?: number): bool; - } - } - - /***** AdSense Library *****/ - export module adsense { - export class AdUnit extends MVCObject { - constructor (container: Element, opts: AdUnitOptions); - getChannelNumber(): string; - getContainer(): Element; - getFormat(): AdFormat; - getMap(): Map; - getPosition(): ControlPosition; - getPublisherId(): string; - setChannelNumber(channelNumber: string): void; - setFormat(format: AdFormat): void; - setMap(map: Map): void; - setPosition(position: ControlPosition): void; - } - - export interface AdUnitOptions { - channelNumber?: string; - format?: AdFormat; - map?: Map; - position?: ControlPosition; - publisherId?: string; - } - - export enum AdFormat { - BANNER, - BUTTON, - HALF_BANNER, - LARGE_RECTANGLE, - LEADERBOARD, - MEDIUM_RECTANGLE, - SKYSCRAPER, - SMALL_RECTANGLE, - SMALL_SQUARE, - SQUARE, - VERTICAL_BANNER, - WIDE_SKYSCRAPER - } - } - - /***** Panoramio Library *****/ - export module panoramio { - export class PanoramioLayer extends MVCObject { - constructor (opts?: PanoramioLayerOptions); - getMap(): Map; - getTag(): string; - getUserId(): string; - setMap(map: Map): void; - setOptions(options: PanoramioLayerOptions): void; - setTag(tag: string): void; - setUserId(userId: string): void; - } - - export interface PanoramioLayerOptions { - map?: Map; - suppressInfoWindows?: bool; - tag?: string; - userId?: string; - } - - export interface PanoramioFeature { - author: string; - photoId: string; - title: string; - url: string; - userId: string; - } - - export interface PanoramioMouseEvent { - featureDetails: PanoramioFeature; - infoWindowHtml: string; - latLng: LatLng; - pixelOffset: Size; - } - } - - export module places { - - export class Autocomplete extends MVCObject { - constructor (inputField: HTMLInputElement, opts?: AutocompleteOptions); - getBounds(): LatLngBounds; - getPlace(): PlaceResult; - setBounds(bounds: LatLngBounds): void; - setComponentRestrictions(restrictions: ComponentRestrictions): void; - setTypes(types: string[]): void; - } - - export interface AutocompleteOptions { - bounds: LatLngBounds; - componentRestrictions: ComponentRestrictions; - types: string[]; - } - - export interface ComponentRestrictions { - country: string; - } - - export interface PlaceDetailsRequest { - reference: string; - } - - export interface PlaceGeometry { - location: LatLng; - viewport: LatLngBounds; - } - - export interface PlaceResult { - address_components: GeocoderAddressComponent[]; - formatted_address: string; - formatted_phone_number: string; - geometry: PlaceGeometry; - html_attributions: string[]; - icon: string; - id: string; - international_phone_number: string; - name: string; - rating: number; - reference: string; - types: string[]; - url: string; - vicinity: string; - website: string; - } - - export interface PlaceSearchRequest { - bounds: LatLngBounds; - keyword: string; - location: LatLng; - name: string; - radius: number; - rankBy: RankBy; - types: string[]; - } - - export interface PlaceSearchPagination { - nextPage(): void; - hasNextPage: bool; - } - - export class PlacesService { - constructor (attrContainer: HTMLDivElement); - constructor (attrContainer: Map); - getDetails(request: PlaceDetailsRequest, callback: (result: PlaceResult, status: PlacesServiceStatus) => void ): void; - nearbySearch(request: PlaceSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus, pagination: PlaceSearchPagination) => void ): void; - textSearch(request: TextSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void ): void; - } - - export enum PlacesServiceStatus { - INVALID_REQUEST, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR, - ZERO_RESULTS - } - - export enum RankBy { - DISTANCE, - PROMINENCE - } - - export interface TextSearchRequest { - bounds: LatLngBounds; - location: LatLng; - query: string; - radius: number; - } - } - - export module drawing { - export class DrawingManager extends MVCObject { - constructor (options?: DrawingManagerOptions); - getDrawingMode(): OverlayType; - getMap(): Map; - setDrawingMode(drawingMode: OverlayType): void; - setMap(map: Map): void; - setOptions(options: DrawingManagerOptions): void; - } - - export interface DrawingManagerOptions { - circleOptions: CircleOptions; - drawingControl: bool; - drawingControlOptions: DrawingControlOptions; - drawingMode: OverlayType; - map: Map; - markerOptions: MarkerOptions; - polygonOptions: PolygonOptions; - polylineOptions: PolylineOptions; - rectangleOptions: RectangleOptions; - } - - export interface DrawingControlOptions { - drawingModes: OverlayType[]; - position: ControlPosition; - } - - export interface OverlayCompleteEvent { - overlay: MVCObject; - type: OverlayType; - } - - export enum OverlayType { - CIRCLE, - MARKER, - POLYGON, - POLYLINE, - RECTANGLE - } - } - - export module weather { - export class CloudLayer extends MVCObject { - constructor (); - getMap(): Map; - setMap(map: Map): void; - } - export class WeatherLayer extends MVCObject { - constructor (opts?: WeatherLayerOptions); - getMap(): Map; - setMap(map: Map): void; - setOptions(options: WeatherLayerOptions): void; - } - - export interface WeatherLayerOptions { - clickable: bool; - labelColor: LabelColor; - map: Map; - suppressInfoWindows: bool; - temperatureUnits: TemperatureUnit; - windSpeedUnits: WindSpeedUnit; - } - - export enum TemperatureUnit { - CELSIUS, - FAHRENHEIT - } - - export enum WindSpeedUnit { - KILOMETERS_PER_HOUR, - METERS_PER_SECOND, - MILES_PER_HOUR - } - - export enum LabelColor { - BLACK, - WHITE - } - - export interface WeatherMouseEvent { - featureDetails: WeatherFeature; - infoWindowHtml: string; - latLng: LatLng; - pixelOffset: Size; - } - - export interface WeatherFeature { - current: WeatherConditions; - forecast: WeatherForecast[]; - location: string; - temperatureUnit: TemperatureUnit; - windSpeedUnit: WindSpeedUnit; - } - - export interface WeatherConditions { - day: string; - description: string; - high: number; - humidity: number; - low: number; - shortDay: string; - temperature: number; - windDirection: string; - windSpeed: number; - } - - export interface WeatherForecast { - day: string; - description: string; - high: number; - low: number; - shortDay: string; - } - } - export module visualization { - export class HeatmapLayer extends MVCObject { - constructor (opts?: HeatmapLayerOptions); - getData(): MVCArray; - getMap(): Map; - setData(data: MVCArray): void; - setData(data: LatLng[]): void; - setData(data: WeightedLocation[]): void; - setMap(map: Map): void; - } - - export interface HeatmapLayerOptions { - data: LatLng[]; - dissipating: bool; - gradient: string[]; - map: Map; - maxIntensity: number; - opacity: number; - radius: number; - } - - export interface WeightedLocation { - location: LatLng; - weight: number; - } - } -} - +/* +The MIT License + +Copyright (c) 2012 Folia A/S. http://www.folia.dk + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +declare module google.maps { + + /***** MVC *****/ + export class MVCObject { + constructor (); + bindTo(key: string, target: MVCObject, targetKey?: string, noNotify?: bool): void; + changed(key: string): void; + get(key: string): any; + notify(key: string): void; + set(key: string, value: any): void; + setValues(values: any): void; + setValues(values: undefined); + unbind(key: string): void; + unbindAll(): void; + } + + export class MVCArray extends MVCObject { + constructor (array?: any[]); + clear(): void; + forEach(callback: (elem: any, index: number) => void ): void; + getArray(): any[]; + getAt(i: number): any; + getLength(): number; + insertAt(i: number, elem: any): void; + pop(): void; + push(elem: any): number; + removeAt(i: number): any; + setAt(i: number, elem: any): void; + } + + /***** Map *****/ + export class Map extends MVCObject { + constructor (mapDiv: Element, opts?: MapOptions); + fitBounds(bounds: LatLngBounds); + getBounds(): LatLngBounds; + getCenter(): LatLng; + getDiv(): Element; + getHeading(): number; + getMapTypeId(): MapTypeId; + getProjection(): Projection; + getStreetView(): StreetViewPanorama; + getTilt(): number; + getZoom(): number; + panBy(x: number, y: number): void; + panTo(latLng: LatLng): void; + panToBounds(latLngBounds: LatLngBounds): void; + setCenter(latlng: LatLng): void; + setHeading(heading: number): void; + setMapTypeId(mapTypeId: MapTypeId): void; + setOptions(options: MapOptions): void; + setStreetView(panorama: StreetViewPanorama): void; + setTilt(tilt: number): void; + setZoom(zoom: number): void; + } + + export interface MapOptions { + backgroundColor?: string; + center?: LatLng; + disableDefaultUI?: bool; + disableDoubleClickZoom?: bool; + draggable?: bool; + draggableCursor?: string; + draggingCursor?: string; + heading?: number; + keyboardShortcuts?: bool; + mapMaker?: bool; + mapTypeControl?: bool; + mapTypeControlOptions?: MapTypeControlOptions; + mapTypeId?: MapTypeId; + maxZoom?: number; + minZoom?: number; + noClear?: bool; + overviewMapControl?: bool; + overviewMapControlOptions?: OverviewMapControlOptions; + panControl?: bool; + panControlOptions?: PanControlOptions; + rotateControl?: bool; + rotateControlOptions?: RotateControlOptions; + scaleControl?: bool; + scaleControlOptions?: ScaleControlOptions; + scrollwheel?: bool; + streetView?: bool; + streetViewControlOptions?: StreetViewControlOptions; + styles?: MapTypeStyle[]; + tilt?: number; + zoom?: number; + zoomControl?: bool; + zoomControlOptions?: ZoomControlOptions; + } + + export enum MapTypeId { + HYBRID, + ROADMAP, + SATELLITE, + TERRAIN + } + + /***** Controls *****/ + export interface MapTypeControlOptions { + mapTypeIds?: MapTypeId[]; + position?: ControlPosition; + style?: MapTypeControlStyle; + } + + export enum MapTypeControlStyle { + DEFAULT, + DROPDOWN_MENU, + HORIZONTAL_BAR + } + + export interface OverviewMapControlOptions { + opened?: bool; + } + + export interface PanControlOptions { + position: ControlPosition; + } + + export interface RotateControlOptions { + position: ControlPosition; + } + + export interface ScaleControlOptions { + position?: ControlPosition; + style?: ScaleControlStyle; + } + + export enum ScaleControlStyle { + DEFAULT + } + + export interface StreetViewControlOptions { + position: ControlPosition; + } + + export interface ZoomControlOptions { + position?: ControlPosition; + style?: ZoomControlStyle; + } + + export enum ZoomControlStyle { + DEFAULT, + LARGE, + SMALL + } + + export enum ControlPosition { + BOTTOM_CENTER, + BOTTOM_LEFT, + BOTTOM_RIGHT, + LEFT_BOTTOM, + LEFT_CENTER, + LEFT_TOP, + RIGHT_BOTTOM, + RIGHT_CENTER, + RIGHT_TOP, + TOP_CENTER, + TOP_LEFT, + TOP_RIGHT + } + + /***** Overlays *****/ + export class Marker extends MVCObject { + constructor (opts?: MarkerOptions); + getAnimation(): Animation; + getClickable(): bool; + getCursor(): string; + getDraggable(): bool; + getFlat(): bool; + getIcon(): MarkerImage; + getMap(): Map; + getMap(): StreetViewPanorama; + getPosition(): LatLng; + getShadow(): MarkerImage; + getShape(): MarkerShape; + getTitle(): string; + getVisible(): bool; + getZIndex(): number; + setAnimation(animation: Animation): void; + setClickable(flag: bool): void; + setCursor(cursor: string): void; + setDraggable(flag: bool): void; + setFlat(flag: bool): void; + setIcon(icon: MarkerImage): void; + setIcon(icon: string): void; + setMap(map: Map): void; + setMap(map: StreetViewPanorama): void; + setOptions(options: MarkerOptions): void; + setPosition(latlng: LatLng): void; + setShadow(shadow: MarkerImage): void; + setShadow(shadow: string): void; + setShape(shape: MarkerShape): void; + setTitle(title: string): void; + setVisible(visible: bool): void; + setZIndex(zIndex: number): void; + } + + export interface MarkerOptions { + animation?: Animation; + clickable?: bool; + cursor?: string; + draggable?: bool; + flat?: bool; + icon?: any; + map?: any; + optimized?: bool; + position?: LatLng; + raiseOnDrag?: bool; + shadow?: any; + shape?: MarkerShape; + title?: string; + visible?: bool; + zIndex?: number; + } + + export class MarkerImage { + constructor (url: string, size?: Size, origin?: Point, anchor?: Point, scaledSize?: Size); + anchor: Point; + origin: Point; + scaledSize: Size; + size: Size; + url: string; + } + + export interface MarkerShape { + coords?: number[]; + type?: string; + } + + export interface Symbol { + anchor?: Point; + fillColor?: string; + fillOpacity?: number; + path?: any; + rotation?: number; + scale?: number; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + } + + export enum SymbolPath { + BACKWARD_CLOSED_ARROW, + BACKWARD_OPEN_ARROW, + CIRCLE, + FORWARD_CLOSED_ARROW, + FORWARD_OPEN_ARROW + } + + export enum Animation { + BOUNCE, + DROP + } + + export class InfoWindow extends MVCObject { + constructor (opts?: InfoWindowOptions); + close(): void; + getContent(): string; + getContent(): Element; + getPosition(): LatLng; + getZIndex(): number; + open(map?: Map, anchor?: MVCObject): void; + open(map?: StreetViewPanorama, anchor?: MVCObject): void; + setContent(content: Node): void; + setContent(content: string): void; + setOptions(options: InfoWindowOptions): void; + setPosition(position: LatLng): void; + setZIndex(zIndex: number): void; + } + + export interface InfoWindowOptions { + content?: any; + disableAutoPan?: bool; + maxWidth?: number; + pixelOffset?: Size; + position?: LatLng; + zIndex?: number; + } + + export class Polyline extends MVCObject { + constructor (opts?: PolylineOptions); + getEditable(): bool; + getMap(): Map; + getPath(): MVCArray[]; + getVisible(): bool; + setEditable(editable: bool): void; + setMap(map: Map): void; + setOptions(options: PolylineOptions): void; + setPath(path: MVCArray[]): void; + setPath(path: LatLng[]): void; + setVisible(visible: bool): void; + } + + export interface PolylineOptions { + clickable?: bool; + editable?: bool; + geodesic?: bool; + icons?: IconSequence[]; + map?: Map; + path?: any[]; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + visible?: bool; + zIndex?: number; + } + + export interface IconSequence { + icon?: Symbol; + offset?: string; + repeat?: string; + } + + export class Polygon extends MVCObject { + constructor (opts?: PolygonOptions); + getEditable(): bool; + getMap(): Map; + getPath(): MVCArray[]; + getPaths(): MVCArray[][]; + getVisible(): bool; + setEditable(editable: bool): void; + setMap(map: Map): void; + setOptions(options: PolygonOptions): void; + setPath(path: MVCArray[]): void; + setPath(path: LatLng[]): void; + setPaths(paths: MVCArray[]): void; + setPaths(paths: MVCArray[][]): void; + setPaths(path: LatLng[]): void; + setPaths(path: LatLng[][]): void; + setVisible(visible: bool): void; + } + + export interface PolygonOptions { + clickable?: bool; + editable?: bool; + fillColor?: string; + fillOpacity?: number; + geodesic?: bool; + map?: Map; + paths?: any[]; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + visible?: bool; + zIndex?: number; + } + + export interface PolyMouseEvent { + edge?: number; + path?: number; + vertex?: number; + } + + export class Rectangle extends MVCObject { + constructor (opts?: RectangleOptions); + getBounds(): LatLngBounds; + getEditable(): bool; + getMap(): Map; + getVisible(): bool; + setBounds(bounds: LatLngBounds): void; + setEditable(editable: bool): void; + setMap(map: Map): void; + setOptions(options: RectangleOptions): void; + setVisible(visible: bool): void; + } + + export interface RectangleOptions { + bounds?: LatLngBounds; + clickable?: bool; + editable?: bool; + fillColor?: string; + fillOpacity?: number; + map?: Map; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + visible?: bool; + zIndex?: number; + } + + export class Circle extends MVCObject { + constructor (opts?: CircleOptions); + getBounds(): LatLngBounds; + getCenter(): LatLng; + getEditable(): bool; + getMap(): Map; + getRadius(): number; + getVisible(): bool; + setCenter(center: LatLng): void; + setEditable(editable: bool): void; + setMap(map: Map): void; + setOptions(options: CircleOptions): void; + setRadius(radius: number): void; + setVisible(visible: bool): void; + } + + export interface CircleOptions { + center?: LatLng; + clickable?: bool; + editable?: bool; + fillColor?: string; + fillOpacity?: number; + map?: Map; + radius?: number; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + visible?: bool; + zIndex?: number; + } + + export class GroundOverlay extends MVCObject { + constructor (url: string, bounds: LatLngBounds, opts?: GroundOverlayOptions); + getBounds(): LatLngBounds; + getMap(): Map; + getOpacity(): number; + getUrl(): string; + setMap(map: Map): void; + setOpacity(opacity: number): void; + } + + export interface GroundOverlayOptions { + clickable?: bool; + map?: Map; + opacity?: number; + } + + export class OverlayView extends MVCObject { + draw(): void; + getMap(): Map; + getPanes(): MapPanes; + getProjection(): MapCanvasProjection; + onAdd(): void; + onRemove(): void; + setMap(map: Map): void; + setMap(map: StreetViewPanorama): void; + } + + export interface MapPanes { + floatPane: Element; + floatShadow: Element; + mapPane: Element; + overlayImage: Element; + overlayLayer: Element; + overlayMouseTarget: Element; + overlayShadow: Element; + } + + export class MapCanvasProjection extends MVCObject { + fromContainerPixelToLatLng(pixel: Point, nowrap?: bool): LatLng; + fromDivPixelToLatLng(pixel: Point, nowrap?: bool): LatLng; + fromLatLngToContainerPixel(latLng: LatLng): Point; + fromLatLngToDivPixel(latLng: LatLng): Point; + getWorldWidth(): number; + } + + /***** Services *****/ + export class Geocoder { + constructor (); + geocode(request: GeocoderRequest, callback: (results: GeocoderResult[], status: GeocoderStatus) => void ): void; + } + + export interface GeocoderRequest { + address: string; + bounds?: LatLngBounds; + location?: LatLng; + region?: string; + } + + export enum GeocoderStatus { + ERROR, + INVALID_REQUEST, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + export interface GeocoderResult { + address_components: GeocoderAddressComponent[]; + formatted_address: string; + geometry: GeocoderGeometry; + types: string[]; + } + + export interface GeocoderAddressComponent { + long_name: string; + short_name: string; + types: string[]; + } + + export interface GeocoderGeometry { + bounds: LatLngBounds; + location: LatLng; + location_type: GeocoderLocationType; + viewport: LatLngBounds; + } + + export enum GeocoderLocationType { + APPROXIMATE, + GEOMETRIC_CENTER, + RANGE_INTERPOLATED, + ROOFTOP + } + + export class DirectionsRenderer extends MVCObject { + constructor (opts?: DirectionsRendererOptions); + getDirections(): DirectionsResult; + getMap(): Map; + getPanel(): Element; + getRouteIndex(): number; + setDirections(directions: DirectionsResult): void; + setMap(map: Map): void; + setOptions(options: DirectionsRendererOptions): void; + setPanel(panel: Element): void; + setRouteIndex(routeIndex: number): void; + } + + export interface DirectionsRendererOptions { + directions?: DirectionsResult; + draggable?: bool; + hideRouteList?: bool; + infoWindow?: InfoWindow; + map?: Map; + markerOptions?: MarkerOptions; + panel?: Element; + polylineOptions?: PolylineOptions; + preserveViewport?: bool; + routeIndex?: number; + suppressBicyclingLayer?: bool; + suppressInfoWindows?: bool; + suppressMarkers?: bool; + suppressPolylines?: bool; + } + + export class DirectionsService { + constructor (); + route(request: DirectionsRequest, callback: (result: DirectionsResult, status: DirectionsStatus) => void ): void; + } + + export interface DirectionsRequest { + avoidHighways?: bool; + avoidTolls?: bool; + destination?: any; + optimizeWaypoints?: bool; + origin?: any; + provideRouteAlternatives?: bool; + region?: string; + transitOptions?: TransitOptions; + travelMode?: TravelMode; + unitSystem?: UnitSystem; + waypoints?: DirectionsWaypoint[]; + } + + export enum TravelMode { + BICYCLING, + DRIVING, + TRANSIT, + WALKING + } + + export enum UnitSystem { + IMPERIAL, + METRIC + } + + export interface TransitOptions { + arrivalTime?: Date; + departureTime?: Date; + } + + export interface DirectionsWaypoint { + location: any; + stopover: bool; + } + + export enum DirectionsStatus { + INVALID_REQUEST, + MAX_WAYPOINTS_EXCEEDED, + NOT_FOUND, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + export interface DirectionsResult { + routes: DirectionsRoute[]; + } + + export interface DirectionsRoute { + bounds: LatLngBounds; + copyrights: string; + legs: DirectionsLeg[]; + overview_path: LatLng[]; + warnings: string[]; + waypoint_order: number[]; + } + + export interface DirectionsLeg { + arrival_time: Distance; + departure_time: Duration; + distance: Distance; + duration: Duration; + end_address: string; + end_location: LatLng; + start_address: string; + start_location: LatLng; + steps: DirectionsStep[]; + via_waypoints: LatLng[]; + } + + export interface DirectionsStep { + distance: Distance; + duration: Duration; + end_location: LatLng; + instructions: string; + path: LatLng[]; + start_location: LatLng; + steps: DirectionsStep; + transit: TransitDetails; + travel_mode: TravelMode; + } + + export interface Distance { + text: string; + value: number; + } + + export interface Duration { + text: string; + value: number; + } + + export interface Time { + text: string; + time_zone: string; + value: Date; + } + + export interface TransitDetails { + arrival_stop: TransitStop; + arrival_time: Time; + departure_stop: TransitStop; + departure_time: Time; + headsign: string; + headway: number; + line: TransitLine; + num_stops: number; + } + + export interface TransitStop { + location: LatLng; + name: string; + } + + export interface TransitLine { + agencies: TransitAgency[]; + color: string; + icon: string; + name: string; + short_name: string; + text_color: string; + url: string; + vehicle: TransitVehicle; + } + + export interface TransitAgency { + name: string; + phone: string; + url: string; + } + + export interface TransitVehicle { + icon: string; + local_icon: string; + name: string; + type: string; + } + + export class ElevationService { + constructor (); + getElevationAlongPath(request: PathElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; + getElevationForLocations(request: LocationElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; + } + + export interface LocationElevationRequest { + locations: LatLng[]; + } + + export interface PathElevationRequest { + path?: LatLng[]; + samples?: number; + } + + export interface ElevationResult { + elevation: number; + location: LatLng; + resolution: number; + } + + export enum ElevationStatus { + INVALID_REQUEST, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR + } + + export class MaxZoomService { + constructor (); + getMaxZoomAtLatLng(latlng: LatLng, callback: (result: MaxZoomResult) => void ): void; + } + + export interface MaxZoomResult { + status: MaxZoomStatus; + zoom: number; + } + + export enum MaxZoomStatus { + ERROR, + OK + } + + export class DistanceMatrixService { + constructor (); + getDistanceMatrix(request: DistanceMatrixRequest, callback: (response: DistanceMatrixResponse, status: DistanceMatrixStatus) => void ): void; + } + + export interface DistanceMatrixRequest { + avoidHighways?: bool; + avoidTolls?: bool; + destinations?: any[]; + origins?: any[]; + region?: string; + travelMode?: TravelMode; + unitSystem?: UnitSystem; + } + + export interface DistanceMatrixResponse { + destinationAddresses: string[]; + originAddresses: string[]; + rows: DistanceMatrixResponseRow[]; + } + + export interface DistanceMatrixResponseRow { + elements: DistanceMatrixResponseElement[]; + } + + export interface DistanceMatrixResponseElement { + distance: Distance; + duration: Duration; + status: DistanceMatrixElementStatus; + } + + export enum DistanceMatrixStatus { + INVALID_REQUEST, + MAX_DIMENSIONS_EXCEEDED, + MAX_ELEMENTS_EXCEEDED, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR + } + + export enum DistanceMatrixElementStatus { + NOT_FOUND, + OK, + ZERO_RESULTS + } + + /***** Map Types *****/ + export interface MapType { + getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; + releaseTile(tile: Element): void; + alt?: string; + maxZoom?: number; + minZoom?: number; + name?: string; + projection?: Projection; + radius?: number; + tileSize?: Size; + } + + export class MapTypeRegistry extends MVCObject { + constructor (); + set(id: string, mapType: MapType): void; + } + + export interface Projection { + fromLatLngToPoint(latLng: LatLng, point?: Point): Point; + fromPointToLatLng(pixel: Point, noWrap?: bool): LatLng; + } + + export class ImageMapType { + constructor (opts: ImageMapTypeOptions); + getOpacity(): number; + setOpacity(opacity: number): void; + } + + export interface ImageMapTypeOptions { + alt?: string; + getTileUrl: (Point, number) => string; + maxZoom?: number; + minZoom?: number; + name?: string; + opacity?: number; + tileSize?: Size; + } + + export class StyledMapType { + constructor (styles: MapTypeStyle[], options?: StyledMapTypeOptions); + } + + export interface StyledMapTypeOptions { + alt?: string; + maxZoom?: number; + minZoom?: number; + name?: string; + } + + export interface MapTypeStyle { + elementType?: MapTypeStyleElementType; + featureType?: MapTypeStyleFeatureType; + stylers?: MapTypeStyler[]; + } + + export interface MapTypeStyleFeatureType { + administrative?: { + country?: string; + land_parcel?: string; + locality?: string; + neighborhood?: string; + province?: string; + }; + all?: string; + landscape?: { + man_made?: string; + natural?: string; + }; + poi?: { + attraction?: string; + business?: string; + government?: string; + medical?: string; + park?: string; + place_of_worship?: string; + school?: string; + sports_complex?: string; + }; + road?: { + arterial?: string; + highway?: { + controlled_access?: string; + }; + local?: string; + }; + transit?: { + line?: string; + station?: { + airport?: string; + bus?: string; + rail?: string; + }; + }; + water?: string; + } + + export enum MapTypeStyleElementType { + all, + geometry, + labels + } + + export interface MapTypeStyler { + gamma?: number; + hue?: string; + invert_lightness?: bool; + lightness?: number; + saturation?: number; + visibility?: string; + } + + /***** Layers *****/ + export class BicyclingLayer extends MVCObject { + constructor (); + getMap(): Map; + setMap(map: Map): void; + } + + export class FusionTablesLayer extends MVCObject { + constructor (options: FusionTablesLayerOptions); + getMap(): Map; + setMap(map: Map): void; + setOptions(options: FusionTablesLayerOptions): void; + } + + export interface FusionTablesLayerOptions { + clickable?: bool; + heatmap?: FusionTablesHeatmap; + map?: Map; + query?: FusionTablesQuery; + styles?: FusionTablesStyle[]; + suppressInfoWindows?: bool; + } + + export interface FusionTablesQuery { + from?: string; + limit?: number; + offset?: number; + orderBy?: string; + select?: string; + where?: string; + } + + export interface FusionTablesStyle { + markerOptions?: FusionTablesMarkerOptions; + polygonOptions?: FusionTablesPolygonOptions; + polylineOptions?: FusionTablesPolylineOptions; + where?: string; + } + + export interface FusionTablesHeatmap { + enabled: bool; + } + + export interface FusionTablesMarkerOptions { + iconName: string; + } + + export interface FusionTablesPolygonOptions { + fillColor?: string; + fillOpacity?: number; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + } + + export interface FusionTablesPolylineOptions { + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + } + + export interface FusionTablesMouseEvent { + infoWindowHtml: string; + latLng: LatLng; + pixelOffset: Size; + row: Object; + } + + export interface FusionTablesCell { + columnName: string; + value: string; + } + + export class KmlLayer extends MVCObject { + constructor (url: string, opts?: KmlLayerOptions); + getDefaultViewport(): LatLngBounds; + getMap(): Map; + getMetadata(): KmlLayerMetadata; + getStatus(): KmlLayerStatus; + getUrl(): string; + setMap(map: Map): void; + } + + export interface KmlLayerOptions { + clickable?: bool; + map?: Map; + preserveViewport?: bool; + suppressInfoWindows?: bool; + } + + export interface KmlLayerMetadata { + author: KmlAuthor; + description: string; + name: string; + snippet: string; + } + + export enum KmlLayerStatus { + DOCUMENT_NOT_FOUND, + DOCUMENT_TOO_LARGE, + FETCH_ERROR, + INVALID_DOCUMENT, + INVALID_REQUEST, + LIMITS_EXCEEDED, + OK, + TIMED_OUT, + UNKNOWN + } + + export interface KmlMouseEvent { + featureData: KmlFeatureData; + latLng: LatLng; + pixelOffset: Size; + } + + export interface KmlFeatureData { + author: KmlAuthor; + description: string; + id: string; + infoWindowHtml: string; + name: string; + snippet: string; + } + + export interface KmlAuthor { + email: string; + name: string; + uri: string; + } + + export class TrafficLayer extends MVCObject { + constructor (); + getMap(): void; + setMap(map: Map): void; + } + + export class TransitLayer extends MVCObject { + constructor (); + getMap(): void; + setMap(map: Map): void; + } + + /***** Street View *****/ + export class StreetViewPanorama { + constructor (container: Element, opts?: StreetViewPanoramaOptions); + controls: MVCArray[]; + getLinks(): StreetViewLink[]; + getPano(): string; + getPosition(): LatLng; + getPov(): StreetViewPov; + getVisible(): bool; + registerPanoProvider(provider: (input: string) => StreetViewPanoramaData); + setPano(pano: string): void; + setPosition(latLng: LatLng): void; + setPov(pov: StreetViewPov): void; + setVisible(flag: bool): void; + + } + + export interface StreetViewPanoramaOptions { + addressControl?: bool; + addressControlOptions?: StreetViewAddressControlOptions; + clickToGo?: bool; + disableDoubleClickZoom?: bool; + enableCloseButton?: bool; + imageDateControl?: bool; + linksControl?: bool; + panControl?: bool; + panControlOptions?: PanControlOptions; + pano?: string; + panoProvider?: (input: string) => StreetViewPanoramaData; + position?: LatLng; + pov?: StreetViewPov; + scrollwheel?: bool; + visible?: bool; + zoomControl?: bool; + zoomControlOptions?: ZoomControlOptions; + } + + export interface StreetViewAddressControlOptions { + position: ControlPosition; + } + + export interface StreetViewLink { + description?: string; + heading?: number; + pano?: string; + } + + export interface StreetViewPov { + heading?: number; + picth?: number; + zoom?: number; + } + + export interface StreetViewPanoramaData { + opyright?: string; + imageDate?: string; + links?: StreetViewLink[]; + location?: StreetViewLocation; + tiles?: StreetViewTileData; + } + + export interface StreetViewLocation { + description?: string; + latLng?: LatLng; + pano?: string; + } + + export interface StreetViewTileData { + centerHeading?: number; + tileSize?: Size; + worldSize?: Size; + } + + export interface StreetViewService { + getPanoramaById(pano: string, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void ); + getPanoramaByLocation(latlng: LatLng, radius: number, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void ); + } + + export enum StreetViewStatus { + OK, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + /***** Base *****/ + export class LatLng { + constructor (lat: number, lng: number, noWrap?: bool); + equals(other: LatLng): bool; + lat(): number; + lng(): number; + toString(): string; + toUrlValue(precision?: number): string; + + } + + export class LatLngBounds { + constructor (sw?: LatLng, ne?: LatLng); + contains(latLng: LatLng): bool; + equals(other: LatLngBounds): bool; + extend(point: LatLng): LatLngBounds; + getCenter(): LatLng; + getNorthEast(): LatLng; + getSouthWest(): LatLng; + intersects(other: LatLngBounds): bool; + isEmpty(): bool; + toSpan(): LatLng; + toString(): string; + toUrlValue(precision?: number): string; + union(other: LatLngBounds): LatLngBounds; + } + + export class Point { + constructor (x: number, y: number); + x: number; + y: number; + equals(other: Point): bool; + toString(): string; + } + + export class Size { + constructor (width: number, height: number, widthUnit?: string, heightUnit?: string); + height: number; + width: number; + equals(other: Size): bool; + toString(): string; + } + + /***** Geometry Library *****/ + export module geometry { + export class encoding { + static decodePath(encodedPath: string): LatLng; + static encodePath(path: any[]): string; + } + + export class spherical { + static computeArea(path: any[], radius?: number): number; + static computeDistanceBetween(from: LatLng, to: LatLng, radius?: number): number; + static computeHeading(from: LatLng, to: LatLng): number; + static computeLength(path: any[], radius?: number): number; + static computeOffset(from: LatLng, distance: number, heading: number, radius?: number): LatLng; + static computeSignedArea(loop: any[], radius?: number): number; + static interpolate(from: LatLng, to: LatLng, fraction: number): LatLng; + } + + export class poly { + containsLocation(point: LatLng, polygon: Polygon): bool; + isLocationOnEdge(point: LatLng, poly: any, tolerance?: number): bool; + } + } + + /***** AdSense Library *****/ + export module adsense { + export class AdUnit extends MVCObject { + constructor (container: Element, opts: AdUnitOptions); + getChannelNumber(): string; + getContainer(): Element; + getFormat(): AdFormat; + getMap(): Map; + getPosition(): ControlPosition; + getPublisherId(): string; + setChannelNumber(channelNumber: string): void; + setFormat(format: AdFormat): void; + setMap(map: Map): void; + setPosition(position: ControlPosition): void; + } + + export interface AdUnitOptions { + channelNumber?: string; + format?: AdFormat; + map?: Map; + position?: ControlPosition; + publisherId?: string; + } + + export enum AdFormat { + BANNER, + BUTTON, + HALF_BANNER, + LARGE_RECTANGLE, + LEADERBOARD, + MEDIUM_RECTANGLE, + SKYSCRAPER, + SMALL_RECTANGLE, + SMALL_SQUARE, + SQUARE, + VERTICAL_BANNER, + WIDE_SKYSCRAPER + } + } + + /***** Panoramio Library *****/ + export module panoramio { + export class PanoramioLayer extends MVCObject { + constructor (opts?: PanoramioLayerOptions); + getMap(): Map; + getTag(): string; + getUserId(): string; + setMap(map: Map): void; + setOptions(options: PanoramioLayerOptions): void; + setTag(tag: string): void; + setUserId(userId: string): void; + } + + export interface PanoramioLayerOptions { + map?: Map; + suppressInfoWindows?: bool; + tag?: string; + userId?: string; + } + + export interface PanoramioFeature { + author: string; + photoId: string; + title: string; + url: string; + userId: string; + } + + export interface PanoramioMouseEvent { + featureDetails: PanoramioFeature; + infoWindowHtml: string; + latLng: LatLng; + pixelOffset: Size; + } + } + + export module places { + + export class Autocomplete extends MVCObject { + constructor (inputField: HTMLInputElement, opts?: AutocompleteOptions); + getBounds(): LatLngBounds; + getPlace(): PlaceResult; + setBounds(bounds: LatLngBounds): void; + setComponentRestrictions(restrictions: ComponentRestrictions): void; + setTypes(types: string[]): void; + } + + export interface AutocompleteOptions { + bounds: LatLngBounds; + componentRestrictions: ComponentRestrictions; + types: string[]; + } + + export interface ComponentRestrictions { + country: string; + } + + export interface PlaceDetailsRequest { + reference: string; + } + + export interface PlaceGeometry { + location: LatLng; + viewport: LatLngBounds; + } + + export interface PlaceResult { + address_components: GeocoderAddressComponent[]; + formatted_address: string; + formatted_phone_number: string; + geometry: PlaceGeometry; + html_attributions: string[]; + icon: string; + id: string; + international_phone_number: string; + name: string; + rating: number; + reference: string; + types: string[]; + url: string; + vicinity: string; + website: string; + } + + export interface PlaceSearchRequest { + bounds: LatLngBounds; + keyword: string; + location: LatLng; + name: string; + radius: number; + rankBy: RankBy; + types: string[]; + } + + export interface PlaceSearchPagination { + nextPage(): void; + hasNextPage: bool; + } + + export class PlacesService { + constructor (attrContainer: HTMLDivElement); + constructor (attrContainer: Map); + getDetails(request: PlaceDetailsRequest, callback: (result: PlaceResult, status: PlacesServiceStatus) => void ): void; + nearbySearch(request: PlaceSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus, pagination: PlaceSearchPagination) => void ): void; + textSearch(request: TextSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void ): void; + } + + export enum PlacesServiceStatus { + INVALID_REQUEST, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + export enum RankBy { + DISTANCE, + PROMINENCE + } + + export interface TextSearchRequest { + bounds: LatLngBounds; + location: LatLng; + query: string; + radius: number; + } + } + + export module drawing { + export class DrawingManager extends MVCObject { + constructor (options?: DrawingManagerOptions); + getDrawingMode(): OverlayType; + getMap(): Map; + setDrawingMode(drawingMode: OverlayType): void; + setMap(map: Map): void; + setOptions(options: DrawingManagerOptions): void; + } + + export interface DrawingManagerOptions { + circleOptions: CircleOptions; + drawingControl: bool; + drawingControlOptions: DrawingControlOptions; + drawingMode: OverlayType; + map: Map; + markerOptions: MarkerOptions; + polygonOptions: PolygonOptions; + polylineOptions: PolylineOptions; + rectangleOptions: RectangleOptions; + } + + export interface DrawingControlOptions { + drawingModes: OverlayType[]; + position: ControlPosition; + } + + export interface OverlayCompleteEvent { + overlay: MVCObject; + type: OverlayType; + } + + export enum OverlayType { + CIRCLE, + MARKER, + POLYGON, + POLYLINE, + RECTANGLE + } + } + + export module weather { + export class CloudLayer extends MVCObject { + constructor (); + getMap(): Map; + setMap(map: Map): void; + } + export class WeatherLayer extends MVCObject { + constructor (opts?: WeatherLayerOptions); + getMap(): Map; + setMap(map: Map): void; + setOptions(options: WeatherLayerOptions): void; + } + + export interface WeatherLayerOptions { + clickable: bool; + labelColor: LabelColor; + map: Map; + suppressInfoWindows: bool; + temperatureUnits: TemperatureUnit; + windSpeedUnits: WindSpeedUnit; + } + + export enum TemperatureUnit { + CELSIUS, + FAHRENHEIT + } + + export enum WindSpeedUnit { + KILOMETERS_PER_HOUR, + METERS_PER_SECOND, + MILES_PER_HOUR + } + + export enum LabelColor { + BLACK, + WHITE + } + + export interface WeatherMouseEvent { + featureDetails: WeatherFeature; + infoWindowHtml: string; + latLng: LatLng; + pixelOffset: Size; + } + + export interface WeatherFeature { + current: WeatherConditions; + forecast: WeatherForecast[]; + location: string; + temperatureUnit: TemperatureUnit; + windSpeedUnit: WindSpeedUnit; + } + + export interface WeatherConditions { + day: string; + description: string; + high: number; + humidity: number; + low: number; + shortDay: string; + temperature: number; + windDirection: string; + windSpeed: number; + } + + export interface WeatherForecast { + day: string; + description: string; + high: number; + low: number; + shortDay: string; + } + } + export module visualization { + export class HeatmapLayer extends MVCObject { + constructor (opts?: HeatmapLayerOptions); + getData(): MVCArray; + getMap(): Map; + setData(data: MVCArray): void; + setData(data: LatLng[]): void; + setData(data: WeightedLocation[]): void; + setMap(map: Map): void; + } + + export interface HeatmapLayerOptions { + data: LatLng[]; + dissipating: bool; + gradient: string[]; + map: Map; + maxIntensity: number; + opacity: number; + radius: number; + } + + export interface WeightedLocation { + location: LatLng; + weight: number; + } + } + + export class MouseEvent { + stop(): void; + } + + export class MapsEventListener { + + } + + export module event { + export function addDomListener(instance: Object, eventName: string, handler: Function, capture?: bool): MapsEventListener; + export function addDomListenerOnce(instance: Object, eventName:string, handler:Function, capture?: bool): MapsEventListener; + export function addListener(instance: Object, eventName: string, handler: Function): MapsEventListener; + export function addListenerOnce(instance:Object, eventName: string, handler: Function): MapsEventListener; + export function clearInstanceListeners(instance: Object): void; + export function clearListeners(instance: Object, eventName: string): void ; + export function removeListener(listener: MapsEventListener): void; + export function trigger(instance:Object, eventName:string, var_args?:any): void; + } +} + From 3b653e414c33b0fef1d7ccf6605b57353d5db564 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Mon, 29 Oct 2012 12:49:49 +0200 Subject: [PATCH 029/107] Initial Sammy.js definitions and tests --- Definitions/sammyjs-0.7.d.ts | 228 ++++++++++++++++ README.md | 5 +- Tests/sammyjs-tests.ts | 500 +++++++++++++++++++++++++++++++++++ 3 files changed, 732 insertions(+), 1 deletion(-) create mode 100644 Definitions/sammyjs-0.7.d.ts create mode 100644 Tests/sammyjs-tests.ts diff --git a/Definitions/sammyjs-0.7.d.ts b/Definitions/sammyjs-0.7.d.ts new file mode 100644 index 000000000..b26d23ca2 --- /dev/null +++ b/Definitions/sammyjs-0.7.d.ts @@ -0,0 +1,228 @@ +// Type definitions for Sammy.js +// Project: http://sammyjs.org/ +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +interface Sammy { + (): Application; + (selector: string): Application; + (handler: Function): Application; + (selector: string, handler: Function): Application; + + Cache(app, options); + DataCacheProxy(initial, $element); + DataLocationProxy(app, data_name, href_attribute); + DefaultLocationProxy(app, run_interval_every); + EJS(app, method_alias); + + Exceptional(app, errorReporter); + Flash(app); + Form(app); // formFor ( name, object, content_callback ) + + Haml(app, method_alias); + Handlebars(app, method_alias); + Hogan(app, method_alias); + Hoptoad(app, errorReporter); + JSON(app); + Meld(app, method_alias); + MemoryCacheProxy(initial); + Mustache(app, method_alias); + NestedParams(app); + OAuth2(app); + PathLocationProxy(app); + Pure(app, method_alias); + PushLocationProxy(app); + Session(app, options); + Storage(app); + + Title(); + Tmpl(app, method_alias); + addLogger(logger); + log(); + + Object: Object; +} + +interface Object { + + constructor (obj: any); + + escapeHTML(s: string): string; + h(s: string): string; + + has(key: string): bool; + join(...args: any[]): string; + keys(attributes_only?: bool): string[]; + log(...args: any[]): void; + toHTML(): string; + toHash(): any; + toString(include_functions?: bool): string; +} + +interface Application extends Object { + + ROUTE_VERBS: string[]; + APP_EVENTS: string[]; + + (appFn: Function); + + $element(selector: string): JQuery; + after: (callback: Function): Application; + any(verb: string, path: string, callback: Function): void; + route(verb: string, path: string, callback: Function): void; + around(callback); + before(options: any, callback: Function): Application; + bind(name: string, data: any, callback: Function): Application; + bindToAllEvents(callback); + clearTemplateCache(); + contextMatchesOptions(context, match_options, positive); + del(path: string, callback: Function): Application; + del(path: RegExp, callback: Function): Application; + destroy(); + error(message, original_error); + eventNamespace(): string; + get(path: string, callback: Function): Application; + get(path: RegExp, callback: Function): Application; + getLocation(): string; + helper(name, method); + helpers(extensions); + isRunning(); + log(...params: any[]): void; + lookupRoute(verb, path); + mapRoutes(route_array: any[]): Application; + notFound(verb, path); + post(path: string, callback: Function): Application; + post(path: RegExp, callback: Function): Application; + put(path: string, callback: Function): Application; + put(path: RegExp, callback: Function): Application; + refresh(): Application; + routablePath(path); + route(verb: string, path: string, callback: Function): Application; + route(verb: string, path: RegExp, callback: Function): Application; + run(start_url); + runRoute(verb, path, params, target); + setLocation(new_location: string): string; + setLocationProxy(new_proxy: DataLocationProxy): void; + swap(content, callback); + templateCache(key, value); + toString(): string; + trigger(name: string, data: any): Application; + unload(); + use(...params: any[]): void; +} + +interface DataLocationProxy { + (app, run_interval_every): DataLocationProxy; + fullPath(location_obj): string; + bind(): void; + unbind(): void; + setLocation(new_location: string): string; + _startPolling(every: number): void; +} + +interface EventContext { + constructor (app, verb, path, params, target); + $element(); + engineFor(engine); + eventNamespace(); + interpolate(content, data, engine, partials); + json(string); + load(location, options, callback); + loadPartials(partials); + notFound(); + partial(location, data, callback, partials); + redirect(); + render(location, data, callback, partials); + renderEach(location, name, data, callback); + send(); + swap(contents, callback); + toString(); + trigger(name, data); +} + +interface FormBuilder { + constructor (name, object); + checkbox(keypath, value, attributes); + close(); + hidden(keypath, attributes); + label(keypath, content, attributes); + open(attributes); + password(keypath, attributes); + radio(keypath, value, attributes); + select(keypath, options, attributes); + submit(attributes); + text(keypath, attributes); + textarea(keypath, attributes); +} + +interface GoogleAnalytics { + constructor (app, tracker); + noTrack(); + track(path); +} + +interface RenderContext { + constructor (event_context); + appendTo(selector); + collect(array, callback, now); + interpolate(data, engine, retain); + load(location, options, callback); + loadPartials(partials); + next(content); + partial(location, data, callback, partials); + prependTo(selector); + render(location, data, callback, partials); + renderEach(location, name, data, callback); + replace(selector); + send(); + swap(callback); + then(callback); + trigger(name, data); + wait(); +} + + +interface StoreOptions { + name?: string; + element?: string; + type?: string; + memory?: any; + data?: any; + cookie?: any; + local?: any; + session?: any; +} + +interface Store { + constructor (options); + + clear(key); + clearAll(); + each(callback); + exists(key); + fetch(key, callback); + filter(callback); + first(callback); + get(key); + isAvailable(); + keys(); + load(key, path, callback); + set(key, value); + + Cookie(name, element, options); + Data(name, element); + LocalStorage(name, element); + Memory(name, element); + SessionStorage(name, element); + isAvailable(type); + Template(app, method_alias); +} + + +interface JQueryStatic { + sammy: Sammy; +} + +declare var Sammy: Sammy; \ No newline at end of file diff --git a/README.md b/README.md index a92d08c42..4f68d27a2 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ Complete * [node_redis](https://github.com/mranney/node_redis) * [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) * [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall)) +* [Sammy.js](http://sammyjs.org/) * [Spin](http://fgnass.github.com/spin.js/) * [Underscore.js](http://underscorejs.org/) @@ -47,4 +48,6 @@ Next * Meteor * PhoneGap * Isotope -* Zepto \ No newline at end of file +* Zepto +* Socket.IO +* MongoDB \ No newline at end of file diff --git a/Tests/sammyjs-tests.ts b/Tests/sammyjs-tests.ts new file mode 100644 index 000000000..fa0fa3a67 --- /dev/null +++ b/Tests/sammyjs-tests.ts @@ -0,0 +1,500 @@ +/// + +var _this: RenderContext; + +function test_general() { + var app = Sammy('#main', function () { + var _this: Application; + _this.use('Mustache'); + _this.get('#/', function () { + _this.load('posts.json') + .renderEach('post.mustache') + .swap(); + }); + }); + + app.run('#/'); + + _this.get('#/', function(context) { + _this.load('data/items.json') + .then(function(items) { + $.each(items, function(i, item) { + context.log(item.title, '-', item.artist); + }); + }); + }); +} + +function test_app() { + var s = new Sammy.Object({ first_name: 'Sammy', last_name: 'Davis Jr.' }); + s.toHTML(); + + var app = $.sammy(function () { + var current_user = false; + function checkLoggedIn(callback) { + if (!current_user) { + $.getJSON('/session', function (json) { + if (json.login) { + current_user = json; + callback(); + } else { + current_user = false; + _this.redirect('#/login'); + } + }); + } else { + callback(); + } + }; + _this.around(checkLoggedIn); + }); + + var app = $.sammy(function () { + _this.before('#/route', function () { }); + _this.before({ except: { path: '#/route' } }, function () { + _this.log('not before #/route'); + }); + _this.get('#/', function () { }); + _this.get('#/route', function () { }); + }); + + var app = $.sammy(), + context = { verb: 'get', path: '#/mypath' }; + + app.contextMatchesOptions(context, '#/mypath'); + app.contextMatchesOptions(context, '#/otherpath'); + app.contextMatchesOptions(context, { only: { path: '#/mypath' } }); + app.contextMatchesOptions(context, { only: { path: '#/otherpath' } }); + app.contextMatchesOptions(context, /path/); + app.contextMatchesOptions(context, /^path/); + app.contextMatchesOptions(context, { only: { verb: 'get' } }); + app.contextMatchesOptions(context, { only: { verb: 'post' } }); + app.contextMatchesOptions(context, { except: { verb: 'post' } }); + app.contextMatchesOptions(context, { except: { verb: 'get' } }); + app.contextMatchesOptions(context, { except: { path: '#/otherpath' } }); + app.contextMatchesOptions(context, { except: { path: '#/mypath' } }); + app.contextMatchesOptions(context, { path: ['#/mypath', '#/otherpath'] }); + app.contextMatchesOptions(context, { path: ['#/otherpath', '#/thirdpath'] }); + app.contextMatchesOptions(context, { only: { path: ['#/mypath', '#/otherpath'] } }); + app.contextMatchesOptions(context, { only: { path: ['#/otherpath', '#/thirdpath'] } }); + app.contextMatchesOptions(context, { except: { path: ['#/mypath', '#/otherpath'] } }); + app.contextMatchesOptions(context, { except: { path: ['#/otherpath', '#/thirdpath'] } }); + + var app = $.sammy(function (app) { + $.each([1, 2, 3], function (i, num) { + app.helper('helper' + num, function () { + _this.log("I'm helper number " + num); + }); + }); + _this.get('#/', function () { + _this.helper2(); + }); + }); + + var app = $.sammy(function () { + helpers({ + upcase: function (text) { + return text.toString().toUpperCase(); + } + }); + get('#/', function () { + with (_this) { + $('#main').html(upcase($('#main').text()); + } + }); + }); + + var app = $.sammy(function () { + _this.mapRoutes([ + ['get', '#/', function () { _this.log('index'); }], + ['post', '#/create', 'addUser'], + [/dowhatever/, function () { _this.log(_this.verb, _this.path) }]; + ]); + }); + + var app = $.sammy(function () { }); + $(function () + app.run(); + }); + + var app = $.sammy(function () { + _this.setLocationProxy(new Sammy.DataLocationProxy(_this)); + }); + + var app = $.sammy(function () { + _this.swap = function (content, callback) { + var context = _this; + context.$element().fadeOut('slow', function () { + context.$element().html(content); + context.$element().fadeIn('slow', function () { + if (callback) { + callback.apply(); + } + }); + }); + }; + }); + + var MyPlugin = function (app, prepend) { + _this.helpers({ + myhelper: function (text) { + alert(prepend + " " + text); + } + }); + }; + var app = $.sammy(function () { + _this.use(MyPlugin, '_this is my plugin'); + _this.get('#/', function () { + _this.myhelper('and dont you forget it!'); + }); + }); + + $.sammy(function () { + _this.use('Mustache'); + _this.use('Storage'); + }); +} + +function test_misc() { + var app = $.sammy(function () { + _this.setLocationProxy(new Sammy.DataLocationProxy(_this, 'location', 'rel')); + _this.get('about', function () { + _this.partial('about.html'); + }); + }); + + $.sammy(function () { + _this.get('#/:name', function () { + if (_this.params['name'] == 'sammy') { + _this.partial('name.html.erb', { name: 'Sammy' }); + } else { + _this.redirect('#/somewhere-else') + } + }); + }); + + redirect('#/other/route'); + redirect('#', 'other', 'route'); + render('mytemplate.mustache', { name: 'quirkey' }) + .appendTo('ul'); + renderEach('mytemplate.mustache', [{ name: 'quirkey' }, { name: 'endor' }]); + + var item = { + name: 'My Item', + price: '$25.50', + meta: { + id: '123' + } + }; + var form = new Sammy.FormBuilder('item', item); + form.text('name'); + + var options = [ + ['Small', 's'], + ['Medium', 'm'], + ['Large', 'l'] + ]; + form.select('size', options); + + $.sammy(function () { + _this.use('GoogleAnalytics') + _this.get('#/dont/track/me', function () { + _this.noTrack(); + }); + }); + + var app = $.sammy(function () { + _this.use(Sammy.Haml); + _this.get('#/hello/:name', function () { + _this.title = 'Hello!' + _this.name = _this.params.name; + _this.partial('mytemplate.haml'); + }); + }); + app.run() + + var app = $.sammy(function () { + _this.use('Handlebars', 'hb'); + _this.get('#/hello/:name', function () { + _this.title = 'Hello!' + _this.name = _this.params.name; + _this.partial('mytemplate.hb'); + }); + }); + + var app = $.sammy(function () { + _this.use('Handlebars', 'hb'); + _this.get('#/hello/:name/to/:friend', function (context) { + _this.load('mypartial.hb') + .then(function (partial) { + context.partials = { hello_friend: partial }; + context.name = context.params.name; + context.friend = context.params.friend; + context.partial('mytemplate.hb'); + }); + }); + }); + + var app = $.sammy(function () { + _this.use('Hogan', 'hg'); + _this.get('#/hello/:name', function () { + _this.title = 'Hello!' + _this.name = _this.params.name; + _this.partial('mytemplate.hg'); + }); + }); + + var app = $.sammy(function () { + _this.use('Hogan', 'hg'); + _this.get('#/hello/:name/to/:friend', function (context) { + _this.load('mypartial.hg') + .then(function (partial) { + context.partials = { hello_friend: partial }; + context.name = context.params.name; + context.friend = context.params.friend; + context.partial('mytemplate.hg'); + }); + }); + }); + + var app = $.sammy(function () { + _this.use(Sammy.JSON); + _this.get('#/', function () { + _this.json({ user_id: 123 }); + _this.json("{\"user_id\":\"123\"}"); + _this.json("{\"user_id\":\"123\"}").user_id; + }); + }) + + var app = $.sammy(function () { + _this.use('Mustache', 'ms'); + _this.get('#/hello/:name', function () { + _this.title = 'Hello!' + _this.name = _this.params.name; + _this.partial('mytemplate.ms'); + }); + }); + + var app = $.sammy(function () { + _this.use('Mustache', 'ms'); + _this.get('#/hello/:name/to/:friend', function (context) { + _this.load('mypartial.ms') + .then(function (partial) { + context.partials = { hello_friend: partial }; + context.name = context.params.name; + context.friend = context.params.friend; + context.partial('mytemplate.ms'); + }); + }); + }); + + var app = $.sammy(function (app) { + _this.use(Sammy.NestedParams); + _this.post('#/parse_me', function (context) { + $.log(_this.params); + }); + }); + + _this.use('Storage'); + _this.use('OAuth2'); + _this.oauthorize = "/oauth/authorize"; + _this.requireOAuth(); + _this.requireOAuth("/private"); + _this.before(function (context) { return context.requireOAuth(); }) + _this.get("/private", function (context) { + _this.requireOAuth(function () { }); + }); + _this.bind("oauth.connected", function () { $("#signin").hide() }); + _this.bind("oauth.disconnected", function () { $("#signin").show() }); + _this.bind("oauth.denied", function (evt, error) { + _this.partial("admin/views/no_access.tmpl", { error: error.message }); + }); + _this.get("#/signout", function (context) { + context.loseAccessToken(); + context.redirect("#/"); + }); + + _this.get('#/', function () { + _this.render('mytemplate.template', { name: 'test' }); + }); + + _this.send($.getJSON, '/app.json') + .then(function (json) { + $('#message').text(json['message']); + } + ); + + _this.get('#/', function () { + _this.load('myfile.txt') + .then(function (content) { + $('#main').html(content); + }); + }); + + _this.get('#/', function () { + _this.load('mytext.json') + .then(function (content) { + var context = _this, + data = JSON.parse(content); + context.wait(); + $.post(data.url, {}, function (response) { + context.next(JSON.parse(response)); + }); + }) + .then(function (data) { + $('#message').text(data.status); + }); + }); + + var store = new Sammy.Store({ name: 'mystore', element: '#element', type: 'local' }); + store.set('foo', 'bar'); + store.get('foo'); + store.set('json', { obj: '_this is an obj' }); + store.get('json'); + store.keys(); + store.clear('foo'); + store.keys(); + store.clearAll(); + store.keys(); + + store.each(function (key, value) { + Sammy.log('key', key, 'value', value); + }); + var store = new Sammy.Store; + store.exists('foo'); + store.fetch('foo', function () { + return 'bar!'; + }); + store.get('foo'); + store.fetch('foo', function () { + return 'baz!'; + }); + + var store = new Sammy.Store; + store.set('one', 'two'); + store.set('two', 'three'); + store.set('1', 'two'); + var returned = store.filter(function (key, value) { + return value === 'two'; + }); + + var store = new Sammy.Store; + store.load('mytemplate', '/mytemplate.tpl', function () { + s.get('mytemplate') + }); + + var store = new Sammy.Store({ name: 'kvo' }); + $('body').bind('set-kvo-foo', function (e, data) { + Sammy.log(data.key + ' changed to ' + data.value); + }); + store.set('foo', 'bar'); + + $.sammy(function () { + _this.use('Template'); + _this.get('#/', function () { + _this.user = { name: 'Aaron Quint' }; + _this.partial('user.template'); + }) + }); + + _this.use(Sammy.Template, 'tpl'); + _this.get('#/', function () { + _this.partial('myfile.tpl'); + }); + _this.get('#/', function () { + _this.template('myform.tpl', { form: "
    " }, { escape_html: false }); + }); +} + +function test_routes() { + route('get', '#/', function () { + }); + put('#/post/form', function () { + return false; + }); + get('/test/123', function () { + }); + + get('#/by_name/:name', function () { + alert(_this.params['name']); + }); + get(/\#\/by_name\/(.*)/, function () { + alert(_this.params['splat']); + }); + get('#/by_name/:name', function () { + _this.redirect('#', _this.params['name']); + }); + + get('#/by_name/:name', function (context) { + context.redirect('#', _this.params['name']); + }); +} + +function test_events() { + bind('db-loaded', function (e, data) { + _this.redirect('#/'); + }); + + var app = $.sammy(function () { + bind('test', function () { + _this.trigger('other-event'); + }); + }); + app.trigger('other-event'); + + var app = $.sammy(function () { + bind('test', function (e, data) { + alert(data['my_data']); + }); + get('#/', function () { + _this.trigger('test', { my_data: 'EVENTED!' }); + }); + }); +} + +function test_plugins() { + var MyPlugin = function (app) { + _this.helpers({ + alert: function (message) { + _this.log("ALERT! " + message); + } + }); + }; + var app = $.sammy(function () { + _this.use(MyPlugin); + _this.get('#/', function () { + _this.alert("I'm home"); + }); + }); + var MyAdvancedPlugin = function (app, prefix, suffix) { + _this.helpers({ + alert: function (message) { + _this.log(prefix, message, suffix); + } + }); + }; + + var app = $.sammy(function () { + _this.use(MyAdvancedPlugin, 'BEFORE!', 'AFTER!'); + _this.get('#/', function () { + _this.alert("I'm home"); + }); + }); + + var dbLoadAndDisplay = function (app) { + _this.get('#/', function () { + _this.record = _this.app.db[_this.app.element_selector]; + _this.app.swap(_this.record.toHTML()); + }); + _this.bind('run', function () { + }); + }; + + var app1 = Sammy('#div_1', function () { + _this.use(dbLoadAndDisplay); + }); + + var app2 = Sammy('#div_2', function () { + _this.use(dbLoadAndDisplay); + }); +} \ No newline at end of file From 6db4460328357dc6a62e671d686f663a19aaabb5 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Mon, 29 Oct 2012 15:38:37 +0200 Subject: [PATCH 030/107] Improve Sammy.js definitions and tests --- Definitions/sammyjs-0.7.d.ts | 427 ++++++++++++++++++----------------- Tests/sammyjs-tests.ts | 96 +++++--- 2 files changed, 282 insertions(+), 241 deletions(-) diff --git a/Definitions/sammyjs-0.7.d.ts b/Definitions/sammyjs-0.7.d.ts index b26d23ca2..42723157a 100644 --- a/Definitions/sammyjs-0.7.d.ts +++ b/Definitions/sammyjs-0.7.d.ts @@ -5,224 +5,225 @@ /// -interface Sammy { - (): Application; - (selector: string): Application; - (handler: Function): Application; - (selector: string, handler: Function): Application; +module Sammy { + export function (): Sammy.Application; + export function (selector: string): Sammy.Application; + export function (handler: Function): Sammy.Application; + export function (selector: string, handler: Function): Sammy.Application; - Cache(app, options); - DataCacheProxy(initial, $element); - DataLocationProxy(app, data_name, href_attribute); - DefaultLocationProxy(app, run_interval_every); - EJS(app, method_alias); + export function Cache(app, options); + export function DataCacheProxy(initial, $element); + export function DataLocationProxy(app, data_name, href_attribute); + export function DefaultLocationProxy(app, run_interval_every); + export function EJS(app, method_alias); - Exceptional(app, errorReporter); - Flash(app); - Form(app); // formFor ( name, object, content_callback ) + export function Exceptional(app, errorReporter); + export function Flash(app); + export function Form(app); // formFor ( name, object, content_callback ) - Haml(app, method_alias); - Handlebars(app, method_alias); - Hogan(app, method_alias); - Hoptoad(app, errorReporter); - JSON(app); - Meld(app, method_alias); - MemoryCacheProxy(initial); - Mustache(app, method_alias); - NestedParams(app); - OAuth2(app); - PathLocationProxy(app); - Pure(app, method_alias); - PushLocationProxy(app); - Session(app, options); - Storage(app); + export function Haml(app, method_alias); + export function Handlebars(app, method_alias); + export function Hogan(app, method_alias); + export function Hoptoad(app, errorReporter); + export function JSON(app); + export function Meld(app, method_alias); + export function MemoryCacheProxy(initial); + export function Mustache(app, method_alias); + export function NestedParams(app); + export function OAuth2(app); + export function PathLocationProxy(app); + export function Pure(app, method_alias); + export function PushLocationProxy(app); + export function Session(app, options); + export function Storage(app); - Title(); - Tmpl(app, method_alias); - addLogger(logger); - log(); + export function Title(); + export function Tmpl(app, method_alias); + export function addLogger(logger); + export function log(); + + export interface Object { + + constructor (obj: any); + + escapeHTML(s: string): string; + h(s: string): string; + + has(key: string): bool; + join(...args: any[]): string; + keys(attributes_only?: bool): string[]; + log(...args: any[]): void; + toHTML(): string; + toHash(): any; + toString(include_functions?: bool): string; + } + + export interface Application extends Object { + + ROUTE_VERBS: string[]; + APP_EVENTS: string[]; + + (appFn: Function); + + $element(selector?: string): JQuery; + after(callback: Function): Application; + any(verb: string, path: string, callback: Function): void; + route(verb: string, path: string, callback: Function): void; + around(callback: Function): Application; + before(options: any, callback: Function): Application; + bind(name: string, callback: Function): Application; + bind(name: string, data: any, callback: Function): Application; + bindToAllEvents(callback: Function): Application; + clearTemplateCache(): any; + contextMatchesOptions(context: any, match_options: any, positive?: bool): bool; + del(path: string, callback: Function): Application; + del(path: RegExp, callback: Function): Application; + destroy(): Application; + error(message: string, original_error: Error): void; + eventNamespace(): string; + get(path: string, callback: Function): Application; + get(path: RegExp, callback: Function): Application; + getLocation(): string; + helper(name: string, method: Function): Application; + helpers(extensions: any): Application; + isRunning(): bool; + log(...params: any[]): void; + lookupRoute(verb: string, path: string): any; + mapRoutes(route_array: any[]): Application; + notFound(verb: string, path: string): any; + post(path: string, callback: Function): Application; + post(path: RegExp, callback: Function): Application; + put(path: string, callback: Function): Application; + put(path: RegExp, callback: Function): Application; + refresh(): Application; + routablePath(path: string): string; + route(verb: string, path: string, callback: Function): Application; + route(verb: string, path: RegExp, callback: Function): Application; + run(start_url?: string): Application; + runRoute(verb: string, path: string, params: any, target: any): any; + setLocation(new_location: string): string; + setLocationProxy(new_proxy: DataLocationProxy): void; + swap(content: any, callback: Function): string; + templateCache(key: string, value: any): any; + toString(): string; + trigger(name: string, data?: any): Application; + unload(): Application; + use(...params: any[]): void; + } + + export interface DataLocationProxy { + constructor (app, run_interval_every): DataLocationProxy; + fullPath(location_obj): string; + bind(): void; + unbind(): void; + setLocation(new_location: string): string; + _startPolling(every: number): void; + } + + export interface EventContext extends Object { + constructor (app, verb, path, params, target); + $element(): JQuery; + engineFor(engine: any): any; + eventNamespace(): string; + interpolate(content: any, data: any, engine: any, partials): EventContext; + json(str: string): any; + load(location: any, options?: any, callback?: Function): any; + loadPartials(partials); + notFound(): any; + partial(location, data, callback, partials); + redirect(...params: any[]): void; + render(location: string, data: any, callback: Function, partials): RenderContext; + renderEach(location: any, name?: string, data?: any, callback?: Function): RenderContext; + send(...params: any[]): RenderContext; + swap(contents: any, callback: Function): string; + toString(): string; + trigger(name: string, data?: any): EventContext; + } + + export interface FormBuilder { + constructor (name, object); + checkbox(keypath, value, attributes); + close(); + hidden(keypath, attributes); + label(keypath, content, attributes); + open(attributes); + password(keypath, attributes); + radio(keypath, value, attributes); + select(keypath, options, attributes); + submit(attributes); + text(keypath, attributes); + textarea(keypath, attributes); + } + + export interface GoogleAnalytics { + constructor (app, tracker); + noTrack(); + track(path); + } + + export interface RenderContext extends Object { + constructor (event_context); + appendTo(selector: string): RenderContext; + collect(array: any[], callback: Function, now?: bool): RenderContext; + interpolate(data: any, engine?: any, retain?: bool): RenderContext; + load(location: string, options?: any, callback?: Function): RenderContext; + loadPartials(partials?: any): RenderContext; + next(content: any): void; + partial(location: string, callback: Function, partials): RenderContext; + partial(location: string, data: any, callback: Function, partials): RenderContext; + prependTo(selector: string): RenderContext; + render(callback: Function): RenderContext; + render(location: string, data: any): RenderContext; + render(location: string, callback: Function, partials?: any): RenderContext; + render(location: string, data: any, callback: Function): RenderContext; + render(location: string, data: any, callback: Function, partials: any): RenderContext; + renderEach(location: string, name: string, data: any, callback: Function): RenderContext; + replace(selector: string): RenderContext; + send(...params: any[]): RenderContext; + swap(callback: Function): RenderContext; + then(callback: Function): RenderContext; + trigger(name, data); + wait(): void; + } + + + export interface StoreOptions { + name?: string; + element?: string; + type?: string; + memory?: any; + data?: any; + cookie?: any; + local?: any; + session?: any; + } + + export interface Store { + constructor (options); + + clear(key); + clearAll(); + each(callback); + exists(key); + fetch(key, callback); + filter(callback); + first(callback); + get(key); + isAvailable(); + keys(); + load(key, path, callback); + set(key, value); + + Cookie(name, element, options); + Data(name, element); + LocalStorage(name, element); + Memory(name, element); + SessionStorage(name, element); + isAvailable(type); + Template(app, method_alias); + } - Object: Object; } - -interface Object { - - constructor (obj: any); - - escapeHTML(s: string): string; - h(s: string): string; - - has(key: string): bool; - join(...args: any[]): string; - keys(attributes_only?: bool): string[]; - log(...args: any[]): void; - toHTML(): string; - toHash(): any; - toString(include_functions?: bool): string; -} - -interface Application extends Object { - - ROUTE_VERBS: string[]; - APP_EVENTS: string[]; - - (appFn: Function); - - $element(selector: string): JQuery; - after: (callback: Function): Application; - any(verb: string, path: string, callback: Function): void; - route(verb: string, path: string, callback: Function): void; - around(callback); - before(options: any, callback: Function): Application; - bind(name: string, data: any, callback: Function): Application; - bindToAllEvents(callback); - clearTemplateCache(); - contextMatchesOptions(context, match_options, positive); - del(path: string, callback: Function): Application; - del(path: RegExp, callback: Function): Application; - destroy(); - error(message, original_error); - eventNamespace(): string; - get(path: string, callback: Function): Application; - get(path: RegExp, callback: Function): Application; - getLocation(): string; - helper(name, method); - helpers(extensions); - isRunning(); - log(...params: any[]): void; - lookupRoute(verb, path); - mapRoutes(route_array: any[]): Application; - notFound(verb, path); - post(path: string, callback: Function): Application; - post(path: RegExp, callback: Function): Application; - put(path: string, callback: Function): Application; - put(path: RegExp, callback: Function): Application; - refresh(): Application; - routablePath(path); - route(verb: string, path: string, callback: Function): Application; - route(verb: string, path: RegExp, callback: Function): Application; - run(start_url); - runRoute(verb, path, params, target); - setLocation(new_location: string): string; - setLocationProxy(new_proxy: DataLocationProxy): void; - swap(content, callback); - templateCache(key, value); - toString(): string; - trigger(name: string, data: any): Application; - unload(); - use(...params: any[]): void; -} - -interface DataLocationProxy { - (app, run_interval_every): DataLocationProxy; - fullPath(location_obj): string; - bind(): void; - unbind(): void; - setLocation(new_location: string): string; - _startPolling(every: number): void; -} - -interface EventContext { - constructor (app, verb, path, params, target); - $element(); - engineFor(engine); - eventNamespace(); - interpolate(content, data, engine, partials); - json(string); - load(location, options, callback); - loadPartials(partials); - notFound(); - partial(location, data, callback, partials); - redirect(); - render(location, data, callback, partials); - renderEach(location, name, data, callback); - send(); - swap(contents, callback); - toString(); - trigger(name, data); -} - -interface FormBuilder { - constructor (name, object); - checkbox(keypath, value, attributes); - close(); - hidden(keypath, attributes); - label(keypath, content, attributes); - open(attributes); - password(keypath, attributes); - radio(keypath, value, attributes); - select(keypath, options, attributes); - submit(attributes); - text(keypath, attributes); - textarea(keypath, attributes); -} - -interface GoogleAnalytics { - constructor (app, tracker); - noTrack(); - track(path); -} - -interface RenderContext { - constructor (event_context); - appendTo(selector); - collect(array, callback, now); - interpolate(data, engine, retain); - load(location, options, callback); - loadPartials(partials); - next(content); - partial(location, data, callback, partials); - prependTo(selector); - render(location, data, callback, partials); - renderEach(location, name, data, callback); - replace(selector); - send(); - swap(callback); - then(callback); - trigger(name, data); - wait(); -} - - -interface StoreOptions { - name?: string; - element?: string; - type?: string; - memory?: any; - data?: any; - cookie?: any; - local?: any; - session?: any; -} - -interface Store { - constructor (options); - - clear(key); - clearAll(); - each(callback); - exists(key); - fetch(key, callback); - filter(callback); - first(callback); - get(key); - isAvailable(); - keys(); - load(key, path, callback); - set(key, value); - - Cookie(name, element, options); - Data(name, element); - LocalStorage(name, element); - Memory(name, element); - SessionStorage(name, element); - isAvailable(type); - Template(app, method_alias); -} - - interface JQueryStatic { sammy: Sammy; -} - -declare var Sammy: Sammy; \ No newline at end of file +} \ No newline at end of file diff --git a/Tests/sammyjs-tests.ts b/Tests/sammyjs-tests.ts index fa0fa3a67..e6249c78a 100644 --- a/Tests/sammyjs-tests.ts +++ b/Tests/sammyjs-tests.ts @@ -1,12 +1,11 @@ /// -var _this: RenderContext; - function test_general() { var app = Sammy('#main', function () { - var _this: Application; + var _this: Sammy.Application; _this.use('Mustache'); _this.get('#/', function () { + var _this: Sammy.RenderContext; _this.load('posts.json') .renderEach('post.mustache') .swap(); @@ -15,14 +14,16 @@ function test_general() { app.run('#/'); - _this.get('#/', function(context) { + var _this: Sammy.Application; + _this.get('#/', function (context) { + var _this: Sammy.RenderContext; _this.load('data/items.json') - .then(function(items) { - $.each(items, function(i, item) { - context.log(item.title, '-', item.artist); + .then(function (items) { + $.each(items, function (i, item) { + context.log(item.title, '-', item.artist); }); }); - }); + }); } function test_app() { @@ -30,8 +31,10 @@ function test_app() { s.toHTML(); var app = $.sammy(function () { + var current_user = false; function checkLoggedIn(callback) { + var _this: Sammy.EventContext; if (!current_user) { $.getJSON('/session', function (json) { if (json.login) { @@ -46,10 +49,12 @@ function test_app() { callback(); } }; + var _this: Sammy.Application; _this.around(checkLoggedIn); }); var app = $.sammy(function () { + var _this: Sammy.Application; _this.before('#/route', function () { }); _this.before({ except: { path: '#/route' } }, function () { _this.log('not before #/route'); @@ -81,30 +86,32 @@ function test_app() { app.contextMatchesOptions(context, { except: { path: ['#/otherpath', '#/thirdpath'] } }); var app = $.sammy(function (app) { + var _this: Sammy.Application; $.each([1, 2, 3], function (i, num) { app.helper('helper' + num, function () { _this.log("I'm helper number " + num); }); }); _this.get('#/', function () { - _this.helper2(); }); }); var app = $.sammy(function () { - helpers({ + var _this: Sammy.Application; + _this.helpers({ upcase: function (text) { return text.toString().toUpperCase(); } }); - get('#/', function () { + _this.get('#/', function () { with (_this) { - $('#main').html(upcase($('#main').text()); + $('#main').html(upcase($('#main').text())); } }); }); var app = $.sammy(function () { + var _this: Sammy.Application; _this.mapRoutes([ ['get', '#/', function () { _this.log('index'); }], ['post', '#/create', 'addUser'], @@ -113,15 +120,17 @@ function test_app() { }); var app = $.sammy(function () { }); - $(function () + $(function () { app.run(); }); var app = $.sammy(function () { + var _this: Sammy.Application; _this.setLocationProxy(new Sammy.DataLocationProxy(_this)); }); var app = $.sammy(function () { + var _this: Sammy.Application; _this.swap = function (content, callback) { var context = _this; context.$element().fadeOut('slow', function () { @@ -136,6 +145,7 @@ function test_app() { }); var MyPlugin = function (app, prepend) { + var _this: Sammy.Application; _this.helpers({ myhelper: function (text) { alert(prepend + " " + text); @@ -143,6 +153,7 @@ function test_app() { }); }; var app = $.sammy(function () { + var _this: Sammy.Application; _this.use(MyPlugin, '_this is my plugin'); _this.get('#/', function () { _this.myhelper('and dont you forget it!'); @@ -150,6 +161,7 @@ function test_app() { }); $.sammy(function () { + var _this: Sammy.Application; _this.use('Mustache'); _this.use('Storage'); }); @@ -157,6 +169,7 @@ function test_app() { function test_misc() { var app = $.sammy(function () { + var _this: Sammy.Application; _this.setLocationProxy(new Sammy.DataLocationProxy(_this, 'location', 'rel')); _this.get('about', function () { _this.partial('about.html'); @@ -164,6 +177,7 @@ function test_misc() { }); $.sammy(function () { + var _this: Sammy.Application; _this.get('#/:name', function () { if (_this.params['name'] == 'sammy') { _this.partial('name.html.erb', { name: 'Sammy' }); @@ -173,11 +187,12 @@ function test_misc() { }); }); - redirect('#/other/route'); - redirect('#', 'other', 'route'); - render('mytemplate.mustache', { name: 'quirkey' }) + var _this: Sammy.Application; + _this.redirect('#/other/route'); + _this.redirect('#', 'other', 'route'); + _this.render('mytemplate.mustache', { name: 'quirkey' }) .appendTo('ul'); - renderEach('mytemplate.mustache', [{ name: 'quirkey' }, { name: 'endor' }]); + _this.renderEach('mytemplate.mustache', [{ name: 'quirkey' }, { name: 'endor' }]); var item = { name: 'My Item', @@ -197,6 +212,7 @@ function test_misc() { form.select('size', options); $.sammy(function () { + var _this: Sammy.Application; _this.use('GoogleAnalytics') _this.get('#/dont/track/me', function () { _this.noTrack(); @@ -204,6 +220,7 @@ function test_misc() { }); var app = $.sammy(function () { + var _this: Sammy.Application; _this.use(Sammy.Haml); _this.get('#/hello/:name', function () { _this.title = 'Hello!' @@ -214,6 +231,7 @@ function test_misc() { app.run() var app = $.sammy(function () { + var _this: Sammy.Application; _this.use('Handlebars', 'hb'); _this.get('#/hello/:name', function () { _this.title = 'Hello!' @@ -223,6 +241,7 @@ function test_misc() { }); var app = $.sammy(function () { + var _this: Sammy.Application; _this.use('Handlebars', 'hb'); _this.get('#/hello/:name/to/:friend', function (context) { _this.load('mypartial.hb') @@ -236,6 +255,7 @@ function test_misc() { }); var app = $.sammy(function () { + var _this: Sammy.Application; _this.use('Hogan', 'hg'); _this.get('#/hello/:name', function () { _this.title = 'Hello!' @@ -245,6 +265,7 @@ function test_misc() { }); var app = $.sammy(function () { + var _this: Sammy.Application; _this.use('Hogan', 'hg'); _this.get('#/hello/:name/to/:friend', function (context) { _this.load('mypartial.hg') @@ -258,6 +279,7 @@ function test_misc() { }); var app = $.sammy(function () { + var _this: Sammy.Application; _this.use(Sammy.JSON); _this.get('#/', function () { _this.json({ user_id: 123 }); @@ -267,6 +289,7 @@ function test_misc() { }) var app = $.sammy(function () { + var _this: Sammy.Application; _this.use('Mustache', 'ms'); _this.get('#/hello/:name', function () { _this.title = 'Hello!' @@ -276,6 +299,7 @@ function test_misc() { }); var app = $.sammy(function () { + var _this: Sammy.Application; _this.use('Mustache', 'ms'); _this.get('#/hello/:name/to/:friend', function (context) { _this.load('mypartial.ms') @@ -289,12 +313,14 @@ function test_misc() { }); var app = $.sammy(function (app) { + var _this: Sammy.Application; _this.use(Sammy.NestedParams); _this.post('#/parse_me', function (context) { $.log(_this.params); }); }); + var _this: Sammy.Application; _this.use('Storage'); _this.use('OAuth2'); _this.oauthorize = "/oauth/authorize"; @@ -407,46 +433,54 @@ function test_misc() { } function test_routes() { - route('get', '#/', function () { + var _this: Sammy.Application; + + _this.route('get', '#/', function () { }); - put('#/post/form', function () { + _this.put('#/post/form', function () { return false; }); - get('/test/123', function () { + _thisget('/test/123', function () { }); - get('#/by_name/:name', function () { + _thisget('#/by_name/:name', function () { alert(_this.params['name']); }); - get(/\#\/by_name\/(.*)/, function () { + _thisget(/\#\/by_name\/(.*)/, function () { alert(_this.params['splat']); }); - get('#/by_name/:name', function () { + _thisget('#/by_name/:name', function () { _this.redirect('#', _this.params['name']); }); - get('#/by_name/:name', function (context) { + _thisget('#/by_name/:name', function (context) { context.redirect('#', _this.params['name']); }); } function test_events() { - bind('db-loaded', function (e, data) { + var _this: Sammy.Application; + + _this.bind('db-loaded', function (e, data) { + var _this: Sammy.EventContext; _this.redirect('#/'); }); var app = $.sammy(function () { - bind('test', function () { + var _this: Sammy.Application; + _this.bind('test', function () { + var _this: Sammy.EventContext; _this.trigger('other-event'); }); }); app.trigger('other-event'); var app = $.sammy(function () { - bind('test', function (e, data) { + var _this: Sammy.Application; + _this.bind('test', function (e, data) { alert(data['my_data']); }); - get('#/', function () { + _this.get('#/', function () { _this.trigger('test', { my_data: 'EVENTED!' }); }); }); @@ -454,6 +488,7 @@ function test_events() { function test_plugins() { var MyPlugin = function (app) { + var _this: Sammy.Application; _this.helpers({ alert: function (message) { _this.log("ALERT! " + message); @@ -461,12 +496,15 @@ function test_plugins() { }); }; var app = $.sammy(function () { + var _this: Sammy.Application; _this.use(MyPlugin); _this.get('#/', function () { + var _this: Sammy.EventContext; _this.alert("I'm home"); }); }); var MyAdvancedPlugin = function (app, prefix, suffix) { + var _this: Sammy.Application; _this.helpers({ alert: function (message) { _this.log(prefix, message, suffix); @@ -475,6 +513,7 @@ function test_plugins() { }; var app = $.sammy(function () { + var _this: Sammy.Application; _this.use(MyAdvancedPlugin, 'BEFORE!', 'AFTER!'); _this.get('#/', function () { _this.alert("I'm home"); @@ -482,6 +521,7 @@ function test_plugins() { }); var dbLoadAndDisplay = function (app) { + var _this: Sammy.Application; _this.get('#/', function () { _this.record = _this.app.db[_this.app.element_selector]; _this.app.swap(_this.record.toHTML()); From d7c856dc479c7ae488ee8fc66c6b4db1d6f3b6a7 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Mon, 29 Oct 2012 19:57:14 +0200 Subject: [PATCH 031/107] Improve Sammy.js declarations --- Definitions/sammyjs-0.7.d.ts | 56 ++++++++++++++++++++---------------- Tests/sammyjs-tests.ts | 18 ++++++------ 2 files changed, 40 insertions(+), 34 deletions(-) diff --git a/Definitions/sammyjs-0.7.d.ts b/Definitions/sammyjs-0.7.d.ts index 42723157a..8582eb3cc 100644 --- a/Definitions/sammyjs-0.7.d.ts +++ b/Definitions/sammyjs-0.7.d.ts @@ -130,7 +130,7 @@ module Sammy { load(location: any, options?: any, callback?: Function): any; loadPartials(partials); notFound(): any; - partial(location, data, callback, partials); + partial(location: string, data: any, callback: Function, partials): RenderContext; redirect(...params: any[]): void; render(location: string, data: any, callback: Function, partials): RenderContext; renderEach(location: any, name?: string, data?: any, callback?: Function): RenderContext; @@ -142,17 +142,21 @@ module Sammy { export interface FormBuilder { constructor (name, object); - checkbox(keypath, value, attributes); - close(); - hidden(keypath, attributes); - label(keypath, content, attributes); - open(attributes); - password(keypath, attributes); - radio(keypath, value, attributes); - select(keypath, options, attributes); - submit(attributes); - text(keypath, attributes); - textarea(keypath, attributes); + checkbox(keypath: string, value: any, ...attributes: any[]): string; + close(): string; + hidden(keypath: string, ...attributes: any[]): string; + label(keypath: string, content: any, ...attributes: any[]): string; + open(...attributes: any[]); + password(keypath: string, ...attributes: any[]): string; + radio(keypath: string, value: any, ...attributes: any[]): string; + select(keypath: string, options: any, ...attributes: any[]): string; + submit(...attributes: any[]): string; + text(keypath: string, ...attributes: any[]): string; + textarea(keypath: string, ...attributes: any[]): string; + } + + export interface Form { + formFor(name: string, object: any, content_callback: Function): FormBuilder; } export interface GoogleAnalytics { @@ -199,20 +203,23 @@ module Sammy { } export interface Store { + + stores: any; + constructor (options); - clear(key); - clearAll(); - each(callback); - exists(key); - fetch(key, callback); - filter(callback); - first(callback); - get(key); - isAvailable(); - keys(); - load(key, path, callback); - set(key, value); + clear(key: string): any; + clearAll(): void; + each(callback: Function): bool; + exists(key: string): bool; + fetch(key: string, callback: Function): any; + filter(callback: Function): bool; + first(callback: Function): bool; + get(key: string): any; + isAvailable(): bool; + keys(): string[]; + load(key: string, path: string, callback: Function): void; + set(key: string, value: any): any; Cookie(name, element, options); Data(name, element); @@ -222,7 +229,6 @@ module Sammy { isAvailable(type); Template(app, method_alias); } - } interface JQueryStatic { sammy: Sammy; diff --git a/Tests/sammyjs-tests.ts b/Tests/sammyjs-tests.ts index e6249c78a..588d08f2c 100644 --- a/Tests/sammyjs-tests.ts +++ b/Tests/sammyjs-tests.ts @@ -113,9 +113,9 @@ function test_app() { var app = $.sammy(function () { var _this: Sammy.Application; _this.mapRoutes([ - ['get', '#/', function () { _this.log('index'); }], + ['get', '#/', function () { }], ['post', '#/create', 'addUser'], - [/dowhatever/, function () { _this.log(_this.verb, _this.path) }]; + [/dowhatever/, function () { }] ]); }); @@ -156,7 +156,6 @@ function test_app() { var _this: Sammy.Application; _this.use(MyPlugin, '_this is my plugin'); _this.get('#/', function () { - _this.myhelper('and dont you forget it!'); }); }); @@ -172,6 +171,7 @@ function test_misc() { var _this: Sammy.Application; _this.setLocationProxy(new Sammy.DataLocationProxy(_this, 'location', 'rel')); _this.get('about', function () { + var _this: Sammy.EventContext; _this.partial('about.html'); }); }); @@ -488,7 +488,7 @@ function test_events() { function test_plugins() { var MyPlugin = function (app) { - var _this: Sammy.Application; + var _this: Sammy.Application; _this.helpers({ alert: function (message) { _this.log("ALERT! " + message); @@ -496,15 +496,15 @@ function test_plugins() { }); }; var app = $.sammy(function () { - var _this: Sammy.Application; + var _this: Sammy.Application; _this.use(MyPlugin); _this.get('#/', function () { - var _this: Sammy.EventContext; + var _this: Sammy.EventContext; _this.alert("I'm home"); }); }); var MyAdvancedPlugin = function (app, prefix, suffix) { - var _this: Sammy.Application; + var _this: Sammy.Application; _this.helpers({ alert: function (message) { _this.log(prefix, message, suffix); @@ -513,7 +513,7 @@ function test_plugins() { }; var app = $.sammy(function () { - var _this: Sammy.Application; + var _this: Sammy.Application; _this.use(MyAdvancedPlugin, 'BEFORE!', 'AFTER!'); _this.get('#/', function () { _this.alert("I'm home"); @@ -521,7 +521,7 @@ function test_plugins() { }); var dbLoadAndDisplay = function (app) { - var _this: Sammy.Application; + var _this: Sammy.Application; _this.get('#/', function () { _this.record = _this.app.db[_this.app.element_selector]; _this.app.swap(_this.record.toHTML()); From a0068e57fbd70de5f6eeb8e2a54145d41a90ece5 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Mon, 29 Oct 2012 20:06:40 +0200 Subject: [PATCH 032/107] Rename files to two significant digits for version --- .../{angular-1.0.2.d.ts => angular-1.0.d.ts} | 0 ...es-1.0.2.d.ts => angular-cookies-1.0.d.ts} | 0 ...ocks-1.0.2.d.ts => angular-mocks-1.0.d.ts} | 0 ...e-1.0.2.d.ts => angular-resource-1.0.d.ts} | 0 ...e-1.0.2.d.ts => angular-sanitize-1.0.d.ts} | 0 .../{linq-2.2.0.2.d.ts => linq-2.2.d.ts} | 438 +++++++++--------- 6 files changed, 219 insertions(+), 219 deletions(-) rename Definitions/{angular-1.0.2.d.ts => angular-1.0.d.ts} (100%) rename Definitions/{angular-cookies-1.0.2.d.ts => angular-cookies-1.0.d.ts} (100%) rename Definitions/{angular-mocks-1.0.2.d.ts => angular-mocks-1.0.d.ts} (100%) rename Definitions/{angular-resource-1.0.2.d.ts => angular-resource-1.0.d.ts} (100%) rename Definitions/{angular-sanitize-1.0.2.d.ts => angular-sanitize-1.0.d.ts} (100%) rename Definitions/{linq-2.2.0.2.d.ts => linq-2.2.d.ts} (98%) diff --git a/Definitions/angular-1.0.2.d.ts b/Definitions/angular-1.0.d.ts similarity index 100% rename from Definitions/angular-1.0.2.d.ts rename to Definitions/angular-1.0.d.ts diff --git a/Definitions/angular-cookies-1.0.2.d.ts b/Definitions/angular-cookies-1.0.d.ts similarity index 100% rename from Definitions/angular-cookies-1.0.2.d.ts rename to Definitions/angular-cookies-1.0.d.ts diff --git a/Definitions/angular-mocks-1.0.2.d.ts b/Definitions/angular-mocks-1.0.d.ts similarity index 100% rename from Definitions/angular-mocks-1.0.2.d.ts rename to Definitions/angular-mocks-1.0.d.ts diff --git a/Definitions/angular-resource-1.0.2.d.ts b/Definitions/angular-resource-1.0.d.ts similarity index 100% rename from Definitions/angular-resource-1.0.2.d.ts rename to Definitions/angular-resource-1.0.d.ts diff --git a/Definitions/angular-sanitize-1.0.2.d.ts b/Definitions/angular-sanitize-1.0.d.ts similarity index 100% rename from Definitions/angular-sanitize-1.0.2.d.ts rename to Definitions/angular-sanitize-1.0.d.ts diff --git a/Definitions/linq-2.2.0.2.d.ts b/Definitions/linq-2.2.d.ts similarity index 98% rename from Definitions/linq-2.2.0.2.d.ts rename to Definitions/linq-2.2.d.ts index 0cf528287..7ddecff84 100644 --- a/Definitions/linq-2.2.0.2.d.ts +++ b/Definitions/linq-2.2.d.ts @@ -1,220 +1,220 @@ -// http://linqjs.codeplex.com/ -// 2.2.0.2 - -// todo: jQuery plugin, RxJS Binding - -module linq { - - interface EnumerableStatic { - Choice(...contents: any[]): Enumerable; - Choice(contents: any[]): Enumerable; - Cycle(...contents: any[]): Enumerable; - Cycle(contents: any[]): Enumerable; - Empty(): Enumerable; - From(obj: any[]): Enumerable; - From(obj: any): Enumerable; - Return(element: any): Enumerable; - Matches(input: string, pattern: RegExp): Enumerable; - Matches(input: string, pattern: string, flags?: string): Enumerable; - Range(start: number, count: number, step?: number): Enumerable; - RangeDown(start: number, count: number, step?: number): Enumerable; - RangeTo(start: number, to: number, step?: number): Enumerable; - Repeat(obj: any, count?: number): Enumerable; - RepeatWithFinalize(initializer: () => any, finalizer: (resource: any) =>void ): Enumerable; - Generate(func: () => any, count?: number): Enumerable; - Generate(func: string, count?: number): Enumerable; - ToInfinity(start?: number, step?: number): Enumerable; - ToNegativeInfinity(start?: number, step?: number): Enumerable; - Unfold(seed, func: ($) => any): Enumerable; - Unfold(seed, func: string): Enumerable; - } - - interface Enumerable { - //Projection and Filtering Methods - CascadeBreadthFirst(func: ($) => any[], resultSelector: (v, i: number) => any): Enumerable; - CascadeBreadthFirst(func: string, resultSelector: string): Enumerable; - CascadeDepthFirst(func: ($) => any[], resultSelector: (v, i: number) => any): Enumerable; - CascadeDepthFirst(func: string, resultSelector: string): Enumerable; - Flatten(...items: any[]): Enumerable; - Pairwise(selector: (prev, next) => any): Enumerable; - Pairwise(selector: string): Enumerable; - Scan(func: (a, b) => any): Enumerable; - Scan(func: string): Enumerable; - Scan(seed, func: (a, b) => any, resultSelector?: ($) => any): Enumerable; - Scan(seed, func: string, resultSelector?: string): Enumerable; - Select(selector: ($, i: number) => any): Enumerable; - Select(selector: string): Enumerable; - SelectMany(collectionSelector: ($, i: number) => any[], resultSelector?: ($, item) => any): Enumerable; - SelectMany(collectionSelector: ($, i: number) => Enumerable, resultSelector?: ($, item) => any): Enumerable; - SelectMany(collectionSelector: string, resultSelector?: string): Enumerable; - Where(predicate: ($, i: number) => bool): Enumerable; - Where(predicate: string): Enumerable; - OfType(type: Function): Enumerable; - Zip(second: any[], selector: (v1, v2, i: number) => any): Enumerable; - Zip(second: any[], selector: string): Enumerable; - Zip(second: Enumerable, selector: (v1, v2, i: number) => any): Enumerable; - Zip(second: Enumerable, selector: string): Enumerable; - //Join Methods - Join(inner: any[], outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2) => any, compareSelector?: (v) => any): Enumerable; - Join(inner: any[], outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; - Join(inner: Enumerable, outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2) => any, compareSelector?: (v) => any): Enumerable; - Join(inner: Enumerable, outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; - GroupJoin(inner: any[], outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2: Enumerable) => any, compareSelector?: (v) => any): Enumerable; - GroupJoin(inner: any[], outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; - GroupJoin(inner: Enumerable, outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2: Enumerable) => any, compareSelector?: (v) => any): Enumerable; - GroupJoin(inner: Enumerable, outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; - //Set Methods - All(predicate: ($) => bool): bool; - All(predicate: string): bool; - Any(predicate?: ($) => bool): bool; - Any(predicate?: string): bool; - Concat(second: any[]): Enumerable; - Concat(second: Enumerable): Enumerable; - Insert(index: number, second: any[]): Enumerable; - Insert(index: number, second: Enumerable): Enumerable; - Alternate(value): Enumerable; - Contains(value, compareSelector?: ($) => any): bool; - Contains(value, compareSelector?: string): bool; - DefaultIfEmpty(defaultValue): Enumerable; - Distinct(compareSelector?: ($) => any): Enumerable; - Distinct(compareSelector?: string): Enumerable; - Except(second: any[], compareSelector?: ($) => any): Enumerable; - Except(second: any[], compareSelector?: string): Enumerable; - Except(second: Enumerable, compareSelector?: ($) => any): Enumerable; - Except(second: Enumerable, compareSelector?: string): Enumerable; - Intersect(second: any[], compareSelector?: ($) => any): Enumerable; - Intersect(second: any[], compareSelector?: string): Enumerable; - Intersect(second: Enumerable, compareSelector?: ($) => any): Enumerable; - Intersect(second: Enumerable, compareSelector?: string): Enumerable; - SequenceEqual(second: any[], compareSelector?: ($) => any): bool; - SequenceEqual(second: any[], compareSelector?: string): bool; - SequenceEqual(second: Enumerable, compareSelector?: ($) => any): bool; - SequenceEqual(second: Enumerable, compareSelector?: string): bool; - Union(second: any[], compareSelector?: ($) => any): Enumerable; - Union(second: any[], compareSelector?: string): Enumerable; - Union(second: Enumerable, compareSelector?: ($) => any): Enumerable; - Union(second: Enumerable, compareSelector?: string): Enumerable; - //Ordering Methods - OrderBy(keySelector?: ($) => any): OrderedEnumerable; - OrderBy(keySelector?: string): OrderedEnumerable; - OrderByDescending(keySelector?: ($) => any): OrderedEnumerable; - OrderByDescending(keySelector?: string): OrderedEnumerable; - Reverse(): Enumerable; - Shuffle(): Enumerable; - //Grouping Methods - GroupBy(keySelector: ($) => any, elementSelector?: ($) => any, resultSelector?: (key, e) => any, compareSelector?: ($) =>any): Enumerable; - GroupBy(keySelector: string, elementSelector?: string, resultSelector?: string, compareSelector?: string): Enumerable; - PartitionBy(keySelector: ($) => any, elementSelector?: ($) => any, resultSelector?: (key, e) => any, compareSelector?: ($) =>any): Enumerable; - PartitionBy(keySelector: string, elementSelector?: string, resultSelector?: string, compareSelector?: string): Enumerable; - BufferWithCount(count: number): Enumerable; - // Aggregate Methods - Aggregate(func: (a, b) => any); - Aggregate(seed, func: (a, b) => any, resultSelector?: ($) => any); - Aggregate(func: string); - Aggregate(seed, func: string, resultSelector?: string); - Average(selector?: ($) => number): number; - Average(selector?: string): number; - Count(predicate?: ($) => bool): number; - Count(predicate?: string): number; - Max(selector?: ($) => number): number; - Max(selector?: string): number; - Min(selector?: ($) => number): number; - Min(selector?: string): number; - MaxBy(selector: ($) => number): any; - MaxBy(selector: string): any; - MinBy(selector: ($) => number): any; - MinBy(selector: string): any; - Sum(selector?: ($) => number): number; - Sum(selector?: string): number; - //Paging Methods - ElementAt(index: number): any; - ElementAtOrDefault(index: number, defaultValue): any; - First(predicate?: ($) => bool): any; - First(predicate?: string): any; - FirstOrDefault(defaultValue, predicate?: ($) => bool): any; - FirstOrDefault(defaultValue, predicate?: string): any; - Last(predicate?: ($) => bool): any; - Last(predicate?: string): any; - LastOrDefault(defaultValue, predicate?: ($) => bool): any; - LastOrDefault(defaultValue, predicate?: string): any; - Single(predicate?: ($) => bool): any; - Single(predicate?: string): any; - SingleOrDefault(defaultValue, predicate?: ($) => bool): any; - SingleOrDefault(defaultValue, predicate?: string): any; - Skip(count: number): Enumerable; - SkipWhile(predicate: ($, i: number) => bool): Enumerable; - SkipWhile(predicate: string): Enumerable; - Take(count: number): Enumerable; - TakeWhile(predicate: ($, i: number) => bool): Enumerable; - TakeWhile(predicate: string): Enumerable; - TakeExceptLast(count?: number): Enumerable; - TakeFromLast(count: number): Enumerable; - IndexOf(item): number; - LastIndexOf(item): number; - // Convert Methods - ToArray(): any[]; - ToLookup(keySelector: ($) => any, elementSelector?: ($) => any, compareSelector?: (key) => any): Lookup; - ToLookup(keySelector: string, elementSelector?: string, compareSelector?: string): Lookup; - ToObject(keySelector: ($) => string, elementSelector: ($) => any): any; - ToObject(keySelector: string, elementSelector: string): any; - ToDictionary(keySelector: ($) => any, elementSelector: ($) => any, compareSelector?: (key) => any): Dictionary; - ToDictionary(keySelector: string, elementSelector: string, compareSelector?: string): Dictionary; - ToJSON(replacer?: (key, value) => any, space?: number): string; - ToJSON(replacer?: string, space?: number): string; - ToString(separator?: string, selector?: ($) =>any): string; - ToString(separator?: string, selector?: string): string; - //Action Methods - Do(action: ($, i: number) => void ): Enumerable; - Do(action: string): Enumerable; - ForEach(action: ($, i: number) => void ): void; - ForEach(func: ($, i: number) => bool): void; - ForEach(action_func: string): void; - Write(separator?: string, selector?: ($) =>any): void; - Write(separator?: string, selector?: string): void; - WriteLine(selector?: ($) =>any): void; - Force(): void; - //Functional Methods - Let(func: (e: Enumerable) => Enumerable): Enumerable; - Share(): Enumerable; - MemoizeAll(): Enumerable; - //Error Handling Methods - Catch(handler: (error: Error) => void ): Enumerable; - Catch(handler: string): Enumerable; - Finally(finallyAction: () => void ): Enumerable; - Finally(finallyAction: string): Enumerable; - //For Debug Methods - Trace(message?: string, selector?: ($) =>any): Enumerable; - Trace(message?: string, selector?: string): Enumerable; - } - - interface OrderedEnumerable extends Enumerable { - ThenBy(keySelector: ($) => any): OrderedEnumerable; - ThenBy(keySelector: string): OrderedEnumerable; - ThenByDescending(keySelector: ($) => any): OrderedEnumerable; - ThenByDescending(keySelector: string): OrderedEnumerable; - } - - interface Grouping extends Enumerable { - Key(); - } - - interface Lookup { - Count(): number; - Get(key): Enumerable; - Contains(key): bool; - ToEnumerable(): Enumerable; - } - - interface Dictionary { - Add(key, value): void; - Get(key): any; - Set(key, value): bool; - Contains(key): bool; - Clear(): void; - Remove(key): void; - Count(): number; - ToEnumerable(): Enumerable; - } -} - +// http://linqjs.codeplex.com/ +// 2.2.0.2 + +// todo: jQuery plugin, RxJS Binding + +module linq { + + interface EnumerableStatic { + Choice(...contents: any[]): Enumerable; + Choice(contents: any[]): Enumerable; + Cycle(...contents: any[]): Enumerable; + Cycle(contents: any[]): Enumerable; + Empty(): Enumerable; + From(obj: any[]): Enumerable; + From(obj: any): Enumerable; + Return(element: any): Enumerable; + Matches(input: string, pattern: RegExp): Enumerable; + Matches(input: string, pattern: string, flags?: string): Enumerable; + Range(start: number, count: number, step?: number): Enumerable; + RangeDown(start: number, count: number, step?: number): Enumerable; + RangeTo(start: number, to: number, step?: number): Enumerable; + Repeat(obj: any, count?: number): Enumerable; + RepeatWithFinalize(initializer: () => any, finalizer: (resource: any) =>void ): Enumerable; + Generate(func: () => any, count?: number): Enumerable; + Generate(func: string, count?: number): Enumerable; + ToInfinity(start?: number, step?: number): Enumerable; + ToNegativeInfinity(start?: number, step?: number): Enumerable; + Unfold(seed, func: ($) => any): Enumerable; + Unfold(seed, func: string): Enumerable; + } + + interface Enumerable { + //Projection and Filtering Methods + CascadeBreadthFirst(func: ($) => any[], resultSelector: (v, i: number) => any): Enumerable; + CascadeBreadthFirst(func: string, resultSelector: string): Enumerable; + CascadeDepthFirst(func: ($) => any[], resultSelector: (v, i: number) => any): Enumerable; + CascadeDepthFirst(func: string, resultSelector: string): Enumerable; + Flatten(...items: any[]): Enumerable; + Pairwise(selector: (prev, next) => any): Enumerable; + Pairwise(selector: string): Enumerable; + Scan(func: (a, b) => any): Enumerable; + Scan(func: string): Enumerable; + Scan(seed, func: (a, b) => any, resultSelector?: ($) => any): Enumerable; + Scan(seed, func: string, resultSelector?: string): Enumerable; + Select(selector: ($, i: number) => any): Enumerable; + Select(selector: string): Enumerable; + SelectMany(collectionSelector: ($, i: number) => any[], resultSelector?: ($, item) => any): Enumerable; + SelectMany(collectionSelector: ($, i: number) => Enumerable, resultSelector?: ($, item) => any): Enumerable; + SelectMany(collectionSelector: string, resultSelector?: string): Enumerable; + Where(predicate: ($, i: number) => bool): Enumerable; + Where(predicate: string): Enumerable; + OfType(type: Function): Enumerable; + Zip(second: any[], selector: (v1, v2, i: number) => any): Enumerable; + Zip(second: any[], selector: string): Enumerable; + Zip(second: Enumerable, selector: (v1, v2, i: number) => any): Enumerable; + Zip(second: Enumerable, selector: string): Enumerable; + //Join Methods + Join(inner: any[], outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2) => any, compareSelector?: (v) => any): Enumerable; + Join(inner: any[], outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; + Join(inner: Enumerable, outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2) => any, compareSelector?: (v) => any): Enumerable; + Join(inner: Enumerable, outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; + GroupJoin(inner: any[], outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2: Enumerable) => any, compareSelector?: (v) => any): Enumerable; + GroupJoin(inner: any[], outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; + GroupJoin(inner: Enumerable, outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2: Enumerable) => any, compareSelector?: (v) => any): Enumerable; + GroupJoin(inner: Enumerable, outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; + //Set Methods + All(predicate: ($) => bool): bool; + All(predicate: string): bool; + Any(predicate?: ($) => bool): bool; + Any(predicate?: string): bool; + Concat(second: any[]): Enumerable; + Concat(second: Enumerable): Enumerable; + Insert(index: number, second: any[]): Enumerable; + Insert(index: number, second: Enumerable): Enumerable; + Alternate(value): Enumerable; + Contains(value, compareSelector?: ($) => any): bool; + Contains(value, compareSelector?: string): bool; + DefaultIfEmpty(defaultValue): Enumerable; + Distinct(compareSelector?: ($) => any): Enumerable; + Distinct(compareSelector?: string): Enumerable; + Except(second: any[], compareSelector?: ($) => any): Enumerable; + Except(second: any[], compareSelector?: string): Enumerable; + Except(second: Enumerable, compareSelector?: ($) => any): Enumerable; + Except(second: Enumerable, compareSelector?: string): Enumerable; + Intersect(second: any[], compareSelector?: ($) => any): Enumerable; + Intersect(second: any[], compareSelector?: string): Enumerable; + Intersect(second: Enumerable, compareSelector?: ($) => any): Enumerable; + Intersect(second: Enumerable, compareSelector?: string): Enumerable; + SequenceEqual(second: any[], compareSelector?: ($) => any): bool; + SequenceEqual(second: any[], compareSelector?: string): bool; + SequenceEqual(second: Enumerable, compareSelector?: ($) => any): bool; + SequenceEqual(second: Enumerable, compareSelector?: string): bool; + Union(second: any[], compareSelector?: ($) => any): Enumerable; + Union(second: any[], compareSelector?: string): Enumerable; + Union(second: Enumerable, compareSelector?: ($) => any): Enumerable; + Union(second: Enumerable, compareSelector?: string): Enumerable; + //Ordering Methods + OrderBy(keySelector?: ($) => any): OrderedEnumerable; + OrderBy(keySelector?: string): OrderedEnumerable; + OrderByDescending(keySelector?: ($) => any): OrderedEnumerable; + OrderByDescending(keySelector?: string): OrderedEnumerable; + Reverse(): Enumerable; + Shuffle(): Enumerable; + //Grouping Methods + GroupBy(keySelector: ($) => any, elementSelector?: ($) => any, resultSelector?: (key, e) => any, compareSelector?: ($) =>any): Enumerable; + GroupBy(keySelector: string, elementSelector?: string, resultSelector?: string, compareSelector?: string): Enumerable; + PartitionBy(keySelector: ($) => any, elementSelector?: ($) => any, resultSelector?: (key, e) => any, compareSelector?: ($) =>any): Enumerable; + PartitionBy(keySelector: string, elementSelector?: string, resultSelector?: string, compareSelector?: string): Enumerable; + BufferWithCount(count: number): Enumerable; + // Aggregate Methods + Aggregate(func: (a, b) => any); + Aggregate(seed, func: (a, b) => any, resultSelector?: ($) => any); + Aggregate(func: string); + Aggregate(seed, func: string, resultSelector?: string); + Average(selector?: ($) => number): number; + Average(selector?: string): number; + Count(predicate?: ($) => bool): number; + Count(predicate?: string): number; + Max(selector?: ($) => number): number; + Max(selector?: string): number; + Min(selector?: ($) => number): number; + Min(selector?: string): number; + MaxBy(selector: ($) => number): any; + MaxBy(selector: string): any; + MinBy(selector: ($) => number): any; + MinBy(selector: string): any; + Sum(selector?: ($) => number): number; + Sum(selector?: string): number; + //Paging Methods + ElementAt(index: number): any; + ElementAtOrDefault(index: number, defaultValue): any; + First(predicate?: ($) => bool): any; + First(predicate?: string): any; + FirstOrDefault(defaultValue, predicate?: ($) => bool): any; + FirstOrDefault(defaultValue, predicate?: string): any; + Last(predicate?: ($) => bool): any; + Last(predicate?: string): any; + LastOrDefault(defaultValue, predicate?: ($) => bool): any; + LastOrDefault(defaultValue, predicate?: string): any; + Single(predicate?: ($) => bool): any; + Single(predicate?: string): any; + SingleOrDefault(defaultValue, predicate?: ($) => bool): any; + SingleOrDefault(defaultValue, predicate?: string): any; + Skip(count: number): Enumerable; + SkipWhile(predicate: ($, i: number) => bool): Enumerable; + SkipWhile(predicate: string): Enumerable; + Take(count: number): Enumerable; + TakeWhile(predicate: ($, i: number) => bool): Enumerable; + TakeWhile(predicate: string): Enumerable; + TakeExceptLast(count?: number): Enumerable; + TakeFromLast(count: number): Enumerable; + IndexOf(item): number; + LastIndexOf(item): number; + // Convert Methods + ToArray(): any[]; + ToLookup(keySelector: ($) => any, elementSelector?: ($) => any, compareSelector?: (key) => any): Lookup; + ToLookup(keySelector: string, elementSelector?: string, compareSelector?: string): Lookup; + ToObject(keySelector: ($) => string, elementSelector: ($) => any): any; + ToObject(keySelector: string, elementSelector: string): any; + ToDictionary(keySelector: ($) => any, elementSelector: ($) => any, compareSelector?: (key) => any): Dictionary; + ToDictionary(keySelector: string, elementSelector: string, compareSelector?: string): Dictionary; + ToJSON(replacer?: (key, value) => any, space?: number): string; + ToJSON(replacer?: string, space?: number): string; + ToString(separator?: string, selector?: ($) =>any): string; + ToString(separator?: string, selector?: string): string; + //Action Methods + Do(action: ($, i: number) => void ): Enumerable; + Do(action: string): Enumerable; + ForEach(action: ($, i: number) => void ): void; + ForEach(func: ($, i: number) => bool): void; + ForEach(action_func: string): void; + Write(separator?: string, selector?: ($) =>any): void; + Write(separator?: string, selector?: string): void; + WriteLine(selector?: ($) =>any): void; + Force(): void; + //Functional Methods + Let(func: (e: Enumerable) => Enumerable): Enumerable; + Share(): Enumerable; + MemoizeAll(): Enumerable; + //Error Handling Methods + Catch(handler: (error: Error) => void ): Enumerable; + Catch(handler: string): Enumerable; + Finally(finallyAction: () => void ): Enumerable; + Finally(finallyAction: string): Enumerable; + //For Debug Methods + Trace(message?: string, selector?: ($) =>any): Enumerable; + Trace(message?: string, selector?: string): Enumerable; + } + + interface OrderedEnumerable extends Enumerable { + ThenBy(keySelector: ($) => any): OrderedEnumerable; + ThenBy(keySelector: string): OrderedEnumerable; + ThenByDescending(keySelector: ($) => any): OrderedEnumerable; + ThenByDescending(keySelector: string): OrderedEnumerable; + } + + interface Grouping extends Enumerable { + Key(); + } + + interface Lookup { + Count(): number; + Get(key): Enumerable; + Contains(key): bool; + ToEnumerable(): Enumerable; + } + + interface Dictionary { + Add(key, value): void; + Get(key): any; + Set(key, value): bool; + Contains(key): bool; + Clear(): void; + Remove(key): void; + Count(): number; + ToEnumerable(): Enumerable; + } +} + declare var Enumerable: linq.EnumerableStatic; \ No newline at end of file From bb5807e3f62c65f2973ae325eb4ceb922e74fb28 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Mon, 29 Oct 2012 20:10:08 +0200 Subject: [PATCH 033/107] Readme update --- Definitions/linq-2.2.d.ts | 6 ++++-- README.md | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Definitions/linq-2.2.d.ts b/Definitions/linq-2.2.d.ts index 7ddecff84..ead5a5ea8 100644 --- a/Definitions/linq-2.2.d.ts +++ b/Definitions/linq-2.2.d.ts @@ -1,5 +1,7 @@ -// http://linqjs.codeplex.com/ -// 2.2.0.2 +// Type definitions for linq.js 2.2 +// Project: http://linqjs.codeplex.com/ +// Definitions by: Marcin Najder +// Definitions: https://github.com/borisyankov/DefinitelyTyped // todo: jQuery plugin, RxJS Binding diff --git a/README.md b/README.md index 4f68d27a2..a7318226b 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ Complete * [jQuery UI](http://jqueryui.com/) * [Knockout.js](http://knockoutjs.com/) * [Knockout.Mapping](https://github.com/SteveSanderson/knockout.mapping) +* [linq.js](http://linqjs.codeplex.com/) (by Marcin Najder (https://github.com/marcinnajder)) * [Modernizr](http://modernizr.com/) * [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) * [Mustache.js](https://github.com/janl/mustache.js) From 3937c6d0a0d7a37157d5c005a1c79ff9b25d4aa3 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Mon, 29 Oct 2012 20:15:13 +0200 Subject: [PATCH 034/107] Fix for Backbone definitions --- Definitions/backbone-0.9.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Definitions/backbone-0.9.d.ts b/Definitions/backbone-0.9.d.ts index 64a9fe8e3..f44034690 100644 --- a/Definitions/backbone-0.9.d.ts +++ b/Definitions/backbone-0.9.d.ts @@ -9,7 +9,7 @@ declare module Backbone { trigger(events: string, ...args: any[]): any; } - export class Model { + export class Model extends Events { static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality @@ -146,6 +146,7 @@ declare module Backbone { export class History { start(options? ); + navigate(fragment: string, options: any); } export class Sync { From a14c1b84b163fd3f3b4a5a30536fe7cdce618ddf Mon Sep 17 00:00:00 2001 From: Marcel Binot Date: Mon, 29 Oct 2012 11:15:35 +0100 Subject: [PATCH 035/107] fixes for Backbone --- Definitions/backbone-0.9.d.ts | 299 +++++++++++++++++++--------------- 1 file changed, 171 insertions(+), 128 deletions(-) diff --git a/Definitions/backbone-0.9.d.ts b/Definitions/backbone-0.9.d.ts index 46281829f..58370d36c 100644 --- a/Definitions/backbone-0.9.d.ts +++ b/Definitions/backbone-0.9.d.ts @@ -1,157 +1,195 @@ // Type definitions for Backbone 0.9 // https://github.com/borisyankov/DefinitelyTyped -declare module "Backbone" { +declare module Backbone { export class Events { - on(events: string, callback: (event) => any, context?: any): any; - off(events?: string, callback?: (event) => any, context?: any): any; - trigger(events: string, ...args: any[]): any; + on(eventName: string, callback: (event, a, b) => void, context?: any) : any; + bind(eventName: string, callback: (event, a, b) => void, context?: any) : any; + off(eventName?: string, callback?: (event, a, b) => void, context?: any): any; + trigger(eventName: string, ...args: any[]): any; } - export class Model { + export interface ICallbackOptions { + success(model: any, resonse: any); + error(model: any, resonse: any); + } + + export interface ISilenceable { + silent: bool; + } + + export interface IAddOptions extends ISilenceable { + at: number; + } + + export interface ICreateOptions extends ISilenceable { + wait: bool; + } + + export class ModelBase { + bind(eventName: string, handler: Function, ctx?: any); + fetch(options? : ICallbackOptions); + url: string; // or url(): string; + parse(response); + toJSON(): string; + } + + export class Model extends ModelBase { static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality + attributes: any; + changed: any[]; + cid: string; + defaults : any; // or defaults(); + id: any; + idAttribute: string; + urlRoot : string; // or urlRoot() + constructor (attributes?: any, options?: any); + initialize(attributes?: any); get(attributeName: string): any; - set(attributeName: string, value: any): void; - set(obj: any): void; + set(attributeName: string, value: any); + set(obj: any); - escape(attribute); - has(attribute); - unset(attribute, options? ); - clear(options? ); - - id: any; - idAttribute: any; - cid; - attributes; - changed; - - bind(ev: string, f: Function, ctx?: any): void; /// ???? - - defaults; // or defaults(); - toJSON(): string; - fetch(options? ); - save(attributes? , options? ): void; - destroy(options? ): void; - validate(attributes); - isValid(); - url(); - urlRoot; // or urlRoot() - parse(response); - clone(); - isNew(); change(); - hasChanged(attribute? ); - changedAttributes(attributes? ); - previous(attribute); - previousAttributes(); + changedAttributes(attributes? : any) : any[]; + clear(options? : ISilenceable ); + clone() : Model; + destroy(options? : ICallbackOptions ); + escape(attribute : string); + has(attribute : string) : bool; + hasChanged(attribute? : string ) : bool; + isNew() : bool; + isValid() : string; + previous(attribute : string) : any; + previousAttributes(): any[]; + save(attributes? : any, options? : ICallbackOptions ); + unset(attribute: string, options? : ISilenceable ); + validate(attributes : any) : any; } - export class Collection { + export class Collection extends ModelBase { static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality - model; - - constructor (models? , options? ); - - models; - toJSON(): any; - - ///// start UNDERSCORE 28: - bind(ev: string, f: Function, ctx?: any): void; + model: Model; + models : any; collection: Model; - create(attrs, opts? ): Collection; - each(f: (elem: any) => void ): void; - last(): any; - last(n: number): any[]; - filter(f: (elem: any) => any): Collection; - without(...values: any[]): Collection; - - // Underscore bindings - - each(object: any, iterator: (value, key, list? ) => void , context?: any): any[]; - forEach(object: any, iterator: (value, key, list? ) => void , context?: any): any[]; - map(object: any, iterator: (value, key, list? ) => void , context?: any): any[]; - reduce(list: any[], iterator: any, memo: (memo: any, element: any, index: number, list: any[]) => any, context?: any): any[]; - reduceRight(list: any[], iterator: (memo: any, element: any, index: number, list: any[]) => any, memo: any, context?: any): any[]; - find(list: any[], iterator: any, context?: any): any; // ??? - detect(list: any[], iterator: any, context?: any): any; // ??? - filter(list: any[], iterator: any, context?: any): any[]; - select(list: any[], iterator: any, context?: any): any[]; - reject(list: any[], iterator: any, context?: any): any[]; - every(list: any[], iterator: any, context?: any): bool; - all(list: any[], iterator: any, context?: any): bool; - any(list: any[], iterator?: any, context?: any): bool; - some(list: any[], iterator?: any, context?: any): bool; - contains(list: any, value: any): bool; - contains(list: any[], value: any): bool; - include(list: any, value: any): bool; - include(list: any[], value: any): bool; - invoke(list: any[], methodName: string, arguments: any[]): any; - invoke(object: any, methodName: string, ...arguments: any[]): any; - max(list: any[], iterator?: any, context?: any): any; - min(list: any[], iterator?: any, context?: any): any; - sortBy(list: any[], iterator?: any, context?: any): any; - sortedIndex(list: any[], valueL: any, iterator?: any): number; - toArray(list: any): any[]; - size(list: any): number; - first(array: any[], n?: number): any; - initial(array: any[], n?: number): any[]; - rest(array: any[], n?: number): any[]; - last(array: any[], n?: number): any; - without(array: any[], ...values: any[]): any[]; - indexOf(array: any[], value: any, isSorted?: bool): number; - shuffle(list: any[]): any[]; - lastIndexOf(array: any[], value: any, fromIndex?: number): number; - isEmpty(object: any): bool; - groupBy(list: any[], iterator: any): any; - - add(models, options? ); - remove(models, options? ); - get(id); - getByCid(cid); - at(index: number); - push(model, options? ); - pop(options? ); - unshift(model, options? ); - shift(options? ); length: number; - //comparator; - sort(options? ); - pluck(attribute); - where(attributes); - url; // or url() - parse(response); - fetch(options?: any): void; - reset(models, options? ); - create(attributes, options? ); + + constructor (models? :any , options? ); + + add(model: Model, options? : IAddOptions); + add(models: Model[], options? : IAddOptions); + at(index: number) : Model; + comparator(attribute: string): number; + comparator(compare: Model, to:Model): number; + get(id : any) : Model; + getByCid(cid) : Model; + create(attributes: any, options? : ICreateOptions ): Collection; + pluck(attribute:string) : any[]; + push(model: Model, options? : IAddOptions); + pop(options? : ISilenceable); + remove(model: Model, options? : ISilenceable); + remove(models: Model[], options? : ISilenceable); + reset(models : Model[], options? ); + shift(options? : ISilenceable); + sort(options? : ISilenceable); + unshift(model: Model, options?: IAddOptions); + where(properies: any): Model[]; + + all(iterator: (element: Model, index:number) => bool, context?: any): bool; + any(iterator:(element: Model, index:number) => bool, context?: any): bool; + collect(iterator: (element: Model, index:number, context? : any ) => any[] , context?: any): any[]; + compact(): Model[]; + contains(value: any): bool; + countBy(iterator: (element:Model, index:number) => any) : any[]; + countBy(attribute: string) : any[]; + detect(iterator: (item: any) => bool, context?: any): any; // ??? + difference(...model: Model[]) : Model[]; + drop(): Model; + drop(n: number): Model[]; + each(iterator: (element: Model, index:number, list? ) => void , context?: any); + every(iterator: (element: Model, index:number) => bool, context?: any): bool; + filter(iterator: (elemebt:Model, index:number) => bool, context?: any): Model[]; + find(iterator: (element:Model, index:number) => bool, context?: any): Model; + first(): Model; + first(n: number): Model[]; + flatten(shallow?: bool): Model[]; + foldl(iterator: (memo: any, element: Model, index:number) => any, initialMemo: any, context?: any): any; + forEach(iterator: (element: Model, index:number, list? ) => void , context?: any); + groupBy(iterator: (element:Model, index:number) => any) : any[]; + groupBy(attribute: string) : any[]; + include(value: any): bool; + indexOf(element: Model, isSorted?: bool): number; + initial(): Model; + initial(n: number): Model[]; + inject(iterator: (memo: any, element: Model, index:number) => any, initialMemo: any, context?: any): any; + intersection(...model: Model[]) : Model[]; + isEmpty(object: any): bool; + invoke(methodName: string, arguments?: any[]); + last(): Model; + last(n: number): Model[]; + lastIndexOf(element: Model, fromIndex?: number): number; + map(iterator: (element: Model, index:number, context? : any ) => any[] , context?: any): any[]; + max(iterator?: (element:Model, index:number) => any, context?: any): Model; + min(iterator?: (element:Model, index:number) => any, context?: any): Model; + object(...values: any[]): any[]; + reduce(iterator: (memo: any, element: Model, index:number) => any, initialMemo: any, context?: any): any; + select(iterator: any, context?: any): any[]; + size(): number; + shuffle(): any[]; + some(iterator:(element: Model, index:number) => bool, context?: any): bool; + sortBy(iterator: (element:Model, index:number) => number, context?: any): Model[]; + sortBy(attribute:string, context?: any): Model[]; + sortedIndex(element: Model, iterator?: (element:Model, index:number) => number): number; + range(stop: number, step?:number); + range(start: number, stop: number, step?:number); + reduceRight(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any[]; + reject(iterator: (element:Model, index:number) => bool, context?: any): Model[]; + rest(): Model; + rest(n: number): Model[]; + tail(): Model; + tail(n: number): Model[]; + toArray(): any[]; + union(...model: Model[]) : Model[]; + uniq(isSorted? : bool, iterator?: (element:Model, index:number) => bool) : Model[]; + without(...values: any[]): Model[]; + zip(...model: Model[]): Model[]; + } + + export interface IRouterOptions { + routes: any; + } + + export interface INavigateOptions { + trigger: bool; } export class Router { static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality - routes; - constructor (options? ); - route(route, name, callback? ); - navigate(fragment, options? ); + routes : any; + + constructor (options? : IRouterOptions); + initialize (options? : IRouterOptions); + route(route: string, name: string, callback?: (...parameter:any[]) => void ); + navigate(fragment : string, options? : INavigateOptions); + } + + export interface IHistoryOptions extends ISilenceable { + pushState: bool; + root: string; } export var history: History; - export class History { - start(options? ); - } - - export class Sync { - sync(method, model, options? ); - emulateHTTP: bool; - emulateJSONBackbone: bool; + start(options? : IHistoryOptions ); + pushSate(); } export class View { @@ -163,7 +201,7 @@ declare module "Backbone" { $(selector: string): any; model: Model; make(tagName: string, attrs? , opts? ): View; - setElement(element: HTMLElement, delegate?: bool): void; + setElement(element: HTMLElement, delegate?: bool); tagName: string; events: any; @@ -173,15 +211,20 @@ declare module "Backbone" { attributes; $(selector); render(); - remove(): void;; + remove(); make(tagName, attributes? , content? ); //delegateEvents: any; delegateEvents(events?: any): any; undelegateEvents(); } - export class Utility { - noConflict(): any; - setDomLibrary(jQueryNew); - } + // SYNC + function sync(method, model, options? : ICallbackOptions); + var emulateHTTP: bool; + var emulateJSONBackbone: bool; + + // Utility + function noConflict(): Backbone; + function setDomLibrary(jQueryNew); + } \ No newline at end of file From 50e4b795e934f933e24a22a509d1bcc709f234a3 Mon Sep 17 00:00:00 2001 From: David Berneda Date: Tue, 30 Oct 2012 09:43:02 +0100 Subject: [PATCH 036/107] TeeChart definitions for TypeScript --- Definitions/teechart.d.ts | 681 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 681 insertions(+) create mode 100644 Definitions/teechart.d.ts diff --git a/Definitions/teechart.d.ts b/Definitions/teechart.d.ts new file mode 100644 index 000000000..e4aba5b45 --- /dev/null +++ b/Definitions/teechart.d.ts @@ -0,0 +1,681 @@ +/** + * TeeChart(tm) for TypeScript + * + * v1.3 October 2012 + * Copyright(c) 2012 by Steema Software SL. All Rights Reserved. + * http://www.steema.com + * + * Licensed with commercial and non-commercial attributes, + * specifically: http://www.steema.com/licensing/html5 + * + * TypeScript is a Microsoft product: www.typescriptlang.org + * + */ + +/** + * @author Steema Software + * @version 1.3 + */ + + +/// + +module Tee { + + interface IPoint { + x: number; + y: number; + } + + interface IRectangle { + x: number; + y: number; + width: number; + height: number; + + contains(point: IPoint): bool; + } + + interface ITool { + active: bool; + chart: IChart; + + mousedown(event): bool; + mousemove(event): bool; + clicked(p:IPoint): bool; + draw(): void; + } + + interface IGradient { + chart: IChart; + visible: bool; + + colors: string[]; + direction: string; + stops: number[]; + offset: IPoint; + } + + interface IShadow { + chart: IChart; + visible: bool; + blur:number; + color: string; + width:number; + height:number; + } + + interface IStroke { + chart: IChart; + fill: string; + size: number; + join: string; + cap: string; + dash: number[]; + gradient: IGradient; + } + + interface IFont { + chart: IChart; + style: string; + gradient: IGradient; + fill: string; + stroke: IStroke; + shadow: IShadow; + textAlign: string; + baseLine: string; + + getSize():number; + setSize(size:number):void; + } + + interface IImage { + url: string; + chart: IChart; + visible: bool; + } + + interface IFormat { + font: IFont; + gradient: IGradient; + shadow: IShadow; + stroke: IStroke; + round: IPoint; + transparency: number; + image: IImage; + fill: string; + + textHeight(text:string): number; + textWidth(text:string): number; + drawText(bounds:IRectangle, text:string); + rectangle(x:number, y:number, width:number, height:number); + poligon(points:IPoint[]); + ellipse(x:number, y:number, width:number, height:number); + } + + interface IMargins { + left: number; + top: number; + right: number; + bottom: number; + } + + interface IAnnotation extends ITool { + position: IPoint; + margins: IMargins; + items: IAnnotation[]; + bounds: IRectangle; + visible: bool; + transparent: bool; + text: string; + format: IFormat; + + add(text: string): IAnnotation; + resize(): void; + clicked(point: IPoint): bool; + draw(): void; + } + + interface IPanel { + format: IFormat; + transparent: bool; + margins: IMargins; + } + + interface ITitle extends IAnnotation { + expand: bool; + padding: number; + transparent: bool; + } + + interface IPalette { + colors: string[]; + + get(index: number): string; + } + + interface IArrow extends IFormat { + length: number; + underline: bool; + } + + interface IMarks extends IAnnotation { + arrow: IArrow; + series: ISeries; + + style: string; + + drawEvery: number; + visible: bool; + } + + interface ISeriesData { + values: number[]; + labels: string[]; + source: any; + } + + interface ICursor { + cursor: string; + } + + interface ISeries { + data: ISeriesData; + marks: IMarks; + + yMandatory: bool; + horizAxis: string; + vertAxis: string; + + format: IFormat; + hover: IFormat; + + visible: bool; + + cursor: ICursor; + over: number; + + palette: IPalette; + colorEach: string; + + useAxes: bool; + decimals: number; + + title: string; + + //refresh(failure: function): void; + + toPercent(index: number): string; + markText(index: number): string; + + valueText(index: number): string; + + associatedToAxis(axis: IAxis): bool; + + bounds(rectangle: IRectangle): void; + + calc(index: number, position: IPoint): void; + + clicked(position: IPoint): number; + + minXValue(): number; + maxXValue(): number; + + minYValue(): number; + maxYValue(): number; + + count(): number; + + addRandom(count: number, range?: number, x?: bool): ISeries; + + + } + + interface IAxisLabels { + chart: IChart; + format: IFormat; + decimals: number; + padding: number; + separation: number; // % + visible: bool; + rotation: number; + alternate: bool; + maxWidth: number; + + labelStyle: string; + dateFormat: string; + + getLabel(value: number): string; + width(value: number): number; + + } + + interface IGrid { + chart: IChart; + format: IFormat; + visible: bool; + lineDash: bool; + } + + interface ITicks { + chart: IChart; + stroke: IStroke; + visible: bool; + length: number; + } + + interface IMinorTicks extends ITicks { + count: number; + } + + interface IAxisTitle extends IAnnotation { + padding: number; + transparent: bool; + } + + interface IAxis { + chart: IChart; + visible: bool; + inverted: bool; + + horizontal: bool; // readonly + otherSize: bool; // readonly + bounds: IRectangle; // readonly? + + position: number; + format: IFormat; + custom: bool; // readonly + + grid: IGrid; + labels: IAxisLabels; + ticks: ITicks; + minorTicks: IMinorTicks; + innerTicks: ITicks; + + title: IAxisTitle; + + automatic: bool; + minimum: number; + maximum: number; + increment: number; + log: bool; + + startPos: number; + endPos: number; + + start: number; // % + end: number; // % + + axisSize: number; + + scale: number; + increm: number; + + calc(value: number): number; + fromPos(position: number): number; + fromSize(size: number): number; + + hasAnySeries(): bool; + scroll(delta: number): void; + setMinMax(minimum: number, maximum: number): void; + } + + interface IAxes { + chart: IChart; + visible: bool; + + left: IAxis; + top: IAxis; + right: IAxis; + bottom: IAxis; + + items: IAxis[]; + + add(horizontal: bool, otherSide: bool): IAxis; + //each(f: function): void; + } + + interface ISymbol { + chart: IChart; + format: IFormat; + width: number; + height: number; + padding: number; + visible: bool; + } + + interface ILegend { + chart: IChart; + + transparent: bool; + + format: IFormat; + title: IAnnotation; + + bounds: IRectangle; + position: string; + visible: bool; + inverted: bool; + padding: number; + align: number; + + fontColor: bool; + + dividing: IStroke; + over: number; + symbol: ISymbol; + + itemHeight: number; + innerOff: number; + + legendStyle: string; + textStyle: string; + + availRows(): number; + itemsCount(): number; + totalWidth(): number; + showValues(): bool; + itemText(series: ISeries, index: number): string; + isVertical(): bool; + } + + interface IScroll { + chart: IChart; + active: bool; + enabled: bool; + direction: string; + mouseButton: number; + + position: IPoint; + } + + interface ISeriesList { + chart: IChart; + items: ISeries[]; + + anyUsesAxes(): bool; + clicked(position: IPoint): bool; + //each(f: function): void; + firstVisible(): ISeries; + + } + + interface ITools { + chart: IChart; + items: ITool[]; + + add(tool: ITool): ITool; + } + + interface IWall { + format: IFormat; + visible: bool; + bounds: IRectangle; + } + + interface IWalls { + visible: bool; + left: IWall; + right: IWall; + bottom: IWall; + back: IWall; + } + + interface IZoom { + chart: IChart; + active: bool; + direction: string; + enabled: bool; + mouseButton: number; + format: IFormat; + + reset(): void; + } + + interface IChart { + addSeries(series:ISeries): ISeries; + draw(context?:CanvasRenderingContext2D); + } + + // SERIES + + interface ICustomBar extends ISeries { + sideMargins: number; + useOrigin: bool; + origin: number; + + offset: number; + barSize: number; + barStyle: string; + + stacked: string; + } + + interface ISeriesPointer { + chart: IChart; + format: IFormat; + visible: bool; + colorEach: bool; + style: string; + width: number; + height: number; + } + + interface ICustomSeries extends ISeries { + pointer: ISeriesPointer; + + stacked: string; + stairs: bool; + } + + interface ILine extends ICustomSeries { + smooth: number; + } + + interface ISmoothLine extends ILine { + smooth: number; + } + + interface IArea extends ISeries { + useOrigin: bool; + origin: number; + } + + interface IPie extends ISeries { + donut: number; + rotation: number; + sort: string; + orderAscending: bool; + explode: number[]; + concentric: bool; + + calcPos(angle: number, position: IPoint): void; + } + + interface IBubbleData extends ISeriesData { + radius: number[]; + } + + interface IBubble extends ICustomSeries { + data: IBubbleData; + } + + interface IGanttData extends ISeriesData { + start: number[]; + x: number[]; + end: number[]; + } + + interface IGantt extends ISeries { + data: IGanttData; + dateFormat: string; + colorEach: string; + height: number; + margin: IPoint; + + add(index: number, label: string, start: number, end: number): void; + bounds(index: number, rectangle: IRectangle): void; + } + + interface ICandleData extends ISeriesData { + open: number[]; + close: number[]; + high: number[]; + low: number[]; + } + + interface ICandle extends ICustomSeries { + data: ICandleData; + higher: IFormat; + lower: IFormat; + style: string; + } + + // TOOLS + + interface IDragTool extends ITool { + series: ISeries; + } + + interface ICursorTool extends ITool { + direction: string; + size: IPoint; + + followMouse: bool; + dragging: number; + + format: IFormat; + + horizAxis: IAxis; + vertAxis: IAxis; + + render: string; + + over(point: IPoint): bool; + setRender(render: string): void; + } + + interface IToolTip extends IAnnotation { + animated: number; + autoHide: bool; + autoRedraw: bool; + currentSeries: ISeries; + currentIndex: number; + delay: number; + + hide(): void; + refresh(series: ISeries, index: number): void; + } + + declare class Point implements IPoint { + public x:number; + public y:number; + } + + declare class Chart implements IChart { + //public aspect: IAspect; + + public axes: IAxes; + public footer: ITitle; + public legend: ILegend; + public panel: IPanel; + public scroll: IScroll; + public series: ISeriesList; + public title: ITitle; + public tools: ITools; + public walls: IWalls; + public zoom: IZoom; + + public bounds: IRectangle; + public canvas: HTMLCanvasElement; + public chartRect: IRectangle; + public palette: IPalette; + + constructor(canvas: string); + addSeries(series: ISeries): ISeries; + getSeries(index: number): ISeries; + removeSeries(series:ISeries): void; + + draw(context?:CanvasRenderingContext2D); + toImage(image: HTMLImageElement, format:string, quality:number): void; + } + + // SERIES + + declare var Line: { + prototype: ILine; + new(values?:number[]): ILine; + } + + declare var PointXY: { + prototype: ICustomSeries; + new(values?:number[]): ICustomSeries; + } + + declare var Area: { + prototype: IArea; + new(values?:number[]): IArea; + } + + declare var HorizArea: { + prototype: IArea; + new(values?:number[]): IArea; + } + + declare var Bar: { + prototype: ICustomBar; + new(values?:number[]): ICustomBar; + } + + declare var HorizBar: { + prototype: ICustomBar; + new(values?:number[]): ICustomBar; + } + + declare var Pie: { + prototype: IPie; + new(values?:number[]): IPie; + } + + declare var Donut: { + prototype: IPie; + new(values?:number[]): IPie; + } + + declare var Bubble: { + prototype: IBubble; + new(values?:number[]): IBubble; + } + + declare var Gantt: { + prototype: IGantt; + new(values?:number[]): IGantt; + } + + declare var Volume: { + prototype: ICustomBar; + new(values?:number[]): ICustomBar; + } + + declare var Candle: { + prototype: ICandle; + new(values?:number[]): ICandle; + } + + // TOOLS + + declare var CursorTool: { + prototype: ICursorTool; + new(chart?: Chart): ICursorTool; + } + + declare var DragTool: { + prototype: IDragTool; + new(chart?: Chart): IDragTool; + } + + declare var ToolTip: { + prototype: IToolTip; + new(chart?: Chart): IToolTip; + } +} From 0ecfdee637bc3c5b50ad2df5a8a787175503a4bf Mon Sep 17 00:00:00 2001 From: BreeeZe Date: Tue, 30 Oct 2012 11:40:24 +0100 Subject: [PATCH 037/107] Defined different KnockoutObservable types for primitive types. --- Definitions/knockout-2.2.d.ts | 52 +++++++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 11 deletions(-) diff --git a/Definitions/knockout-2.2.d.ts b/Definitions/knockout-2.2.d.ts index 598669a24..14a5395d2 100644 --- a/Definitions/knockout-2.2.d.ts +++ b/Definitions/knockout-2.2.d.ts @@ -41,18 +41,42 @@ interface KnockoutObservableArray extends KnockoutObservableArrayFunctions { (value: any[]): KnockoutObservableArray; } -interface KnockoutObservable { +interface KnockoutObservableBase { fn; - (): any; - (value): void; - extend(source); subscribe(func: Function): KnockoutSubscription; } -interface KnockoutComputed extends KnockoutObservable { +interface KnockoutObservableAny extends KnockoutObservableBase { + + (): any; + (value): void; +} + +interface KnockoutObservableString extends KnockoutObservableBase { + (): string; + (value: string): void; +} + + +interface KnockoutObservableNumber extends KnockoutObservableBase { + (): number; + (value: number): void; +} + +interface KnockoutObservableBool extends KnockoutObservableBase { + (): bool; + (value: bool): void; +} + +interface KnockoutObservableDate extends KnockoutObservableBase { + (): Date; + (value: Date): void; +} + +interface KnockoutComputed extends KnockoutObservableBase { (): KnockoutComputed; (func: Function, context?: any): KnockoutComputed; (def: KnockoutComputedDefine): KnockoutComputed; @@ -80,11 +104,11 @@ interface KnockoutBindingContext { interface KnockoutBindingHandler { // TODO: Work out how to define bindingHandlers when not using all the args // adding element?: any, etc doesnt work... - //init(element: any, valueAccessor: any, allBindingsAccessor: any, viewModel: any, bindingContext: KnockoutBindingContext) : void; - //update(element: any, valueAccessor: any, allBindingsAccessor: any, viewModel: any, bindingContext: KnockoutBindingContext) : void; - init: any; - update: any; - options: any; + init(element: any, valueAccessor: () => any, allBindingsAccessor: () => any, viewModel: any, bindingContext: KnockoutBindingContext): void; + update(element: any, valueAccessor: () => any, allBindingsAccessor: () => any, viewModel: any, bindingContext: KnockoutBindingContext): void; + //init: any; + //update: any; + options?: any; } interface KnockoutBindingHandlers { @@ -172,7 +196,13 @@ interface KnockoutStatic { applyBindings(viewModel: any, rootNode?: any): void; applyBindingsToDescendants(viewModel: any, rootNode: any): void; - observable(intial? ): KnockoutObservable; + + observable(value: string): KnockoutObservableString; + observable(value: Date): KnockoutObservableDate; + observable(value: number): KnockoutObservableNumber; + observable(value: bool): KnockoutObservableBool; + observable(value?: any): KnockoutObservableAny; + contextFor(node: any): any; isSubscribable(instance: any): bool; subscribable(): void; From c90059bdb2b768b2b8411ab486b7a08e857f03a3 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Tue, 30 Oct 2012 13:21:00 +0200 Subject: [PATCH 038/107] Update Backbone definitions --- Definitions/backbone-0.9.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Definitions/backbone-0.9.d.ts b/Definitions/backbone-0.9.d.ts index f44034690..119b5584b 100644 --- a/Definitions/backbone-0.9.d.ts +++ b/Definitions/backbone-0.9.d.ts @@ -1,5 +1,7 @@ // Type definitions for Backbone 0.9 -// https://github.com/borisyankov/DefinitelyTyped +// Project: http://backbonejs.org/ +// Definitions: https://github.com/borisyankov/DefinitelyTyped + declare module Backbone { From 1adf8d7cd90199ce882a218a3df74e3697d23d36 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Tue, 30 Oct 2012 13:26:46 +0200 Subject: [PATCH 039/107] Update Teechart files --- .../{teechart.d.ts => teechart-1.3.d.ts} | 1362 ++++++++--------- README.md | 1 + 2 files changed, 682 insertions(+), 681 deletions(-) rename Definitions/{teechart.d.ts => teechart-1.3.d.ts} (94%) diff --git a/Definitions/teechart.d.ts b/Definitions/teechart-1.3.d.ts similarity index 94% rename from Definitions/teechart.d.ts rename to Definitions/teechart-1.3.d.ts index e4aba5b45..af93aa762 100644 --- a/Definitions/teechart.d.ts +++ b/Definitions/teechart-1.3.d.ts @@ -1,681 +1,681 @@ -/** - * TeeChart(tm) for TypeScript - * - * v1.3 October 2012 - * Copyright(c) 2012 by Steema Software SL. All Rights Reserved. - * http://www.steema.com - * - * Licensed with commercial and non-commercial attributes, - * specifically: http://www.steema.com/licensing/html5 - * - * TypeScript is a Microsoft product: www.typescriptlang.org - * - */ - -/** - * @author Steema Software - * @version 1.3 - */ - - -/// - -module Tee { - - interface IPoint { - x: number; - y: number; - } - - interface IRectangle { - x: number; - y: number; - width: number; - height: number; - - contains(point: IPoint): bool; - } - - interface ITool { - active: bool; - chart: IChart; - - mousedown(event): bool; - mousemove(event): bool; - clicked(p:IPoint): bool; - draw(): void; - } - - interface IGradient { - chart: IChart; - visible: bool; - - colors: string[]; - direction: string; - stops: number[]; - offset: IPoint; - } - - interface IShadow { - chart: IChart; - visible: bool; - blur:number; - color: string; - width:number; - height:number; - } - - interface IStroke { - chart: IChart; - fill: string; - size: number; - join: string; - cap: string; - dash: number[]; - gradient: IGradient; - } - - interface IFont { - chart: IChart; - style: string; - gradient: IGradient; - fill: string; - stroke: IStroke; - shadow: IShadow; - textAlign: string; - baseLine: string; - - getSize():number; - setSize(size:number):void; - } - - interface IImage { - url: string; - chart: IChart; - visible: bool; - } - - interface IFormat { - font: IFont; - gradient: IGradient; - shadow: IShadow; - stroke: IStroke; - round: IPoint; - transparency: number; - image: IImage; - fill: string; - - textHeight(text:string): number; - textWidth(text:string): number; - drawText(bounds:IRectangle, text:string); - rectangle(x:number, y:number, width:number, height:number); - poligon(points:IPoint[]); - ellipse(x:number, y:number, width:number, height:number); - } - - interface IMargins { - left: number; - top: number; - right: number; - bottom: number; - } - - interface IAnnotation extends ITool { - position: IPoint; - margins: IMargins; - items: IAnnotation[]; - bounds: IRectangle; - visible: bool; - transparent: bool; - text: string; - format: IFormat; - - add(text: string): IAnnotation; - resize(): void; - clicked(point: IPoint): bool; - draw(): void; - } - - interface IPanel { - format: IFormat; - transparent: bool; - margins: IMargins; - } - - interface ITitle extends IAnnotation { - expand: bool; - padding: number; - transparent: bool; - } - - interface IPalette { - colors: string[]; - - get(index: number): string; - } - - interface IArrow extends IFormat { - length: number; - underline: bool; - } - - interface IMarks extends IAnnotation { - arrow: IArrow; - series: ISeries; - - style: string; - - drawEvery: number; - visible: bool; - } - - interface ISeriesData { - values: number[]; - labels: string[]; - source: any; - } - - interface ICursor { - cursor: string; - } - - interface ISeries { - data: ISeriesData; - marks: IMarks; - - yMandatory: bool; - horizAxis: string; - vertAxis: string; - - format: IFormat; - hover: IFormat; - - visible: bool; - - cursor: ICursor; - over: number; - - palette: IPalette; - colorEach: string; - - useAxes: bool; - decimals: number; - - title: string; - - //refresh(failure: function): void; - - toPercent(index: number): string; - markText(index: number): string; - - valueText(index: number): string; - - associatedToAxis(axis: IAxis): bool; - - bounds(rectangle: IRectangle): void; - - calc(index: number, position: IPoint): void; - - clicked(position: IPoint): number; - - minXValue(): number; - maxXValue(): number; - - minYValue(): number; - maxYValue(): number; - - count(): number; - - addRandom(count: number, range?: number, x?: bool): ISeries; - - - } - - interface IAxisLabels { - chart: IChart; - format: IFormat; - decimals: number; - padding: number; - separation: number; // % - visible: bool; - rotation: number; - alternate: bool; - maxWidth: number; - - labelStyle: string; - dateFormat: string; - - getLabel(value: number): string; - width(value: number): number; - - } - - interface IGrid { - chart: IChart; - format: IFormat; - visible: bool; - lineDash: bool; - } - - interface ITicks { - chart: IChart; - stroke: IStroke; - visible: bool; - length: number; - } - - interface IMinorTicks extends ITicks { - count: number; - } - - interface IAxisTitle extends IAnnotation { - padding: number; - transparent: bool; - } - - interface IAxis { - chart: IChart; - visible: bool; - inverted: bool; - - horizontal: bool; // readonly - otherSize: bool; // readonly - bounds: IRectangle; // readonly? - - position: number; - format: IFormat; - custom: bool; // readonly - - grid: IGrid; - labels: IAxisLabels; - ticks: ITicks; - minorTicks: IMinorTicks; - innerTicks: ITicks; - - title: IAxisTitle; - - automatic: bool; - minimum: number; - maximum: number; - increment: number; - log: bool; - - startPos: number; - endPos: number; - - start: number; // % - end: number; // % - - axisSize: number; - - scale: number; - increm: number; - - calc(value: number): number; - fromPos(position: number): number; - fromSize(size: number): number; - - hasAnySeries(): bool; - scroll(delta: number): void; - setMinMax(minimum: number, maximum: number): void; - } - - interface IAxes { - chart: IChart; - visible: bool; - - left: IAxis; - top: IAxis; - right: IAxis; - bottom: IAxis; - - items: IAxis[]; - - add(horizontal: bool, otherSide: bool): IAxis; - //each(f: function): void; - } - - interface ISymbol { - chart: IChart; - format: IFormat; - width: number; - height: number; - padding: number; - visible: bool; - } - - interface ILegend { - chart: IChart; - - transparent: bool; - - format: IFormat; - title: IAnnotation; - - bounds: IRectangle; - position: string; - visible: bool; - inverted: bool; - padding: number; - align: number; - - fontColor: bool; - - dividing: IStroke; - over: number; - symbol: ISymbol; - - itemHeight: number; - innerOff: number; - - legendStyle: string; - textStyle: string; - - availRows(): number; - itemsCount(): number; - totalWidth(): number; - showValues(): bool; - itemText(series: ISeries, index: number): string; - isVertical(): bool; - } - - interface IScroll { - chart: IChart; - active: bool; - enabled: bool; - direction: string; - mouseButton: number; - - position: IPoint; - } - - interface ISeriesList { - chart: IChart; - items: ISeries[]; - - anyUsesAxes(): bool; - clicked(position: IPoint): bool; - //each(f: function): void; - firstVisible(): ISeries; - - } - - interface ITools { - chart: IChart; - items: ITool[]; - - add(tool: ITool): ITool; - } - - interface IWall { - format: IFormat; - visible: bool; - bounds: IRectangle; - } - - interface IWalls { - visible: bool; - left: IWall; - right: IWall; - bottom: IWall; - back: IWall; - } - - interface IZoom { - chart: IChart; - active: bool; - direction: string; - enabled: bool; - mouseButton: number; - format: IFormat; - - reset(): void; - } - - interface IChart { - addSeries(series:ISeries): ISeries; - draw(context?:CanvasRenderingContext2D); - } - - // SERIES - - interface ICustomBar extends ISeries { - sideMargins: number; - useOrigin: bool; - origin: number; - - offset: number; - barSize: number; - barStyle: string; - - stacked: string; - } - - interface ISeriesPointer { - chart: IChart; - format: IFormat; - visible: bool; - colorEach: bool; - style: string; - width: number; - height: number; - } - - interface ICustomSeries extends ISeries { - pointer: ISeriesPointer; - - stacked: string; - stairs: bool; - } - - interface ILine extends ICustomSeries { - smooth: number; - } - - interface ISmoothLine extends ILine { - smooth: number; - } - - interface IArea extends ISeries { - useOrigin: bool; - origin: number; - } - - interface IPie extends ISeries { - donut: number; - rotation: number; - sort: string; - orderAscending: bool; - explode: number[]; - concentric: bool; - - calcPos(angle: number, position: IPoint): void; - } - - interface IBubbleData extends ISeriesData { - radius: number[]; - } - - interface IBubble extends ICustomSeries { - data: IBubbleData; - } - - interface IGanttData extends ISeriesData { - start: number[]; - x: number[]; - end: number[]; - } - - interface IGantt extends ISeries { - data: IGanttData; - dateFormat: string; - colorEach: string; - height: number; - margin: IPoint; - - add(index: number, label: string, start: number, end: number): void; - bounds(index: number, rectangle: IRectangle): void; - } - - interface ICandleData extends ISeriesData { - open: number[]; - close: number[]; - high: number[]; - low: number[]; - } - - interface ICandle extends ICustomSeries { - data: ICandleData; - higher: IFormat; - lower: IFormat; - style: string; - } - - // TOOLS - - interface IDragTool extends ITool { - series: ISeries; - } - - interface ICursorTool extends ITool { - direction: string; - size: IPoint; - - followMouse: bool; - dragging: number; - - format: IFormat; - - horizAxis: IAxis; - vertAxis: IAxis; - - render: string; - - over(point: IPoint): bool; - setRender(render: string): void; - } - - interface IToolTip extends IAnnotation { - animated: number; - autoHide: bool; - autoRedraw: bool; - currentSeries: ISeries; - currentIndex: number; - delay: number; - - hide(): void; - refresh(series: ISeries, index: number): void; - } - - declare class Point implements IPoint { - public x:number; - public y:number; - } - - declare class Chart implements IChart { - //public aspect: IAspect; - - public axes: IAxes; - public footer: ITitle; - public legend: ILegend; - public panel: IPanel; - public scroll: IScroll; - public series: ISeriesList; - public title: ITitle; - public tools: ITools; - public walls: IWalls; - public zoom: IZoom; - - public bounds: IRectangle; - public canvas: HTMLCanvasElement; - public chartRect: IRectangle; - public palette: IPalette; - - constructor(canvas: string); - addSeries(series: ISeries): ISeries; - getSeries(index: number): ISeries; - removeSeries(series:ISeries): void; - - draw(context?:CanvasRenderingContext2D); - toImage(image: HTMLImageElement, format:string, quality:number): void; - } - - // SERIES - - declare var Line: { - prototype: ILine; - new(values?:number[]): ILine; - } - - declare var PointXY: { - prototype: ICustomSeries; - new(values?:number[]): ICustomSeries; - } - - declare var Area: { - prototype: IArea; - new(values?:number[]): IArea; - } - - declare var HorizArea: { - prototype: IArea; - new(values?:number[]): IArea; - } - - declare var Bar: { - prototype: ICustomBar; - new(values?:number[]): ICustomBar; - } - - declare var HorizBar: { - prototype: ICustomBar; - new(values?:number[]): ICustomBar; - } - - declare var Pie: { - prototype: IPie; - new(values?:number[]): IPie; - } - - declare var Donut: { - prototype: IPie; - new(values?:number[]): IPie; - } - - declare var Bubble: { - prototype: IBubble; - new(values?:number[]): IBubble; - } - - declare var Gantt: { - prototype: IGantt; - new(values?:number[]): IGantt; - } - - declare var Volume: { - prototype: ICustomBar; - new(values?:number[]): ICustomBar; - } - - declare var Candle: { - prototype: ICandle; - new(values?:number[]): ICandle; - } - - // TOOLS - - declare var CursorTool: { - prototype: ICursorTool; - new(chart?: Chart): ICursorTool; - } - - declare var DragTool: { - prototype: IDragTool; - new(chart?: Chart): IDragTool; - } - - declare var ToolTip: { - prototype: IToolTip; - new(chart?: Chart): IToolTip; - } -} +/** + * TeeChart(tm) for TypeScript + * + * v1.3 October 2012 + * Copyright(c) 2012 by Steema Software SL. All Rights Reserved. + * http://www.steema.com + * + * Licensed with commercial and non-commercial attributes, + * specifically: http://www.steema.com/licensing/html5 + * + * TypeScript is a Microsoft product: www.typescriptlang.org + * + */ + +/** + * @author Steema Software + * @version 1.3 + */ + + +/// + +module Tee { + + interface IPoint { + x: number; + y: number; + } + + interface IRectangle { + x: number; + y: number; + width: number; + height: number; + + contains(point: IPoint): bool; + } + + interface ITool { + active: bool; + chart: IChart; + + mousedown(event): bool; + mousemove(event): bool; + clicked(p:IPoint): bool; + draw(): void; + } + + interface IGradient { + chart: IChart; + visible: bool; + + colors: string[]; + direction: string; + stops: number[]; + offset: IPoint; + } + + interface IShadow { + chart: IChart; + visible: bool; + blur:number; + color: string; + width:number; + height:number; + } + + interface IStroke { + chart: IChart; + fill: string; + size: number; + join: string; + cap: string; + dash: number[]; + gradient: IGradient; + } + + interface IFont { + chart: IChart; + style: string; + gradient: IGradient; + fill: string; + stroke: IStroke; + shadow: IShadow; + textAlign: string; + baseLine: string; + + getSize():number; + setSize(size:number):void; + } + + interface IImage { + url: string; + chart: IChart; + visible: bool; + } + + interface IFormat { + font: IFont; + gradient: IGradient; + shadow: IShadow; + stroke: IStroke; + round: IPoint; + transparency: number; + image: IImage; + fill: string; + + textHeight(text:string): number; + textWidth(text:string): number; + drawText(bounds:IRectangle, text:string); + rectangle(x:number, y:number, width:number, height:number); + poligon(points:IPoint[]); + ellipse(x:number, y:number, width:number, height:number); + } + + interface IMargins { + left: number; + top: number; + right: number; + bottom: number; + } + + interface IAnnotation extends ITool { + position: IPoint; + margins: IMargins; + items: IAnnotation[]; + bounds: IRectangle; + visible: bool; + transparent: bool; + text: string; + format: IFormat; + + add(text: string): IAnnotation; + resize(): void; + clicked(point: IPoint): bool; + draw(): void; + } + + interface IPanel { + format: IFormat; + transparent: bool; + margins: IMargins; + } + + interface ITitle extends IAnnotation { + expand: bool; + padding: number; + transparent: bool; + } + + interface IPalette { + colors: string[]; + + get(index: number): string; + } + + interface IArrow extends IFormat { + length: number; + underline: bool; + } + + interface IMarks extends IAnnotation { + arrow: IArrow; + series: ISeries; + + style: string; + + drawEvery: number; + visible: bool; + } + + interface ISeriesData { + values: number[]; + labels: string[]; + source: any; + } + + interface ICursor { + cursor: string; + } + + interface ISeries { + data: ISeriesData; + marks: IMarks; + + yMandatory: bool; + horizAxis: string; + vertAxis: string; + + format: IFormat; + hover: IFormat; + + visible: bool; + + cursor: ICursor; + over: number; + + palette: IPalette; + colorEach: string; + + useAxes: bool; + decimals: number; + + title: string; + + //refresh(failure: function): void; + + toPercent(index: number): string; + markText(index: number): string; + + valueText(index: number): string; + + associatedToAxis(axis: IAxis): bool; + + bounds(rectangle: IRectangle): void; + + calc(index: number, position: IPoint): void; + + clicked(position: IPoint): number; + + minXValue(): number; + maxXValue(): number; + + minYValue(): number; + maxYValue(): number; + + count(): number; + + addRandom(count: number, range?: number, x?: bool): ISeries; + + + } + + interface IAxisLabels { + chart: IChart; + format: IFormat; + decimals: number; + padding: number; + separation: number; // % + visible: bool; + rotation: number; + alternate: bool; + maxWidth: number; + + labelStyle: string; + dateFormat: string; + + getLabel(value: number): string; + width(value: number): number; + + } + + interface IGrid { + chart: IChart; + format: IFormat; + visible: bool; + lineDash: bool; + } + + interface ITicks { + chart: IChart; + stroke: IStroke; + visible: bool; + length: number; + } + + interface IMinorTicks extends ITicks { + count: number; + } + + interface IAxisTitle extends IAnnotation { + padding: number; + transparent: bool; + } + + interface IAxis { + chart: IChart; + visible: bool; + inverted: bool; + + horizontal: bool; // readonly + otherSize: bool; // readonly + bounds: IRectangle; // readonly? + + position: number; + format: IFormat; + custom: bool; // readonly + + grid: IGrid; + labels: IAxisLabels; + ticks: ITicks; + minorTicks: IMinorTicks; + innerTicks: ITicks; + + title: IAxisTitle; + + automatic: bool; + minimum: number; + maximum: number; + increment: number; + log: bool; + + startPos: number; + endPos: number; + + start: number; // % + end: number; // % + + axisSize: number; + + scale: number; + increm: number; + + calc(value: number): number; + fromPos(position: number): number; + fromSize(size: number): number; + + hasAnySeries(): bool; + scroll(delta: number): void; + setMinMax(minimum: number, maximum: number): void; + } + + interface IAxes { + chart: IChart; + visible: bool; + + left: IAxis; + top: IAxis; + right: IAxis; + bottom: IAxis; + + items: IAxis[]; + + add(horizontal: bool, otherSide: bool): IAxis; + //each(f: function): void; + } + + interface ISymbol { + chart: IChart; + format: IFormat; + width: number; + height: number; + padding: number; + visible: bool; + } + + interface ILegend { + chart: IChart; + + transparent: bool; + + format: IFormat; + title: IAnnotation; + + bounds: IRectangle; + position: string; + visible: bool; + inverted: bool; + padding: number; + align: number; + + fontColor: bool; + + dividing: IStroke; + over: number; + symbol: ISymbol; + + itemHeight: number; + innerOff: number; + + legendStyle: string; + textStyle: string; + + availRows(): number; + itemsCount(): number; + totalWidth(): number; + showValues(): bool; + itemText(series: ISeries, index: number): string; + isVertical(): bool; + } + + interface IScroll { + chart: IChart; + active: bool; + enabled: bool; + direction: string; + mouseButton: number; + + position: IPoint; + } + + interface ISeriesList { + chart: IChart; + items: ISeries[]; + + anyUsesAxes(): bool; + clicked(position: IPoint): bool; + //each(f: function): void; + firstVisible(): ISeries; + + } + + interface ITools { + chart: IChart; + items: ITool[]; + + add(tool: ITool): ITool; + } + + interface IWall { + format: IFormat; + visible: bool; + bounds: IRectangle; + } + + interface IWalls { + visible: bool; + left: IWall; + right: IWall; + bottom: IWall; + back: IWall; + } + + interface IZoom { + chart: IChart; + active: bool; + direction: string; + enabled: bool; + mouseButton: number; + format: IFormat; + + reset(): void; + } + + interface IChart { + addSeries(series:ISeries): ISeries; + draw(context?:CanvasRenderingContext2D); + } + + // SERIES + + interface ICustomBar extends ISeries { + sideMargins: number; + useOrigin: bool; + origin: number; + + offset: number; + barSize: number; + barStyle: string; + + stacked: string; + } + + interface ISeriesPointer { + chart: IChart; + format: IFormat; + visible: bool; + colorEach: bool; + style: string; + width: number; + height: number; + } + + interface ICustomSeries extends ISeries { + pointer: ISeriesPointer; + + stacked: string; + stairs: bool; + } + + interface ILine extends ICustomSeries { + smooth: number; + } + + interface ISmoothLine extends ILine { + smooth: number; + } + + interface IArea extends ISeries { + useOrigin: bool; + origin: number; + } + + interface IPie extends ISeries { + donut: number; + rotation: number; + sort: string; + orderAscending: bool; + explode: number[]; + concentric: bool; + + calcPos(angle: number, position: IPoint): void; + } + + interface IBubbleData extends ISeriesData { + radius: number[]; + } + + interface IBubble extends ICustomSeries { + data: IBubbleData; + } + + interface IGanttData extends ISeriesData { + start: number[]; + x: number[]; + end: number[]; + } + + interface IGantt extends ISeries { + data: IGanttData; + dateFormat: string; + colorEach: string; + height: number; + margin: IPoint; + + add(index: number, label: string, start: number, end: number): void; + bounds(index: number, rectangle: IRectangle): void; + } + + interface ICandleData extends ISeriesData { + open: number[]; + close: number[]; + high: number[]; + low: number[]; + } + + interface ICandle extends ICustomSeries { + data: ICandleData; + higher: IFormat; + lower: IFormat; + style: string; + } + + // TOOLS + + interface IDragTool extends ITool { + series: ISeries; + } + + interface ICursorTool extends ITool { + direction: string; + size: IPoint; + + followMouse: bool; + dragging: number; + + format: IFormat; + + horizAxis: IAxis; + vertAxis: IAxis; + + render: string; + + over(point: IPoint): bool; + setRender(render: string): void; + } + + interface IToolTip extends IAnnotation { + animated: number; + autoHide: bool; + autoRedraw: bool; + currentSeries: ISeries; + currentIndex: number; + delay: number; + + hide(): void; + refresh(series: ISeries, index: number): void; + } + + declare class Point implements IPoint { + public x:number; + public y:number; + } + + declare class Chart implements IChart { + //public aspect: IAspect; + + public axes: IAxes; + public footer: ITitle; + public legend: ILegend; + public panel: IPanel; + public scroll: IScroll; + public series: ISeriesList; + public title: ITitle; + public tools: ITools; + public walls: IWalls; + public zoom: IZoom; + + public bounds: IRectangle; + public canvas: HTMLCanvasElement; + public chartRect: IRectangle; + public palette: IPalette; + + constructor(canvas: string); + addSeries(series: ISeries): ISeries; + getSeries(index: number): ISeries; + removeSeries(series:ISeries): void; + + draw(context?:CanvasRenderingContext2D); + toImage(image: HTMLImageElement, format:string, quality:number): void; + } + + // SERIES + + declare var Line: { + prototype: ILine; + new(values?:number[]): ILine; + } + + declare var PointXY: { + prototype: ICustomSeries; + new(values?:number[]): ICustomSeries; + } + + declare var Area: { + prototype: IArea; + new(values?:number[]): IArea; + } + + declare var HorizArea: { + prototype: IArea; + new(values?:number[]): IArea; + } + + declare var Bar: { + prototype: ICustomBar; + new(values?:number[]): ICustomBar; + } + + declare var HorizBar: { + prototype: ICustomBar; + new(values?:number[]): ICustomBar; + } + + declare var Pie: { + prototype: IPie; + new(values?:number[]): IPie; + } + + declare var Donut: { + prototype: IPie; + new(values?:number[]): IPie; + } + + declare var Bubble: { + prototype: IBubble; + new(values?:number[]): IBubble; + } + + declare var Gantt: { + prototype: IGantt; + new(values?:number[]): IGantt; + } + + declare var Volume: { + prototype: ICustomBar; + new(values?:number[]): ICustomBar; + } + + declare var Candle: { + prototype: ICandle; + new(values?:number[]): ICandle; + } + + // TOOLS + + declare var CursorTool: { + prototype: ICursorTool; + new(chart?: Chart): ICursorTool; + } + + declare var DragTool: { + prototype: IDragTool; + new(chart?: Chart): IDragTool; + } + + declare var ToolTip: { + prototype: IToolTip; + new(chart?: Chart): IToolTip; + } +} diff --git a/README.md b/README.md index a7318226b..a12079134 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ Complete * [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall)) * [Sammy.js](http://sammyjs.org/) * [Spin](http://fgnass.github.com/spin.js/) +* [Teechart](http://www.steema.com) (by [Steema])(http://www.steema.com) * [Underscore.js](http://underscorejs.org/) Next From 57247534b628bac0ff04724fc70b81e18e7a6c99 Mon Sep 17 00:00:00 2001 From: Boris Yankov Date: Tue, 30 Oct 2012 14:24:05 +0200 Subject: [PATCH 040/107] Update jQuery UI definitions and tests --- Definitions/jqueryui-1.9.d.ts | 141 +++- Tests/jqueryui-tests.ts | 1201 +++++++++++++++++---------------- 2 files changed, 716 insertions(+), 626 deletions(-) diff --git a/Definitions/jqueryui-1.9.d.ts b/Definitions/jqueryui-1.9.d.ts index d8dd1d9e4..2d49a15e2 100644 --- a/Definitions/jqueryui-1.9.d.ts +++ b/Definitions/jqueryui-1.9.d.ts @@ -39,7 +39,7 @@ interface Accordion extends Widget { icons?: any; // Methods - + // Events activate(event: Event, ui): void; beforeActivate(event: Event, ui): void; @@ -61,7 +61,7 @@ interface Autocomplete extends Widget { source?: any; // [], string or () // Methods - close(); + close(); search(value?: string); // Events @@ -78,7 +78,7 @@ interface Autocomplete extends Widget { // Button ////////////////////////////////////////////////// -interface Button extends Widget { +interface Button extends Widget { // Options disabled?: bool; @@ -152,7 +152,7 @@ interface Datepicker extends Widget { // Methods destroy(); - dialog(date: any, onSelect?: () => void, settings?: any, pos?: any); + dialog(date: any, onSelect?: () => void , settings?: any, pos?: any); getDate(): Date; hide(): void; isDisabled(): bool; @@ -357,7 +357,7 @@ interface Menu extends Widget { blur(event: Event, ui): void; create(event: Event, ui): void; focus(event: Event, ui): void; - select(event: Event, ui): void; + select(event: Event, ui): void; } @@ -372,7 +372,7 @@ interface Progressbar extends Widget { // Methods destroy(); disable(); - enable(); + enable(); option(optionName: string): any; option(): any; option(optionName: string, value: any): void; @@ -414,7 +414,7 @@ interface Resizable extends Widget { minWidth?: number; // Methods - + // Events resize(event: Event, ui): void; start(event: Event, ui): void; @@ -436,7 +436,7 @@ interface Selectable extends Widget { tolerance?: string; // Methods - + // Events selected(event: Event, ui): void; selecting(event: Event, ui): void; @@ -452,7 +452,7 @@ interface Slider extends Widget { // Options animate?: any; // bool, string or number - disabled?: bool; + disabled?: bool; max?: number; min?: number; orientation?: string; @@ -471,8 +471,8 @@ interface Slider extends Widget { // Events change(event: Event, ui): void; - create(event: Event, ui): void; - slide(event: Event, ui): void; + create(event: Event, ui): void; + slide(event: Event, ui): void; start(event: Event, ui): void; stop(event: Event, ui): void; } @@ -615,47 +615,124 @@ interface Tooltip extends Widget { interface JQuery { - accordion(options?: Accordion): void; + accordion(): JQuery; + accordion(methodName: string): JQuery; + accordion(options: Dialog): JQuery; + accordion(optionLiteral: string, options: Dialog): JQuery; + accordion(optionLiteral: string, optionName: string, optionValue: any): JQuery; + accordion(optionLiteral: string, optionName: string): JQuery; - autocomplete(options?: Autocomplete): void; + autocomplete(): JQuery; + autocomplete(methodName: string): JQuery; + autocomplete(options: Autocomplete): JQuery; + autocomplete(optionLiteral: string, options: Autocomplete): JQuery; + autocomplete(optionLiteral: string, optionName: string, optionValue: any): JQuery; + autocomplete(optionLiteral: string, optionName: string): JQuery; - button(options?: Button): void; - buttonset(options?: Button): void; + button(): JQuery; + button(methodName: string): JQuery; + button(options: Button): JQuery; + button(optionLiteral: string, options: Button): JQuery; + button(optionLiteral: string, optionName: string, optionValue: any): JQuery; + button(optionLiteral: string, optionName: string): JQuery; - datepicker(options?: Datepicker): void; + buttonset(): JQuery; + buttonset(methodName: string): JQuery; + buttonset(options: Button): JQuery; + buttonset(optionLiteral: string, options: Button): JQuery; + buttonset(optionLiteral: string, optionName: string, optionValue: any): JQuery; + buttonset(optionLiteral: string, optionName: string): JQuery; - dialog(options?: Dialog): void; - dialog(optionLiteral: string): void; + datepicker(): JQuery; + datepicker(methodName: string): JQuery; + datepicker(options: Datepicker): JQuery; + datepicker(optionLiteral: string, options: Datepicker): JQuery; + datepicker(optionLiteral: string, optionName: string, optionValue: any): JQuery; + datepicker(optionLiteral: string, optionName: string): JQuery; - draggable(options?: Draggable): JQuery; + dialog(): JQuery; + dialog(methodName: string): JQuery; + dialog(options: Dialog): JQuery; + dialog(optionLiteral: string, options: Dialog): JQuery; + dialog(optionLiteral: string, optionName: string, optionValue: any): JQuery; + dialog(optionLiteral: string, optionName: string): JQuery; + + draggable(): JQuery; + draggable(methodName: string): JQuery; + draggable(options: Draggable): JQuery; draggable(optionLiteral: string, options: Draggable): JQuery; draggable(optionLiteral: string, optionName: string, optionValue: any): JQuery; - draggable(optionLiteral: string, optionName: string): any; - // draggable(methodName: string): any; + draggable(optionLiteral: string, optionName: string): JQuery; + droppable(): JQuery; + droppable(methodName: string): JQuery; droppable(options: Droppable): JQuery; droppable(optionLiteral: string, options: Draggable): JQuery; droppable(optionLiteral: string, optionName: string, optionValue: any): JQuery; - droppable(optionLiteral: string, optionName: string): any; - droppable(methodName: string): any; + droppable(optionLiteral: string, optionName: string): JQuery; - menu(options?: Menu): void; + menu(): JQuery; + menu(methodName: string): JQuery; + menu(options: Menu): JQuery; + menu(optionLiteral: string, options: Menu): JQuery; + menu(optionLiteral: string, optionName: string, optionValue: any): JQuery; + menu(optionLiteral: string, optionName: string): JQuery; - progressbar(options?: Progressbar): void; + progressbar(): JQuery; + progressbar(methodName: string): JQuery; + progressbar(options: Progressbar): JQuery; + progressbar(optionLiteral: string, options: Progressbar): JQuery; + progressbar(optionLiteral: string, optionName: string, optionValue: any): JQuery; + progressbar(optionLiteral: string, optionName: string): JQuery; - resizable(options?: Resizable): void; + resizable(): JQuery; + resizable(methodName: string): JQuery; + resizable(options: Resizable): JQuery; + resizable(optionLiteral: string, options: Resizable): JQuery; + resizable(optionLiteral: string, optionName: string, optionValue: any): JQuery; + resizable(optionLiteral: string, optionName: string): JQuery; - selectable(options?: Selectable): void; + selectable(): JQuery; + selectable(methodName: string): JQuery; + selectable(options: Selectable): JQuery; + selectable(optionLiteral: string, options: Selectable): JQuery; + selectable(optionLiteral: string, optionName: string, optionValue: any): JQuery; + selectable(optionLiteral: string, optionName: string): JQuery; - slider(options?: Slider): void; + slider(): JQuery; + slider(methodName: string): JQuery; + slider(options: Slider): JQuery; + slider(optionLiteral: string, options: Slider): JQuery; + slider(optionLiteral: string, optionName: string, optionValue: any): JQuery; + slider(optionLiteral: string, optionName: string): JQuery; - sortable(options?: Sortable): void; + sortable(): JQuery; + sortable(methodName: string): JQuery; + sortable(options: Sortable): JQuery; + sortable(optionLiteral: string, options: Sortable): JQuery; + sortable(optionLiteral: string, optionName: string, optionValue: any): JQuery; + sortable(optionLiteral: string, optionName: string): JQuery; - spinner(options?: Spinner): void; + spinner(): JQuery; + spinner(methodName: string): JQuery; + spinner(options: Spinner): JQuery; + spinner(optionLiteral: string, options: Spinner): JQuery; + spinner(optionLiteral: string, optionName: string, optionValue: any): JQuery; + spinner(optionLiteral: string, optionName: string): JQuery; - tabs(options?: Tabs): void; + tabs(): JQuery; + tabs(methodName: string): JQuery; + tabs(options: Tabs): JQuery; + tabs(optionLiteral: string, options: Tabs): JQuery; + tabs(optionLiteral: string, optionName: string, optionValue: any): JQuery; + tabs(optionLiteral: string, optionName: string): JQuery; - tooltip(options?: Tooltip): void; + tooltip(): JQuery; + tooltip(methodName: string): JQuery; + tooltip(options: Tooltip): JQuery; + tooltip(optionLiteral: string, options: Tooltip): JQuery; + tooltip(optionLiteral: string, optionName: string, optionValue: any): JQuery; + tooltip(optionLiteral: string, optionName: string): JQuery; } interface JQueryStatic { diff --git a/Tests/jqueryui-tests.ts b/Tests/jqueryui-tests.ts index 896b0f7a4..7ef12853a 100644 --- a/Tests/jqueryui-tests.ts +++ b/Tests/jqueryui-tests.ts @@ -2,440 +2,449 @@ declare var $: any; +function tests_draggable() { -// Draggable ////////////////////////////////////////////////// - -$("#draggable").draggable({ axis: "y" }); -$("#draggable2").draggable({ axis: "x" }); -$("#draggable3").draggable({ containment: "#containment-wrapper", scroll: false }); -$("#draggable5").draggable({ containment: "parent" }); -$("#draggable").draggable({ cursor: "move", cursorAt: { top: 56, left: 56 } }); -$("#draggable2").draggable({ cursor: "crosshair", cursorAt: { top: -5, left: -5 } }); -$("#draggable3").draggable({ cursorAt: { bottom: 0 } }); -$("#draggable").draggable(); -$("#draggable").draggable({ distance: 20 }); -$("#draggable2").draggable({ delay: 1000 }); -$("#draggable").draggable({ - start: () => { }, - drag: () => { }, - stop: () => { } -}); -$("#draggable").draggable({ handle: "p" }); -$("#draggable2").draggable({ cancel: "p.ui-widget-header" }); -$("#draggable").draggable({ revert: true }); -$("#draggable2").draggable({ revert: true, helper: "clone" }); -$("#draggable").draggable({ scroll: true }); -$("#draggable2").draggable({ scroll: true, scrollSensitivity: 100 }); -$("#draggable3").draggable({ scroll: true, scrollSpeed: 100 }); -$("#draggable").draggable({ snap: true }); -$("#draggable2").draggable({ snap: ".ui-widget-header" }); -$("#draggable3").draggable({ snap: ".ui-widget-header", snapMode: "outer" }); -$("#draggable4").draggable({ grid: [20, 20] }); -$("#draggable5").draggable({ grid: [80, 80] }); -$("#sortable").sortable({ revert: true }); -$("#draggable").draggable({ - connectToSortable: "#sortable", - helper: "clone", - revert: "invalid" -}); -$("#draggable").draggable({ helper: "original" }); -$("#draggable2").draggable({ opacity: 0.7, helper: "clone" }); -$("#draggable3").draggable({ - cursor: "move", - cursorAt: { top: -12, left: -20 }, - helper: (event) => { return $("
    I'm a custom helper
    "); } -}); -$("#set div").draggable({ stack: "#set div" }); - - -// Droppable ////////////////////////////////////////////////// - -$( "#draggable, #draggable-nonvalid" ).draggable(); -$("#droppable").droppable({ - accept: "#draggable", - activeClass: "ui-state-hover", - hoverClass: "ui-state-active", - drop: (event, ui) => { - $(this) - .addClass("ui-state-highlight") - .find("p") - .html("Dropped!"); - } -}); -$( "#draggable" ).draggable(); -$("#droppable").droppable({ - drop: (event, ui) => { - $(this) - .addClass("ui-state-highlight") - .find("p") - .html("Dropped!"); - } -}); - -var $gallery = $( "#gallery" ), - $trash = $( "#trash" ); -$("li", $gallery).draggable({ - cancel: "a.ui-icon", - revert: "invalid", - containment: "document", - helper: "clone", - cursor: "move" -}); - -$trash.droppable({ - accept: "#gallery > li", - activeClass: "ui-state-highlight", - drop: ( event, ui ) => { } -}); - -$gallery.droppable({ - accept: "#trash li", - activeClass: "custom-state-active", - drop: ( event, ui ) => { } -}); - -var recycle_icon = "Recycle image"; -function deleteImage($item) { - $item.fadeOut(() => { - var $list = $("ul", $trash).length ? - $("ul", $trash) : - $("