diff --git a/types/angular-gettext/index.d.ts b/types/angular-gettext/index.d.ts index 107d9e10e2..5b6eb1d90f 100644 --- a/types/angular-gettext/index.d.ts +++ b/types/angular-gettext/index.d.ts @@ -9,6 +9,7 @@ import * as angular from 'angular'; +export type gettextCatalog = angular.gettext.gettextCatalog; declare module 'angular' { export namespace gettext { diff --git a/types/angular-local-storage/index.d.ts b/types/angular-local-storage/index.d.ts index 76ab65b1b5..6e8c64416a 100644 --- a/types/angular-local-storage/index.d.ts +++ b/types/angular-local-storage/index.d.ts @@ -8,6 +8,10 @@ import * as angular from 'angular'; +export type ILocalStorageServiceProvider = angular.local.storage.ILocalStorageServiceProvider; +export type ILocalStorageService = angular.local.storage.ILocalStorageService; +export type ICookie = angular.local.storage.ICookie; + declare module 'angular' { export namespace local.storage { interface ILocalStorageServiceProvider extends angular.IServiceProvider { diff --git a/types/angular-translate/index.d.ts b/types/angular-translate/index.d.ts index 719fcb5d5c..f35fb57570 100644 --- a/types/angular-translate/index.d.ts +++ b/types/angular-translate/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Translate (pascalprecht.translate module) 2.15 +// Type definitions for Angular Translate (pascalprecht.translate module) 2.16 // Project: https://github.com/PascalPrecht/angular-translate // Definitions by: Michel Salib , Gabriel Gil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -47,8 +47,8 @@ declare module 'angular' { } interface ITranslateService { - (translationId: string, interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string): angular.IPromise; - (translationId: string[], interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string): angular.IPromise<{ [key: string]: string }>; + (translationId: string, interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string, sanitizeStrategy?: string): angular.IPromise; + (translationId: string[], interpolateParams?: any, interpolationId?: string, defaultTranslationText?: string, forceLanguage?: string, sanitizeStrategy?: string): angular.IPromise<{ [key: string]: string }>; cloakClassName(): string; cloakClassName(name: string): ITranslateProvider; fallbackLanguage(langKey?: string): string; diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 89e897a7ad..6b82a2bcb4 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -4,6 +4,7 @@ // Georgii Dolzhykov // Caleb St-Denis // Leonard Thieu +// Steffen Kowalski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -484,6 +485,76 @@ declare namespace angular { $broadcast(name: string, ...args: any[]): IAngularEvent; $destroy(): void; $digest(): void; + + /** + * Suspend watchers of this scope subtree so that they will not be invoked during digest. + * + * This can be used to optimize your application when you know that running those watchers + * is redundant. + * + * **Warning** + * + * Suspending scopes from the digest cycle can have unwanted and difficult to debug results. + * Only use this approach if you are confident that you know what you are doing and have + * ample tests to ensure that bindings get updated as you expect. + * + * Some of the things to consider are: + * + * * Any external event on a directive/component will not trigger a digest while the hosting + * scope is suspended - even if the event handler calls `$apply()` or `$rootScope.$digest()`. + * * Transcluded content exists on a scope that inherits from outside a directive but exists + * as a child of the directive's containing scope. If the containing scope is suspended the + * transcluded scope will also be suspended, even if the scope from which the transcluded + * scope inherits is not suspended. + * * Multiple directives trying to manage the suspended status of a scope can confuse each other: + * * A call to `$suspend()` on an already suspended scope is a no-op. + * * A call to `$resume()` on a non-suspended scope is a no-op. + * * If two directives suspend a scope, then one of them resumes the scope, the scope will no + * longer be suspended. This could result in the other directive believing a scope to be + * suspended when it is not. + * * If a parent scope is suspended then all its descendants will be also excluded from future + * digests whether or not they have been suspended themselves. Note that this also applies to + * isolate child scopes. + * * Calling `$digest()` directly on a descendant of a suspended scope will still run the watchers + * for that scope and its descendants. When digesting we only check whether the current scope is + * locally suspended, rather than checking whether it has a suspended ancestor. + * * Calling `$resume()` on a scope that has a suspended ancestor will not cause the scope to be + * included in future digests until all its ancestors have been resumed. + * * Resolved promises, e.g. from explicit `$q` deferreds and `$http` calls, trigger `$apply()` + * against the `$rootScope` and so will still trigger a global digest even if the promise was + * initiated by a component that lives on a suspended scope. + */ + $suspend(): void; + + /** + * Call this method to determine if this scope has been explicitly suspended. It will not + * tell you whether an ancestor has been suspended. + * To determine if this scope will be excluded from a digest triggered at the $rootScope, + * for example, you must check all its ancestors: + * + * ``` + * function isExcludedFromDigest(scope) { + * while(scope) { + * if (scope.$isSuspended()) return true; + * scope = scope.$parent; + * } + * return false; + * ``` + * + * Be aware that a scope may not be included in digests if it has a suspended ancestor, + * even if `$isSuspended()` returns false. + * + * @returns true if the current scope has been suspended. + */ + $isSuspended(): boolean; + + /** + * Resume watchers of this scope subtree in case it was suspended. + * + * See {$rootScope.Scope#$suspend} for information about the dangers of using this approach. + */ + $resume(): void; + /** * Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners. * diff --git a/types/auth0-lock/auth0-lock-tests.ts b/types/auth0-lock/auth0-lock-tests.ts index 0c64fd361b..fc070f62df 100644 --- a/types/auth0-lock/auth0-lock-tests.ts +++ b/types/auth0-lock/auth0-lock-tests.ts @@ -39,7 +39,10 @@ const showOptions : Auth0LockShowOptions = { type: "error", text: "an error has occurred" }, - rememberLastLogin: false + rememberLastLogin: false, + languageDictionary: { + title: "test" + } }; lock.show(showOptions); diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index 27639834db..7dc20ae176 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -161,6 +161,7 @@ interface Auth0LockShowOptions { initialScreen?: "login" | "signUp" | "forgotPassword"; flashMessage?: Auth0LockFlashMessageOptions; rememberLastLogin?: boolean; + languageDictionary?: any; } interface AuthResult { diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index aa82e908e5..be87ceed2c 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -350,6 +350,7 @@ export interface Identity { user_id: string; provider: string; isSocial: boolean; + access_token?: string; profileData?: { email?: string; email_verified?: boolean; @@ -882,4 +883,4 @@ export class UsersManager { impersonate(userId: string, settings: ImpersonateSettingOptions): Promise; impersonate(userId: string, settings: ImpersonateSettingOptions, cb: (err: Error, data: any) => void): void; -} \ No newline at end of file +} diff --git a/types/browser-sync/browser-sync-tests.ts b/types/browser-sync/browser-sync-tests.ts index c63cb0c862..1c7e7e5996 100644 --- a/types/browser-sync/browser-sync-tests.ts +++ b/types/browser-sync/browser-sync-tests.ts @@ -1,4 +1,5 @@ import browserSync = require("browser-sync"); +import { EventEmitter } from "events"; (() => { //make sure that the interfaces are correctly exposed @@ -391,6 +392,57 @@ bs.init({ bs.reload(); +browserSync.use( + { + plugin: function(opts: object, bs: browserSync.BrowserSyncInstance) { + console.log(opts); + }, + "plugin:name": "test" + }, + { files: "*.css" } +); + +browserSync.use({ + plugin: function(opts: object, bs: browserSync.BrowserSyncInstance) { + console.log(bs.name); + } +}); + +browserSync( + { + server: { + baseDir: "test/fixtures" + }, + logLevel: "silent", + open: false + } +); + +var instanceName = "TestInstance"; +var namedInstance = browserSync.create(instanceName); +namedInstance.init({ + server: { index: "./app" }, + https: true +}); + +console.log(namedInstance.getOption("https")); // Should output true. + +var existingInstance = browserSync.get(instanceName); + +browserSync.create("InstanceWithEventEmitter", new EventEmitter()); + +// Should output something greater than 0. +console.log(browserSync.instances.length); + +browserSync.reset(); + +// Should output 0. +console.log(browserSync.instances.length); + +var cleanupTestInstance = browserSync.create("CleanupTest"); +cleanupTestInstance.cleanup(); +console.log(cleanupTestInstance.active); // Should output false. + function browserSyncInit(): browserSync.BrowserSyncInstance { var browser = browserSync.create(); browser.init(); diff --git a/types/browser-sync/index.d.ts b/types/browser-sync/index.d.ts index de0a457266..bcf0aa966e 100644 --- a/types/browser-sync/index.d.ts +++ b/types/browser-sync/index.d.ts @@ -456,11 +456,15 @@ declare namespace browserSync { * depending on your use-case. */ (config?: Options, callback?: (err: Error, bs: object) => any): BrowserSyncInstance; + /** + * + */ + instances: Array; /** * Create a Browsersync instance * @param name an identifier that can used for retrieval later */ - create(name?: string): BrowserSyncInstance; + create(name?: string, emitter?: NodeJS.EventEmitter): BrowserSyncInstance; /** * Get a single instance by name. This is useful if you have your build scripts in separate files * @param name the identifier used for retrieval @@ -471,6 +475,11 @@ declare namespace browserSync { * @param name the name of the instance */ has(name: string): boolean; + /** + * Reset the state of the module. + * (should only be needed for test environments) + */ + reset(): void; } interface BrowserSyncInstance { @@ -481,6 +490,24 @@ declare namespace browserSync { * depending on your use-case. */ init(config?: Options, callback?: (err: Error, bs: object) => any): BrowserSyncInstance; + /** + * This method will close any running server, stop file watching & exit the current process. + */ + exit(): void; + /** + * Helper method for browser notifications + * @param message Can be a simple message such as 'Connected' or HTML + * @param timeout How long the message will remain in the browser. @since 1.3.0 + */ + notify(message: string, timeout?: number): void; + /** + * Method to pause file change events + */ + pause(): void; + /** + * Method to resume paused watchers + */ + resume(): void; /** * Reload the browser * The reload method will inform all browsers about changed files and will either cause the browser @@ -510,28 +537,30 @@ declare namespace browserSync { */ stream(opts?: StreamOptions): NodeJS.ReadWriteStream; /** - * Helper method for browser notifications - * @param message Can be a simple message such as 'Connected' or HTML - * @param timeout How long the message will remain in the browser. @since 1.3.0 + * Instance Cleanup. */ - notify(message: string, timeout?: number): void; + cleanup(fn?: (error: NodeJS.ErrnoException, bs: BrowserSyncInstance) => void): void; /** - * This method will close any running server, stop file watching & exit the current process. + * Register a plugin. + * Must implement at least a 'plugin' property that returns + * callable function. + * + * @method use + * @param {object} module The object to be `required`. + * @param {object} options The + * @param {any} cb A callback function that will return any errors. */ - exit(): void; + use(module: { "plugin:name"?: string, plugin: (opts: object, bs: BrowserSyncInstance) => any }, options?: object, cb?: any): void; + /** + * Callback helper to examine what options have been set. + * @param {string} name The key to search options map for. + */ + getOption(name: string): any; /** * Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system */ watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any) : NodeJS.EventEmitter; - /** - * Method to pause file change events - */ - pause(): void; - /** - * Method to resume paused watchers - */ - resume(): void; /** * The internal Event Emitter used by the running Browsersync instance (if there is one). You can use * this to emit your own events, such as changed files, logging etc. diff --git a/types/buffer-reader/buffer-reader-tests.ts b/types/buffer-reader/buffer-reader-tests.ts new file mode 100644 index 0000000000..9868131c93 --- /dev/null +++ b/types/buffer-reader/buffer-reader-tests.ts @@ -0,0 +1,28 @@ +import BufferReader from 'buffer-reader'; + +const buffer = new Buffer(1000); +const reader = new BufferReader(buffer); +reader.append(new Buffer(1)); +reader.tell(); +reader.seek(1); +reader.move(2); +reader.restAll(); +reader.nextBuffer(2); +reader.nextString(5); +reader.nextString(5, 'utf8'); +reader.nextStringZero(); +reader.nextStringZero('utf8'); +reader.nextInt8(); +reader.nextUInt8(); +reader.nextInt16LE(); +reader.nextUInt16LE(); +reader.nextInt16BE(); +reader.nextUInt16BE(); +reader.nextInt32LE(); +reader.nextUInt32LE(); +reader.nextInt32BE(); +reader.nextUInt32BE(); +reader.nextFloatLE(); +reader.nextFloatBE(); +reader.nextDouble32LE(); +reader.nextDouble32BE(); diff --git a/types/buffer-reader/index.d.ts b/types/buffer-reader/index.d.ts new file mode 100644 index 0000000000..e83f081e69 --- /dev/null +++ b/types/buffer-reader/index.d.ts @@ -0,0 +1,111 @@ +// Type definitions for buffer-reader 0.1 +// Project: https://github.com/villadora/node-buffer-reader +// Definitions by: nrlquaker +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +/// + +export = BufferReader; + +declare class BufferReader { + /** + * Create a new reader, if no buffer provided, a empty buffer will be used. + */ + constructor(buffer?: Buffer) + /** + * Append new buffer to the end of current reader. + * @param buffer buffer to append + */ + append(buffer: Buffer): void; + /** + * Return current position of the reader. + */ + tell(): number; + /** + * Set new position of the reader, if the pos is invalid, an exception will be raised. + * @param position new position + */ + seek(position: number): void; + /** + * Move the position of reader by offset, offset can be negative; it can be used to skip some bytes. + * @param offset offset to move by + */ + move(offset: number): void; + /** + * Get all the remaining bytes as a Buffer. + */ + restAll(): Buffer; + /** + * Read a buffer with specified length. + * @param length specified length + */ + nextBuffer(length: number): Buffer; + /** + * Read next length of bytes as String, encoding default is 'utf8'. + * @param length length of the string to read + * @param encoding encoding of the string + */ + nextString(length: number, encoding?: string): string; + /** + * Read next bytes till the end of buffer as null-terminated string, encoding default is 'utf8'. + * @param encoding encoding of the string + */ + nextStringZero(encoding?: string): string; + /** + * Read next bytes as Int8, the value is just as the same format Buffer in nodejs doc. + */ + nextInt8(): number; + /** + * Read next bytes as UInt8, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt8(): number; + /** + * Read next bytes as Int16LE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt16LE(): number; + /** + * Read next bytes as UInt16LE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt16LE(): number; + /** + * Read next bytes as Int16BE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt16BE(): number; + /** + * Read next bytes as UInt16BE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt16BE(): number; + /** + * Read next bytes as Int32LE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt32LE(): number; + /** + * Read next bytes as UInt32LE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt32LE(): number; + /** + * Read next bytes as Int32BE, the value is just as the same format Buffer in nodejs doc. + */ + nextInt32BE(): number; + /** + * Read next bytes as UInt32BE, the value is just as the same format Buffer in nodejs doc. + */ + nextUInt32BE(): number; + /** + * Read next bytes as FloatLE, the value is just as the same format Buffer in nodejs doc. + */ + nextFloatLE(): number; + /** + * Read next bytes as FloatBE, the value is just as the same format Buffer in nodejs doc. + */ + nextFloatBE(): number; + /** + * Read next bytes as Double32LE, the value is just as the same format Buffer in nodejs doc. + */ + nextDouble32LE(): number; + /** + * Read next bytes as Double32BE, the value is just as the same format Buffer in nodejs doc. + */ + nextDouble32BE(): number; +} diff --git a/types/buffer-reader/tsconfig.json b/types/buffer-reader/tsconfig.json new file mode 100644 index 0000000000..da70d80fe1 --- /dev/null +++ b/types/buffer-reader/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "esModuleInterop": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "buffer-reader-tests.ts" + ] +} diff --git a/types/buffer-reader/tslint.json b/types/buffer-reader/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/buffer-reader/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai/chai-tests.ts b/types/chai/chai-tests.ts index f19514fe71..2c81c42aeb 100644 --- a/types/chai/chai-tests.ts +++ b/types/chai/chai-tests.ts @@ -1361,6 +1361,39 @@ suite('assert', () => { assert.notDeepEqual(circularObject, secondCircularObject); }); + test('deepStrictEqual', () => { + assert.deepStrictEqual({tea: 'chai'}, {tea: 'chai'}); + assert.throws(() => assert.deepStrictEqual({tea: 'chai'}, {tea: 'black'})); + + const obja = Object.create({tea: 'chai'}); + const objb = Object.create({tea: 'chai'}); + + assert.deepStrictEqual(obja, objb); + + const obj1 = Object.create({tea: 'chai'}); + const obj2 = Object.create({tea: 'black'}); + + assert.throws(() => assert.deepStrictEqual(obj1, obj2)); + }); + + test('deepStrictEqual (ordering)', () => { + const a = {a: 'b', c: 'd'}; + const b = {c: 'd', a: 'b'}; + assert.deepStrictEqual(a, b); + }); + + test('deepStrictEqual (circular)', () => { + const circularObject: any = {}; + const secondCircularObject: any = {}; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.deepStrictEqual(circularObject, secondCircularObject); + + secondCircularObject.field2 = secondCircularObject; + assert.deepStrictEqual(circularObject, secondCircularObject); + }); + test('isNull', () => { assert.isNull(null); assert.isNull(undefined); diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index d0f5ab099c..d260973b71 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -353,7 +353,7 @@ declare namespace Chai { notStrictEqual(actual: T, expected: T, message?: string): void; /** - * Asserts that actual is deeply equal to expected. + * Asserts that actual is deeply equal (==) to expected. * * @type T Type of the objects. * @param actual Actual value. @@ -363,7 +363,7 @@ declare namespace Chai { deepEqual(actual: T, expected: T, message?: string): void; /** - * Asserts that actual is not deeply equal to expected. + * Asserts that actual is not deeply equal (==) to expected. * * @type T Type of the objects. * @param actual Actual value. @@ -372,6 +372,16 @@ declare namespace Chai { */ notDeepEqual(actual: T, expected: T, message?: string): void; + /** + * Asserts that actual is deeply strict equal (===) to expected. + * + * @type T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + deepStrictEqual(actual: T, expected: T, message?: string): void; + /** * Asserts valueToCheck is strictly greater than (>) valueToBeAbove. * diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index cb3db72855..8063cf2629 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -506,6 +506,7 @@ declare namespace Chart { } interface CommonAxe { + bounds?: string; type?: ScaleType | string; display?: boolean; id?: string; diff --git a/types/chromecast-caf-receiver/cast.framework.events.d.ts b/types/chromecast-caf-receiver/cast.framework.events.d.ts index 0c69727a05..03b70ca459 100644 --- a/types/chromecast-caf-receiver/cast.framework.events.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.events.d.ts @@ -367,9 +367,15 @@ declare namespace cast.framework.events { total?: number, whenSkippable?: number, endedReason?: EndedReason, - breakClipId?: string + breakClipId?: string, + breakId?: string ); + /** + * The break's id. Refer to Break.id + */ + breakId?: string; + /** * The break clip's id. Refer to BreakClip.id */ diff --git a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts index a75834b0a8..08ce57cf86 100644 --- a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts +++ b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts @@ -8,7 +8,8 @@ import { } from "chromecast-caf-receiver/cast.framework.system"; import { RequestEvent, - Event + Event, + BreaksEvent } from "chromecast-caf-receiver/cast.framework.events"; import { QueueBase, @@ -29,12 +30,16 @@ import { MediaMetadata } from "chromecast-caf-receiver/cast.framework.messages"; +const breaksEvent = new BreaksEvent('BREAK_STARTED'); +breaksEvent.breakId = 'some-break-id'; +breaksEvent.breakClipId = 'some-break-clip-id'; + const track = new Track(1, "TEXT"); const breakClip = new BreakClip("id"); const adBreak = new Break("id", ["id"], 1); const rEvent = new RequestEvent("BITRATE_CHANGED", { requestId: 2 }); const pManager = new PlayerManager(); -pManager.addEventListener("STALLED", () => {}); +pManager.addEventListener("STALLED", () => { }); const ttManager = new TextTracksManager(); const qManager = new QueueManager(); const qBase = new QueueBase(); @@ -47,10 +52,10 @@ const breakManager: BreakManager = { getBreakClips: () => [breakClip], getBreaks: () => [adBreak], getPlayWatchedBreak: () => true, - setBreakClipLoadInterceptor: () => {}, - setBreakSeekInterceptor: () => {}, - setPlayWatchedBreak: () => {}, - setVastTrackingInterceptor: () => {} + setBreakClipLoadInterceptor: () => { }, + setBreakSeekInterceptor: () => { }, + setPlayWatchedBreak: () => { }, + setVastTrackingInterceptor: () => { } }; const lrd: LoadRequestData = { @@ -103,4 +108,4 @@ const pData: PlayerData = { whenSkippable: 321 }; const binder = new PlayerDataBinder(pData); -binder.addEventListener("ANY_CHANGE", e => {}); +binder.addEventListener("ANY_CHANGE", e => { }); diff --git a/types/cytoscape/cytoscape-tests.ts b/types/cytoscape/cytoscape-tests.ts index 25d6151259..39be1cd0e7 100644 --- a/types/cytoscape/cytoscape-tests.ts +++ b/types/cytoscape/cytoscape-tests.ts @@ -1,6 +1,26 @@ 'use strict'; -import cytoscape = require('cytoscape'); +// TODO: document all aliases as aliases, not as duplicates! + +const assert = (tag: boolean) => { if (!tag) throw new Error(); }; +const aliases = (...obj: Array<{}>) => { if (obj.slice(1).some((alias) => alias !== obj[0])) throw new Error(); }; +const events = (obj: any) => { + aliases(obj.on, obj.bind, obj.listen, obj.addListener); + aliases(obj.promiseOn, obj.pon); + aliases(obj.off, obj.unbind, obj.unlisten, obj.removeListener); + aliases(obj.emit, obj.trigger); +}; + +// definitions +function oneOf(a: A, b: B, c: C, d: D, e: E): A | B | C | D | E; +function oneOf(a: A, b: B, c: C, d: D): A | B | C | D; +function oneOf(a: A, b: B, c: C): A | B | C; +function oneOf(a: A, b: B): A | B; +function oneOf(...array: T[]): T { + return array[0]; +} + +import cytoscape = require('cytoscape'); const parentCSS = { 'padding-top': '10px', 'padding-left': '10px', @@ -69,6 +89,34 @@ const cy = cytoscape({ ] }, + // initial viewport state: + zoom: 1, + pan: { x: 0, y: 0 }, + + // interaction options: + minZoom: 1e-50, + maxZoom: 1e50, + zoomingEnabled: true, + userZoomingEnabled: true, + panningEnabled: true, + userPanningEnabled: true, + selectionType: 'single', + touchTapThreshold: 8, + desktopTapThreshold: 4, + autolock: false, + autoungrabify: false, + + // rendering options: + headless: false, + styleEnabled: true, + hideEdgesOnViewport: false, + hideLabelsOnViewport: false, + textureOnViewport: false, + motionBlur: false, + motionBlurOpacity: 0.2, + wheelSensitivity: 1, + pixelRatio: 'auto', + layout: { name: 'preset', padding: 5 @@ -80,6 +128,42 @@ cy.on('zoom', (event) => { cy.nodes('$node > node').style('opacity', 0); } }); +cy.off('zoom'); +events(cy); + +cy.add({ data: { id: 'g' }, position: {x: 200, y: 150} }); +cy.add([ + { data: { id: 'h' }, position: {x: 250, y: 100} } +]); +const nodesBeforeDelete = cy.nodes(); +const edgesBeforeDelete = cy.edges(); + +const removed = cy.remove('#g #h'); +cy.add(removed); +const diffNodes = nodesBeforeDelete.diff(cy.nodes()); +const diffEdges = edgesBeforeDelete.diff(cy.edges()); +assert(diffNodes.left.size() === 0 && diffNodes.right.size() === 0 && diffNodes.both.size() === cy.nodes().size()); +assert(nodesBeforeDelete.same(cy.nodes())); +assert(edgesBeforeDelete.same(cy.edges())); + +const gh = cy.collection().add(cy.$id('g')).union(cy.getElementById('h')); +const gh2 = cy.$('#g #h'); +const gh3 = cy.nodes('#g #h'); +assert(gh2.same(gh)); +assert(gh3.same(gh)); +assert(gh.same(removed)); + +assert(cy.container() === null); // headless mode! + +cy.center(); +cy.center(gh); +aliases(cy.center, cy.centre); + +cy.fit(cy.$('#a #b #h')); + +const {x1, y1, x2, y2, w, h} = cy.extent(); + +aliases(cy.resize, cy.invalidateDimensions); cy.animate({ fit: { @@ -89,8 +173,323 @@ cy.animate({ duration: 500 }); -const node = cy.nodes()[0]; cy.animate({ - center: {eles: node}, + center: {eles: cy.nodes()[0]}, duration: 500 }); + +const anim = cy.animation({ + zoom: { + level: 1, + position: {x: 0, y: 0} + }, + pan: {x: 100, y: 100}, + duration: 100, + easing: 'ease' +}); +cy.stop(true, true); +anim.play(); +assert(anim.playing()); +anim.progress(anim.progress() + 50); +anim.time(anim.time() - 50); +anim.stop(); + +aliases(cy.layout, cy.createLayout, cy.makeLayout); + +// Preconfigured data for layouts (as it could be passed) +const boundingBox = oneOf({x1: 0, x2: 100, y1: 0, y2: 100}, {x1: 0, w: 100, y1: 0, h: 100}); +const positions = oneOf({a: {x: 100, y: 100}}, (node: cytoscape.NodeCollection): cytoscape.Position => ({x: 100, y: 100})); + +// TODO: uncomment after we have the way to add layout options properties from extensions +// const layouts = [ +// cy.layout({ +// name: 'null', +// ready: () => {}, +// stop: () => {} +// }), +// cy.layout({ +// name: 'random', +// fit: true, +// padding: 30, +// boundingBox, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'preset', +// positions, +// zoom: 1, +// pan: {x: 100, y: 100}, +// fit: false, +// padding: 30, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-out', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'grid', +// fit: true, +// padding: 30, +// boundingBox, +// avoidOverlap: true, +// avoidOverlapPadding: 10, +// nodeDimensionsIncludeLabels: false, +// spacingFactor: oneOf(1, undefined), +// condense: false, +// rows: oneOf(10, undefined), +// cols: oneOf(10, undefined), +// position: (node) => ({ row: 1, col: 1 }), +// sort: (a, b) => 1, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in-out', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'circle', +// fit: true, +// padding: 30, +// boundingBox, +// avoidOverlap: true, +// nodeDimensionsIncludeLabels: false, +// spacingFactor: oneOf(1, undefined), +// radius: oneOf(1, undefined), +// startAngle: 3 / 2 * Math.PI, +// sweep: oneOf(6, undefined), +// clockwise: true, +// sort: (a, b) => 1, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in-sine', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'concentric', +// fit: true, +// padding: 30, +// startAngle: 3 / 2 * Math.PI, +// sweep: oneOf(6, undefined), +// clockwise: true, +// equidistant: false, +// minNodeSpacing: 10, +// boundingBox, +// avoidOverlap: true, +// nodeDimensionsIncludeLabels: false, +// height: oneOf(500, undefined), +// width: oneOf(500, undefined), +// spacingFactor: oneOf(1, undefined), +// concentric: (node) => 1, +// levelWidth: (nodes) => 1, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-out-sine', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'breadthfirst', +// fit: true, +// directed: false, +// padding: 30, +// circle: false, +// spacingFactor: 1.75, +// boundingBox, +// avoidOverlap: true, +// nodeDimensionsIncludeLabels: false, +// maximalAdjustments: 0, +// animate: false, +// animationDuration: 500, +// animationEasing: 'ease-in-out-sine', +// animateFilter: (node, i) => true, +// transform: (node, position) => position +// }), +// cy.layout({ +// name: 'cose', +// ready: () => {}, +// stop: () => {}, +// animate: oneOf(true, false, 'end'), +// animationEasing: oneOf('ease-in-quad', undefined), +// animationDuration: oneOf(500, undefined), +// animateFilter: function ( node, i ){ return true; }, +// animationThreshold: 250, +// refresh: 20, +// fit: true, +// padding: 30, +// boundingBox: undefined, +// nodeDimensionsIncludeLabels: false, +// randomize: false, +// componentSpacing: 40, +// nodeRepulsion: (node) => 2048, +// nodeOverlap: 4, +// idealEdgeLength: (edge) => 32, +// edgeElasticity: (edge) => 32, +// nestingFactor: 1.2, +// gravity: 1, +// numIter: 1000, +// initialTemp: 1000, +// coolingFactor: 0.99, +// minTemp: 1.0, +// weaver: false +// }) +// ]; +// const lay = layouts[0]; +// aliases(lay.run, lay.start); +// events(lay); +// layouts.map(layout => { +// layout.run(); +// layout.stop(); +// }); + +// TODO: cy.style + +cy.png({ + output: oneOf('base64uri', 'base64', 'blob', undefined), + bg: oneOf('#ffffff', undefined), + full: true, + scale: 2, + maxWidth: 100, + maxHeight: 100 +}); +aliases(cy.jpg, cy.jpeg); +cy.jpg({ + output: oneOf('base64uri', 'base64', 'blob', undefined), + bg: oneOf('#ffffff', undefined), + full: true, + scale: 2, + maxWidth: 100, + maxHeight: 100, + quality: 0.5 +}); +cy.json(cy.json()); + +// Types possible to call methods +const ele = oneOf(cy.nodes()[0], cy.edges()[0]); +const eles = cy.elements(); +const node = cy.nodes()[0]; +const nodes = cy.nodes(); +const edge = cy.edges()[0]; +const edges = cy.edges(); + +assert(ele.cy() === cy); +eles.remove(); +assert(eles.removed()); +assert(!eles.inside()); +eles.restore(); + +([ele, eles, node, nodes, edge, edges] as cytoscape.CollectionReturnValue[]).forEach((elem) => { + aliases(elem.clone, elem.copy); + events(elem); + aliases(elem.data, elem.attr); + aliases(elem.removeData, elem.removeAttr); +}); +// TODO: tests for data flow + +const loops = oneOf(true, false); +node.degree(loops); node.indegree(loops); node.outdegree(loops); +nodes.totalDegree(loops); nodes.minDegree(loops); nodes.maxDegree(loops); +nodes.minIndegree(loops); nodes.maxIndegree(loops); nodes.minOutdegree(loops); nodes.maxOutdegree(loops); + +// tslint:disable-next-line:ban-types +const getsetPos = (func: T): T => { + func('x', func('x')); + func(func()); + func({x: 100, y: 100}); + return func; +}; + +aliases(node.modelPosition, node.point, node.position); +getsetPos(node.position); + +nodes.shift('x', 100); +nodes.shift({x: -100, y: 0}); + +aliases(nodes.modelPositions, nodes.positions, nodes.points); +nodes.positions((node, i) => Object.assign(node.position(), {x: node.position('x') + i})); + +aliases(node.renderedPosition, node.renderedPoint); +getsetPos(node.renderedPoint); + +// TODO: tests for compound nodes (relativePosition, in particular) + +const sizes: number[] = [ + ele.width(), ele.outerWidth(), ele.renderedWidth(), ele.renderedOuterWidth(), + ele.height(), ele.outerHeight(), ele.renderedHeight(), ele.renderedOuterHeight() +]; + +aliases(eles.boundingBox, eles.boundingbox); +aliases(eles.renderedBoundingBox, eles.renderedBoundingbox); + +const flags: boolean[] = [ + node.grabbed(), node.grabbable(), node.locked(), ele.active(), +]; + +const edgePoints: cytoscape.Position[] = [ + ...edge.controlPoints(), ...edge.segmentPoints(), edge.sourceEndpoint(), edge.targetEndpoint(), edge.midpoint() +]; + +aliases(eles.layout, eles.createLayout, eles.makeLayout); +const layout = eles.layout({name: 'random'}).run(); + +eles.select(); +assert(ele.selected()); // as we selected all, and this too +aliases(eles.unselect, eles.deselect); +eles.selectify(); +assert(ele.selectable()); +eles.unselectify(); + +eles.addClass('test'); +eles.toggleClass('test', oneOf(true, false, undefined)); +eles.removeClass('test'); +eles.classes(oneOf('test', undefined)); +eles.flashClass('test flash', oneOf(1000, undefined)); +assert(ele.hasClass('test')); + +eles.style('background-color', 'green'); +Object.keys(eles.style()).map(key => eles.style(key)); +eles.style(eles.style()); +aliases(eles.style, eles.css); +aliases(ele.renderedCss, ele.renderedStyle); + +eles.anySame(nodes); +aliases(eles.contains, eles.has); +aliases(eles.allAreNeighbors, eles.allAreNeighbours); +eles.is('#g'); +eles.allAre('#g'); +eles.some((el, i, els) => true); +eles.every((el, i, els) => true); + +aliases(eles.forEach, eles.each); +const selected: cytoscape.SingularElementArgument[] = [eles.eq(0), eles.first(), eles.last()]; +const collSel = cy.collection(selected); +const selectedNodes: cytoscape.NodeSingular[] = [nodes.eq(0), nodes.first(), nodes.last()]; +const collNodes = cy.collection(selectedNodes); +const selectedEdges: cytoscape.EdgeSingular[] = [edges.eq(0), edges.first(), edges.last()]; +eles.slice(0, -1); +eles.toArray(); + +aliases(eles.getElementById, eles.$id); +aliases(eles.union, eles.add, eles.or, eles.u, eles['+'], eles['|']); +aliases(eles.difference, eles.not, eles.subtract, eles.relativeComplement, eles['\\'], eles['!'], eles['-']); +aliases(eles.absoluteComplement, eles.abscomp, eles.complement); +aliases(eles.intersection, eles.intersect, eles.and, eles.n, eles['&'], eles['.']); +aliases(eles.symmetricDifference, eles.symdiff, eles.xor, eles['^'], eles['(+)'], eles['(-)']); +cy.collection([nodes[0]]).union(nodes[1]).union(eles.$id('g')); +eles.difference(collNodes).abscomp().intersection(collSel).symdiff(collNodes); +const diff = collSel.diff(collNodes); +cy.collection().merge(diff.left).merge(diff.right).merge(diff.both).unmerge(collSel).filter((ele, i, eles) => true); + +eles.sort((a, b) => 1).map((ele, i, eles) => [i, ele]); +eles.reduce((prev, ele, i, eles) => [...prev, [ele, i]], []).concat(['finish']); +const min = eles.min((ele, i, eles) => ele.id.length + i); min.ele.scratch('min', min.value); +const max = eles.max((ele, i, eles) => ele.id.length + i); max.ele.scratch('max', max.value); + +// TODO: traversing (need to actively check the nodes/edeges distinction) +// TODO: algorithms +// TODO: compound nodes (there aren't any in current test case) diff --git a/types/cytoscape/index.d.ts b/types/cytoscape/index.d.ts index e85041861a..a3226defd2 100644 --- a/types/cytoscape/index.d.ts +++ b/types/cytoscape/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Cytoscape.js 3.1 +// Type definitions for Cytoscape.js 3.2 // Project: http://js.cytoscape.org/ // Definitions by: Fabian Schmidt and Fred Eisele // Shenghan Gao @@ -9,7 +9,7 @@ // // Translation from Objects in help to Typescript interface. // http://js.cytoscape.org/#notation/functions -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /** * cy --> Cy.Core @@ -361,7 +361,7 @@ declare namespace cytoscape { * * The default value is 1. */ - pixelRatio?: number; + pixelRatio?: number | 'auto'; } /** @@ -386,35 +386,42 @@ declare namespace cytoscape { /** * Add elements to the graph and return them. */ - add(eles: ElementDefinition | ElementDefinition[] | Collection): CollectionElements; + add(eles: ElementDefinition | ElementDefinition[] | CollectionArgument): CollectionReturnValue; /** * Remove elements in collecion or match the selector from the graph and return them. */ - remove(eles: Collection | Selector): CollectionElements; + remove(eles: CollectionArgument | Selector): CollectionReturnValue; /** * Get a collection from elements in the graph matching the specified selector or from an array of elements. * If no parameter specified, an empty collection will be returned */ - collection(eles?: Selector | CollectionElements[]): CollectionElements; + collection(eles?: Selector | CollectionArgument[]): CollectionReturnValue; /** * Get an element from its ID in a very performant way. + * http://js.cytoscape.org/#cy.getElementById */ - getElementById(id: string): CollectionElements; + getElementById(id: string): CollectionReturnValue; + + /** + * Get an element from its ID in a very performant way. + * http://js.cytoscape.org/#cy.getElementById + */ + $id(id: string): CollectionReturnValue; /** * Get elements in the graph matching the specified selector. * http://js.cytoscape.org/#cy.$ */ - $(selector: Selector): CollectionElements; + $(selector: Selector): CollectionReturnValue; /** * Get elements in the graph matching the specified selector. * http://js.cytoscape.org/#cy.$ */ - elements(selector?: Selector): CollectionElements; + elements(selector?: Selector): CollectionReturnValue; /** * Get nodes in the graph matching the specified selector. @@ -428,7 +435,7 @@ declare namespace cytoscape { /** * Get elements in the graph matching the specified selector or filter function. */ - filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionElements) => boolean)): CollectionElements; + filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionArgument) => boolean)): CollectionReturnValue; /** * Allow for manipulation of elements without triggering multiple style calculations or multiple redraws. @@ -599,14 +606,20 @@ declare namespace cytoscape { ready(fn: EventHandler): void; } - interface ZoomOptions { - /** The zoom level to set. */ - level: number; + interface ZoomOptionsModel { /** The position about which to zoom. */ position: Position; + } + interface ZoomOptionsRendered { /** The rendered position about which to zoom. */ renderedPosition: Position; } + interface ZoomOptionsLevel { + /** The zoom level to set. */ + level: number; + } + type ZoomOptions = ZoomOptionsLevel & (ZoomOptionsModel | ZoomOptionsRendered); + /** * http://js.cytoscape.org/#core/viewport-manipulation */ @@ -615,14 +628,21 @@ declare namespace cytoscape { * Get the HTML DOM element in which the graph is visualised. * A null value is returned if the Core is headless. */ - container(): any; + container(): Element | null; /** * Pan the graph to the centre of a collection. * * @param eles The collection to centre upon. */ - center(eles?: Collection): CollectionElements; + center(eles?: CollectionArgument): this; + + /** + * Pan the graph to the centre of a collection. + * + * @param eles The collection to centre upon. + */ + centre(eles?: CollectionArgument): this; /** * Pan and zooms the graph to fit to a collection. @@ -631,13 +651,13 @@ declare namespace cytoscape { * @param eles [optional] The collection to fit to. * @param padding [optional] An amount of padding (in pixels) to have around the graph */ - fit(eles?: Collection, padding?: number): CollectionElements; + fit(eles?: CollectionArgument, padding?: number): this; /** * Reset the graph to the default zoom level and panning position. * http://js.cytoscape.org/#cy.reset */ - reset(): CollectionElements; + reset(): this; /** * Get the panning position of the graph. @@ -651,7 +671,7 @@ declare namespace cytoscape { * * @param renderedPosition The rendered position to pan the graph to. */ - pan(renderedPosition?: Position): void; + pan(renderedPosition?: Position): this; /** * Relatively pan the graph by a specified rendered position vector. @@ -659,7 +679,7 @@ declare namespace cytoscape { * * @param renderedPosition The rendered position vector to pan the graph by. */ - panBy(renderedPosition: Position): void; + panBy(renderedPosition: Position): this; /** * Get whether panning is enabled. @@ -867,7 +887,8 @@ declare namespace cytoscape { * there is no resize or style event for arbitrary DOM elements. * http://js.cytoscape.org/#cy.resize */ - resize(): CollectionElements; + resize(): this; + invalidateDimensions(): this; } /** @@ -875,15 +896,15 @@ declare namespace cytoscape { * */ interface AnimationFitOptions { - eles: CollectionElements | Selector; // to which the viewport will be fitted. + eles: CollectionArgument | Selector; // to which the viewport will be fitted. padding: number; // Padding to use with the fitting. } interface CenterOptions { - eles: CollectionElements | Selector; // to which the viewport will be selected. + eles: CollectionArgument | Selector; // to which the viewport will be selected. } - interface AnimateOptionsCommon { + interface AnimationOptions { /** A zoom level to which the graph will be animated. */ - zoom?: number; + zoom?: ZoomOptions; /** A panning position to which the graph will be animated. */ pan?: Position; /** A relative panning position to which the graph will be animated. */ @@ -892,11 +913,13 @@ declare namespace cytoscape { fit?: AnimationFitOptions; /** An object containing centring options from which the graph will be animated. */ center?: CenterOptions; + /** easing - A transition-timing-function easing style string that shapes the animation progress curve. */ + easing?: string; // TODO: explicit type /** duration - The duration of the animation in milliseconds. */ duration?: number; } - interface AnimateOptions extends AnimateOptionsCommon { + interface AnimateOptions extends AnimationOptions { /** queue - A boolean indicating whether to queue the animation. */ queue?: boolean; /** complete - A function to call when the animation is done. */ @@ -904,14 +927,6 @@ declare namespace cytoscape { /** step - A function to call each time the animation steps. */ step?(): void; } - interface AnimationOptions extends AnimateOptionsCommon { - /** queue - A transition-timing-function easing style string that shapes the animation progress curve. */ - easing?: boolean; - /** complete - A function to call when the animation is done. */ - complete?(): void; - /** step - A function to call each time the animation steps. */ - step?(): void; - } interface CoreAnimation { /** @@ -993,6 +1008,7 @@ declare namespace cytoscape { * An analogue to make a layout on a subset of the graph exists as eles.makeLayout(). */ makeLayout(options: LayoutOptions): LayoutManipulation; + createLayout(options: LayoutOptions): LayoutManipulation; } /** @@ -1080,17 +1096,18 @@ declare namespace cytoscape { /** * Export the current graph view as a JPG image in Base64 representation. */ - jpg(options?: ExportOptions): string; + jpg(options?: ExportJpgOptions): string; /** * Export the current graph view as a JPG image in Base64 representation. */ - jpeg(options?: ExportOptions): string; + jpeg(options?: ExportJpgOptions): string; /** * Export the graph as JSON, the same format used at initialisation. */ - json(): string; + json(): object; + json(json: object): this; } /** @@ -1100,13 +1117,14 @@ declare namespace cytoscape { * The input can be any element (node and edge) collection. * http://js.cytoscape.org/#collection */ - interface Collection extends Singular, + interface Collection + extends Singular, CollectionGraphManipulation, CollectionEvents, CollectionData, CollectionPosition, CollectionLayout, CollectionSelection, CollectionStyle, CollectionAnimation, - CollectionComparision, CollectionIteration, - CollectionBuildingUnion, CollectionAlgorithms { } + CollectionComparision, CollectionIteration, + CollectionBuildingFiltering, CollectionAlgorithms { } /** * ele --> Cy.Singular @@ -1127,7 +1145,8 @@ declare namespace cytoscape { /** * The output is a collection of node and edge elements OR single element. */ - type CollectionElements = EdgeCollection | NodeCollection | SingularElement; + type CollectionArgument = EdgeCollection | NodeCollection | SingularElementArgument; + type CollectionReturnValue = EdgeCollection & NodeCollection & SingularElementReturnValue; /** * edges -> Cy.EdgeCollection @@ -1135,7 +1154,7 @@ declare namespace cytoscape { * * The output is a collection of edge elements OR single edge. */ - interface EdgeCollection extends Collection, EdgeSingular, + interface EdgeCollection extends Collection, EdgeSingular, EdgeCollectionTraversing { } /** * nodes -> Cy.NodeCollection @@ -1143,19 +1162,18 @@ declare namespace cytoscape { * * The output is a collection of node elements OR single node. */ - interface NodeCollection extends Collection, NodeSingular, + interface NodeCollection extends Collection, NodeSingular, NodeCollectionMetadata, NodeCollectionPosition, NodeCollectionTraversing, NodeCollectionCompound { } - interface SingularElement extends EdgeSingular, NodeSingular { - // Intentionally empty. - } + type SingularElementArgument = EdgeSingular | NodeSingular; + type SingularElementReturnValue = EdgeSingular & NodeSingular; /** * edge --> Cy.EdgeSingular * a collection of a single edge */ interface EdgeSingular extends Singular, - EdgeSingularData, EdgeSingularTraversing { } + EdgeSingularData, EdgeSingularPoints, EdgeSingularTraversing { } /** * node --> Cy.NodeSingular @@ -1172,24 +1190,24 @@ declare namespace cytoscape { * Remove the elements from the graph. * http://js.cytoscape.org/#eles.remove */ - remove(): CollectionElements; + remove(): CollectionReturnValue; /** * Put removed elements back into the graph. * http://js.cytoscape.org/#eles.restore */ - restore(): CollectionElements; + restore(): CollectionReturnValue; /** * Get a new collection containing clones (i.e. copies) of the elements in the calling collection. * http://js.cytoscape.org/#eles.clone */ - clone(): CollectionElements; + clone(): CollectionReturnValue; /** * Get a new collection containing clones (i.e. copies) of the elements in the calling collection. * http://js.cytoscape.org/#eles.clone */ - copy(): CollectionElements; + copy(): CollectionReturnValue; /** * Effectively move edges to different nodes. The modified (actually new) elements are returned. @@ -1207,6 +1225,10 @@ declare namespace cytoscape { * http://js.cytoscape.org/#collection/graph-manipulation */ interface SingularGraphManipulation { + /** + * Get the core instance that owns the element. + */ + cy(): Core; /** * Get whether the element has been removed from the graph. * http://js.cytoscape.org/#ele.removed @@ -1279,8 +1301,8 @@ declare namespace cytoscape { * http://js.cytoscape.org/#eles.removeData * @param names A space-separated list of fields to delete. */ - removeData(names?: string): CollectionElements; - removeAttr(names?: string): CollectionElements; + removeData(names?: string): CollectionReturnValue; + removeAttr(names?: string): CollectionReturnValue; /** * Get an array of the plain JavaScript object @@ -1313,6 +1335,22 @@ declare namespace cytoscape { * @param obj The object containing name- value pairs to update data fields. */ data(obj: any): void; + /** + * Get a particular data field for the element. + * @param name The name of the field to get. + */ + attr(name?: string): any; + /** + * Set a particular data field for the element. + * @param name The name of the field to set. + * @param value The value to set for the field. + */ + attr(name: string, value: any): void; + /** + * Update multiple data fields at once via an object. + * @param obj The object containing name- value pairs to update data fields. + */ + attr(obj: any): void; /** * Get or set the scratchpad at a particular namespace, @@ -1461,17 +1499,77 @@ declare namespace cytoscape { * Get the (model) position of a node. */ position(): Position; + /** + * Get the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + position(dimension: PositionDimension): number; /** * Set the value of a specified position dimension. * @param dimension The position dimension to set. * @param value The value to set to the dimension. */ - position(dimension: PositionDimension, value?: Position): void; + position(dimension: PositionDimension, value: number): this; /** * Set the position using name-value pairs in the specified object. * @param pos An object specifying name-value pairs representing dimensions to set. */ - position(pos: Position): void; + position(pos: Position): this; + /** + * Get the (model) position of a node. + */ + modelPosition(): Position; + /** + * Get the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + modelPosition(dimension: PositionDimension): number; + /** + * Set the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + modelPosition(dimension: PositionDimension, value: number): this; + /** + * Set the position using name-value pairs in the specified object. + * @param pos An object specifying name-value pairs representing dimensions to set. + */ + modelPosition(pos: Position): this; + /** + * Get the (model) position of a node. + */ + point(): Position; + /** + * Get the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + point(dimension: PositionDimension): number; + /** + * Set the value of a specified position dimension. + * @param dimension The position dimension to set. + * @param value The value to set to the dimension. + */ + point(dimension: PositionDimension, value: number): this; + /** + * Set the position using name-value pairs in the specified object. + * @param pos An object specifying name-value pairs representing dimensions to set. + */ + point(pos: Position): this; + + /** + * Shift the positions of the nodes by a given model position vector. + * @param dimension The position dimension to shift. + * @param value The value to shift the dimension. + */ + shift(dimension: PositionDimension, value?: number): this; + /** + * Shift the positions of the nodes by a given model position vector. + * @param pos An object specifying name-value pairs representing dimensions to shift. + */ + shift(pos: Position): this; /** * Get or set the rendered (on-screen) position of a node. @@ -1542,8 +1640,8 @@ declare namespace cytoscape { * @param ele The element being iterated over for which the function should return a position to set. * @param ix The index of the element when iterating over the elements in the collection. */ - type ElementPositionFunction = (ele: CollectionElements, ix: number) => void; - type ElementCollectionFunction = (ele: CollectionElements, ix: number, eles: CollectionElements) => void; + type ElementPositionFunction = (ele: NodeSingular, ix: number) => void; + type ElementCollectionFunction = (ele: NodeSingular, ix: number, eles: CollectionArgument) => void; /** * http://js.cytoscape.org/#collection/position--dimensions @@ -1556,9 +1654,7 @@ declare namespace cytoscape { * http://js.cytoscape.org/#nodes.positions */ positions(handler: ElementPositionFunction | Position): void; - modelPositions(handler: ElementPositionFunction | Position): void; - points(handler: ElementPositionFunction | Position): void; /** @@ -1647,11 +1743,13 @@ declare namespace cytoscape { * http://js.cytoscape.org/#eles.boundingBox */ boundingBox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; + boundingbox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; /** * Get the bounding box of the elements in rendered coordinates. * @param options An object containing options for the function. */ renderedBoundingBox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; + renderedBoundingbox(options: BoundingBoxOptions): BoundingBox12 | BoundingBoxWH; } /** @@ -1668,9 +1766,9 @@ declare namespace cytoscape { * * @param options The layout options. */ - layout(options: LayoutOptions): CollectionElements; - makeLayout(options: LayoutOptions): CoreLayout; - createLayout(options: LayoutOptions): CoreLayout; + layout(options: LayoutOptions): LayoutManipulation; + makeLayout(options: LayoutOptions): LayoutManipulation; + createLayout(options: LayoutOptions): LayoutManipulation; } /** @@ -1684,7 +1782,7 @@ declare namespace cytoscape { // easing of animation, if enabled animationEasing?: number; // collection of elements involved in the layout; set by cy.layout() or eles.layout() - eles: CollectionElements; + eles: CollectionArgument; // whether to fit the viewport to the graph fit?: boolean; // padding to leave between graph and viewport @@ -1811,11 +1909,50 @@ declare namespace cytoscape { flashClass(classes: ClassNames, duration?: number): void; /** - * Get or set a particular style property value. - * @param name The name of the visual style property to get. + * Set a particular style property value. + * @param name The name of the visual style property to set. * @param value The value to which the property is set. */ - style(name?: string, value?: any): any; + style(name: string, value: any): this; + /** + * Get a particular style property value. + * @param name The name of the visual style property to get. + */ + style(name: string): any; + /** + * Set several particular style property values. + * @param obj An object of style property name-value pairs to set. + */ + style(obj: object): this; + /** + * Get a name-value pair object containing visual style properties and their values for the element. + */ + style(): {[index: string]: any}; + /** + * Set a particular style property value. + * @param name The name of the visual style property to set. + * @param value The value to which the property is set. + */ + css(name: string, value: any): this; + /** + * Get a particular style property value. + * @param name The name of the visual style property to get. + */ + css(name: string): any; + /** + * Set several particular style property values. + * @param obj An object of style property name-value pairs to set. + */ + css(obj: object): this; + /** + * Get a name-value pair object containing visual style properties and their values for the element. + */ + css(): {[index: string]: any}; + /** + * Remove all or specific style overrides. + * @param names A space-separated list of property names to remove overrides + */ + removeStyle(names?: string): this; } /** @@ -1977,27 +2114,36 @@ declare namespace cytoscape { * * @param eles The other elements to compare to. */ - same(eles: Collection): boolean; + same(eles: CollectionArgument): boolean; /** * Determine whether this collection contains any of the same elements as another collection. * * @param eles The other elements to compare to. */ - anySame(eles: Collection): boolean; + anySame(eles: CollectionArgument): boolean; + + /** + * Determine whether this collection contains all of the elements of another collection. + */ + contains(eles: CollectionArgument): boolean; + /** + * Determine whether this collection contains all of the elements of another collection. + */ + has(eles: CollectionArgument): boolean; /** * Determine whether all elements in the specified collection are in the neighbourhood of the calling collection. * * @param eles The other elements to compare to. */ - allAreNeighbors(eles: Collection): boolean; + allAreNeighbors(eles: CollectionArgument): boolean; /** * Determine whether all elements in the specified collection are in the neighbourhood of the calling collection. * * @param eles The other elements to compare to. */ - allAreNeighbours(eles: Collection): boolean; + allAreNeighbours(eles: CollectionArgument): boolean; /** * Determine whether any element in this collection matches a selector. @@ -2021,7 +2167,7 @@ declare namespace cytoscape { * eles - The collection of elements being tested. * @param thisArg [optional] The value for this within the test function. */ - some(test: (ele: CollectionElements, i: number, eles: CollectionElements) => boolean, thisArg?: any): boolean; + some(test: (ele: CollectionArgument, i: number, eles: CollectionArgument) => boolean, thisArg?: any): boolean; /** * Determine whether all elements in this collection satisfy the specified test function. @@ -2032,13 +2178,13 @@ declare namespace cytoscape { * eles - The collection of elements being tested. * @param thisArg [optional] The value for this within the test function. */ - every(test: (ele: CollectionElements, i: number, eles: CollectionElements) => boolean, thisArg?: any): boolean; + every(test: (ele: CollectionArgument, i: number, eles: CollectionArgument) => boolean, thisArg?: any): boolean; } /** * http://js.cytoscape.org/#collection/iteration */ - interface CollectionIteration { + interface CollectionIteration { /** * Get the number of elements in the collection. */ @@ -2070,8 +2216,8 @@ declare namespace cytoscape { * eles - The collection of elements being iterated. * @param thisArg [optional] The value for this within the iterating function. */ - each(each: (ele: CollectionElements, i: number, eles: CollectionElements) => void | boolean, thisArg?: any): void; - forEach(each: (ele: CollectionElements, i: number, eles: CollectionElements) => void | boolean, thisArg?: any): void; + each(each: (ele: TIn, i: number, eles: this) => void | boolean, thisArg?: any): void; + forEach(each: (ele: TIn, i: number, eles: this) => void | boolean, thisArg?: any): void; /** * Get an element at a particular index in the collection. @@ -2080,21 +2226,21 @@ declare namespace cytoscape { * * @param index The index of the element to get. */ - eq(index: number): CollectionElements; + eq(index: number): TOut; /** * Get an element at a particular index in the collection. * * @param index The index of the element to get. */ - [index: number]: CollectionElements; + [index: number]: TOut; /** * Get the first element in the collection. */ - first(): CollectionElements; + first(): TOut; /** * Get the last element in the collection. */ - last(): CollectionElements; + last(): TOut; /** * Get a subset of the elements in the collection based on specified indices. @@ -2106,7 +2252,12 @@ declare namespace cytoscape { * If omitted, all elements from the start position and to the end of the array will be selected. * Use negative numbers to select from the end of an array. */ - slice(start?: number, end?: number): CollectionElements; + slice(start?: number, end?: number): this; + + /** + * Get the collection as an array, maintaining the order of the elements. + */ + toArray(): SingularElementReturnValue[]; } /** @@ -2118,7 +2269,7 @@ declare namespace cytoscape { * @param eles The elements or array of elements to add or elements in the graph matching the selector. * http://js.cytoscape.org/#eles.union */ - type CollectionBuildingUnionFunc = (eles: Collection | Collection[] | Selector) => CollectionElements; + type CollectionBuildingUnionFunc = (eles: CollectionArgument | CollectionArgument[] | Selector) => CollectionReturnValue; /** * Get a new collection, resulting from the collection without some specified elements. @@ -2126,7 +2277,7 @@ declare namespace cytoscape { * @param eles The elements that will not be in the resultant collection. * Elements from the calling collection matching this selector will not be in the resultant collection. */ - type CollectionBuildingDifferenceFunc = (eles: Collection | Selector) => CollectionElements; + type CollectionBuildingDifferenceFunc = (eles: CollectionArgument | Selector) => CollectionReturnValue; /** * Get the elements in both this collection and another specified collection. @@ -2135,7 +2286,7 @@ declare namespace cytoscape { * A selector representing the elements to intersect with. * All elements in the graph matching the selector are used as the passed collection. */ - type CollectionBuildingIntersectionFunc = (eles: Collection | Selector) => CollectionElements; + type CollectionBuildingIntersectionFunc = (eles: CollectionArgument | Selector) => CollectionReturnValue; /** * Get the elements that are in the calling collection or the passed collection but not in both. @@ -2144,40 +2295,52 @@ declare namespace cytoscape { * A selector representing the elements to apply the symmetric difference with. * All elements in the graph matching the selector are used as the passed collection. */ - type CollectionSymmetricDifferenceFunc = (eles: Collection | Selector) => CollectionElements; + type CollectionSymmetricDifferenceFunc = (eles: CollectionArgument | Selector) => CollectionReturnValue; /** * http://js.cytoscape.org/#collection/building--filtering */ - interface CollectionBuildingUnion { + interface CollectionBuildingFiltering { + /** + * Get an element in the collection from its ID in a very performant way. + * @param id The ID of the element to get. + */ + getElementById(id: string): TOut; + /** + * Get an element in the collection from its ID in a very performant way. + * @param id The ID of the element to get. + */ + $id(id: string): TOut; + /** * Get a new collection, resulting from adding the collection with another one * http://js.cytoscape.org/#eles.union */ union: CollectionBuildingUnionFunc; - // [index: "u"]: CollectionBuildingUnionFunc; + u: CollectionBuildingUnionFunc; add: CollectionBuildingUnionFunc; - // [index: "+"]: CollectionBuildingUnionFunc; + '+': CollectionBuildingUnionFunc; or: CollectionBuildingUnionFunc; - // [index: "|"]: CollectionBuildingUnionFunc; + '|': CollectionBuildingUnionFunc; /** * Get a new collection, resulting from the collection without some specified elements. * http://js.cytoscape.org/#eles.difference */ difference: CollectionBuildingDifferenceFunc; - // [index: "\\"]: CollectionBuildingDifferenceFunc; + subtract: CollectionBuildingDifferenceFunc; + '\\': CollectionBuildingDifferenceFunc; not: CollectionBuildingDifferenceFunc; - // [index: "!"]: CollectionBuildingDifferenceFunc; + '!': CollectionBuildingDifferenceFunc; relativeComplement: CollectionBuildingDifferenceFunc; - // [index: "-"]: CollectionBuildingDifferenceFunc; + '-': CollectionBuildingDifferenceFunc; /** * Get all elements in the graph that are not in the calling collection. * http://js.cytoscape.org/#eles.absoluteComplement */ - absoluteComplement(): CollectionElements; - abscomp(): CollectionElements; - complement(): CollectionElements; + absoluteComplement(): CollectionReturnValue; + abscomp(): CollectionReturnValue; + complement(): CollectionReturnValue; /** * Get the elements in both this collection and another specified collection. @@ -2186,9 +2349,9 @@ declare namespace cytoscape { intersection: CollectionSymmetricDifferenceFunc; intersect: CollectionSymmetricDifferenceFunc; and: CollectionSymmetricDifferenceFunc; - // [index: "n"]: CollectionSymmetricDifferenceFunc; - // [index: "&"]: CollectionSymmetricDifferenceFunc; - // [index: "."]: CollectionSymmetricDifferenceFunc; + n: CollectionSymmetricDifferenceFunc; + '&': CollectionSymmetricDifferenceFunc; + '.': CollectionSymmetricDifferenceFunc; /** * Get the elements that are in the calling collection @@ -2198,11 +2361,9 @@ declare namespace cytoscape { symmetricDifference: CollectionSymmetricDifferenceFunc; symdiff: CollectionSymmetricDifferenceFunc; xor: CollectionSymmetricDifferenceFunc; - // [index: "^"]: CollectionSymmetricDifferenceFunc; - // [index: "(+)"]: CollectionSymmetricDifferenceFunc; - // [index: "(-)"]: CollectionSymmetricDifferenceFunc; - - // [index: string]: CollectionBuildingDifferenceFunc |CollectionBuildingUnionFunc | CollectionBuildingDifferenceFunc | CollectionSymmetricDifferenceFunc; + '^': CollectionSymmetricDifferenceFunc; + '(+)': CollectionSymmetricDifferenceFunc; + '(-)': CollectionSymmetricDifferenceFunc; /** * Perform a traditional left/right diff on the two collections. @@ -2216,12 +2377,62 @@ declare namespace cytoscape { * both - is the set of elements in both collections. * http://js.cytoscape.org/#eles.diff */ - diff(selector: Selector | Collection): { - left: CollectionElements, - right: CollectionElements, - both: CollectionElements + diff(selector: Selector | CollectionArgument): { + left: CollectionReturnValue, + right: CollectionReturnValue, + both: CollectionReturnValue }; + /** + * Perform a in-place merge of the given elements into the calling collection. + * @param eles The elements to merge in-place or a selector representing the elements to merge. + * All elements in the graph matching the selector are used as the passed collection. + * + * This function modifies the calling collection instead of returning a new one. + * Use of this function should be considered for performance in some cases, but otherwise should be avoided. Consider using eles.union() instead. + * Use this function only on new collections that you create yourself, using cy.collection(). + * This ensures that you do not unintentionally modify another collection. + * + * Examples + * With a collection: + * @example + * var col = cy.collection(); // new, empty collection + * var j = cy.$('#j'); + * var e = cy.$('#e'); + * col.merge( j ).merge( e ); + * + * With a selector: + * @example + * var col = cy.collection(); // new, empty collection + * col.merge('#j').merge('#e'); + */ + merge(eles: CollectionArgument | string): this; + /** + * Perform an in-place operation on the calling collection to remove the given elements. + * @param eles The elements to remove in-place or a selector representing the elements to remove . + * All elements in the graph matching the selector are used as the passed collection. + * + * This function modifies the calling collection instead of returning a new one. + * Use of this function should be considered for performance in some cases, but otherwise should be avoided. Consider using eles.filter() or eles.remove() instead. + * Use this function only on new collections that you create yourself, using cy.collection(). + * This ensures that you do not unintentionally modify another collection. + * + * Examples + * With a collection: + * @example + * var col = cy.collection(); // new, empty collection + * var e = cy.$('#e'); + * col.merge( cy.nodes() ); + * col.unmerge( e ); + * + * With a selector: + * @example + * var col = cy.collection(); // new, empty collection + * col.merge( cy.nodes() ); + * col.unmerge('#e'); + */ + unmerge(eles: CollectionArgument | string): this; + /** * Get a new collection containing elements that are accepted by the specified filter. * @@ -2231,21 +2442,21 @@ declare namespace cytoscape { * ele - The element being considered. * http://js.cytoscape.org/#eles.filter */ - filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionElements) => boolean)): CollectionElements; + filter(selector: Selector | ((ele: TOut, i: number, eles: CollectionArgument) => boolean)): CollectionReturnValue; /** * Get the nodes that match the specified selector. * * @param selector The selector to match against. * http://js.cytoscape.org/#eles.filter */ - nodes(selector: Selector): NodeCollection; + nodes(selector?: Selector): NodeCollection; /** * Get the edges that match the specified selector. * * @param selector The selector to match against. * http://js.cytoscape.org/#eles.filter */ - edges(selector: Selector): EdgeCollection; + edges(selector?: Selector): EdgeCollection; /** * Get a new collection containing the elements sorted by the @@ -2257,7 +2468,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.sort */ - sort(sort: (ele1: CollectionElements, ele2: CollectionElements) => number): CollectionElements; + sort(sort: (ele1: CollectionArgument, ele2: CollectionArgument) => number): CollectionReturnValue; /** * Get an array containing values mapped from the collection. @@ -2270,7 +2481,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.map */ - map(fn: (ele: CollectionElements, i: number, eles: CollectionElements) => any, thisArg?: any): any[]; + map(fn: (ele: CollectionArgument, i: number, eles: CollectionArgument) => any, thisArg?: any): any[]; /** * Reduce a single value by applying a @@ -2282,11 +2493,13 @@ declare namespace cytoscape { * ele The current element. * ix The index of the current element. * eles The collection of elements being reduced. - * + * @param initialValue The initial value for reducing + * It is used also for type inference of output, but the type can be + * also stated explicitly as generic * http://js.cytoscape.org/#eles.reduce */ - reduce(fn: (prevVal: any, ele: CollectionElements, - ix: number, eles: CollectionElements) => any): number[]; + reduce(fn: (prevVal: T, ele: SingularElementReturnValue, + ix: number, eles: CollectionReturnValue) => T, initialValue: T): T; /** * Find a minimum value in a collection. @@ -2299,7 +2512,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.min */ - min(fn: (ele: CollectionElements, i: number, eles: CollectionElements) => any, thisArg?: any): { + min(fn: (ele: CollectionArgument, i: number, eles: CollectionArgument) => any, thisArg?: any): { /** * The minimum value found. */ @@ -2307,7 +2520,7 @@ declare namespace cytoscape { /** * The element that corresponds to the minimum value. */ - ele: CollectionElements + ele: CollectionArgument }; /** @@ -2321,7 +2534,7 @@ declare namespace cytoscape { * * http://js.cytoscape.org/#eles.max */ - max(fn: (ele: CollectionElements, i: number, eles: CollectionElements) => any, thisArg?: any): { + max(fn: (ele: CollectionArgument, i: number, eles: CollectionArgument) => any, thisArg?: any): { /** * The maximum value found. */ @@ -2329,7 +2542,7 @@ declare namespace cytoscape { /** * The element that corresponds to the maximum value. */ - ele: CollectionElements + ele: CollectionArgument }; } @@ -2351,7 +2564,7 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - neighborhood(selector?: Selector): CollectionElements; + neighborhood(selector?: Selector): CollectionReturnValue; /** * Get the open neighbourhood of the elements. @@ -2362,7 +2575,7 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - openNeighborhood(selector?: Selector): CollectionElements; + openNeighborhood(selector?: Selector): CollectionReturnValue; /** * Get the closed neighbourhood of the elements. * @@ -2372,13 +2585,54 @@ declare namespace cytoscape { * * @param selector [optional] An optional selector that is used to filter the resultant collection. */ - closedNeighborhood(selector?: Selector): CollectionElements; + closedNeighborhood(selector?: Selector): CollectionReturnValue; /** * Get the connected components, considering only the elements in the calling collection. * An array of collections is returned, with each collection representing a component. */ - components(): Collection; + components(): CollectionReturnValue[]; + } + /** + * http://js.cytoscape.org/#collection/edge-points + */ + interface EdgeSingularPoints { + /** + * Get an array of control point model positions for a {@code curve-style: bezier) or {@code curve-style: unbundled-bezier} edge. + * + * While the control points may be specified relatively in the CSS, + * this function returns the absolute model positions of the control points. + * The points are specified in the order of source-to-target direction. + * This function works for bundled beziers, but it is not applicable to the middle, straight-line edge in the bundle. + */ + controlPoints(): Position[]; + /** + * Get an array of segment point model positions (i.e. bend points) for a {@code curve-style: segments} edge. + * + * While the segment points may be specified relatively in the stylesheet, + * this function returns the absolute model positions of the segment points. + * The points are specified in the order of source-to-target direction. + */ + segmentPoints(): Position[]; + /** + * Get the model position of where the edge ends, towards the source node. + */ + sourceEndpoint(): Position; + /** + * Get the model position of where the edge ends, towards the target node. + */ + targetEndpoint(): Position; + /** + * Get the model position of the midpoint of the edge. + * + * The midpoint is, by default, where the edge’s label is centred. It is also the position towards which mid arrows point. + * For curve-style: unbundled-bezier edges, the midpoint is the middle extremum if the number of control points is odd. + * For an even number of control points, the midpoint is where the two middle-most control points meet. + * This is the middle inflection point for bilaterally symmetric or skew symmetric edges, for example. + * For curve-style: segments edges, the midpoint is the middle segment point if the number of segment points is odd. + * For an even number of segment points, the overall midpoint is the midpoint of the middle-most line segment (i.e. the mean of the middle two segment points). + */ + midpoint(): Position; } interface EdgeSingularTraversing { /** @@ -2457,7 +2711,7 @@ declare namespace cytoscape { * @param eles The other collection. * @param selector The other collection, specified as a selector which is matched against all elements in the graph. */ - edgesWith(eles: Collection | Selector): EdgeCollection; + edgesWith(eles: CollectionArgument | Selector): EdgeCollection; /** * Get the edges coming from the collection (i.e. the source) going to another collection (i.e. the target). @@ -2465,7 +2719,7 @@ declare namespace cytoscape { * @param eles The other collection. * @param selector The other collection, specified as a selector which is matched against all elements in the graph. */ - edgesTo(eles: Collection | Selector): EdgeCollection; + edgesTo(eles: CollectionArgument | Selector): EdgeCollection; /** * Get the edges connected to the nodes in the collection. @@ -2537,7 +2791,7 @@ declare namespace cytoscape { /** * The root nodes (selector or collection) to start the search from. */ - roots: Selector | Collection; + roots: Selector | CollectionArgument; /** * A handler function that is called when a node is visited in the search. */ @@ -2552,7 +2806,7 @@ declare namespace cytoscape { * The path of the search. * - The path returned includes edges such that if path[i] is a node, then path[i - 1] is the edge used to get to that node. */ - path: CollectionElements; + path: CollectionArgument; /** * The node found by the search * - If no node was found, then found is empty. @@ -2568,7 +2822,7 @@ declare namespace cytoscape { /** * The root node (selector or collection) where the algorithm starts. */ - root: Selector | Collection; + root: Selector | CollectionArgument; /** * A function that returns the positive numeric weight for this edge. @@ -2596,14 +2850,14 @@ declare namespace cytoscape { * The path starts with the source node and includes the edges between the nodes in the path such that if pathTo(node)[i] is an edge, * then pathTo(node)[i-1] is the previous node in the path and pathTo(node)[i+1] is the next node in the path. */ - pathTo(node: NodeSingular): Collection; + pathTo(node: NodeSingular): CollectionReturnValue; } /** * http://js.cytoscape.org/#eles.aStar */ interface SearchAStarOptions { - root: Selector | Collection; - goal: Selector | Collection; + root: Selector | CollectionArgument; + goal: Selector | CollectionArgument; weight?: WeightFn; heuristic?(node: NodeCollection): number; directed?: boolean; @@ -2614,7 +2868,7 @@ declare namespace cytoscape { interface SearchAStarResult { found: boolean; distance: number; - path: Collection; + path: CollectionReturnValue; } /** @@ -2641,7 +2895,7 @@ declare namespace cytoscape { * then pathTo(node)[i-1] is the previous node in the path and pathTo(node)[i+1] * is the next node in the path. */ - path(fromNode: NodeSingular | CollectionSelection, toNode: NodeSingular | Selector): Collection; + path(fromNode: NodeSingular | CollectionSelection, toNode: NodeSingular | Selector): CollectionReturnValue; } /** @@ -2670,7 +2924,7 @@ declare namespace cytoscape { * function that computes the shortest path from root node to the argument node * (either objects or selector string) */ - pathTo(node: NodeSingular | Selector): Collection; + pathTo(node: NodeSingular | Selector): CollectionReturnValue; /** * function that computes the shortest distance from root node to argument node @@ -4368,13 +4622,13 @@ declare namespace cytoscape { * Start running the layout * http://js.cytoscape.org/#layout.run */ - run(): void; - start(): void; + run(): this; + start(): this; /** * Stop running the (asynchronous/discrete) layout * http://js.cytoscape.org/#layout.stop */ - stop(): void; + stop(): this; } interface LayoutEvents { /** diff --git a/types/d3/v3/index.d.ts b/types/d3/v3/index.d.ts index 9a2f9ae34a..9f32212f6b 100644 --- a/types/d3/v3/index.d.ts +++ b/types/d3/v3/index.d.ts @@ -3277,7 +3277,7 @@ declare namespace d3 { round(round: boolean): Treemap; sticky(): boolean; - sticky(sticky: boolean): boolean; + sticky(sticky: boolean): Treemap; mode(): string; mode(mode: "squarify"): Treemap; diff --git a/types/decompress/decompress-tests.ts b/types/decompress/decompress-tests.ts old mode 100644 new mode 100755 index 9cb8949d99..5ed96c0b46 --- a/types/decompress/decompress-tests.ts +++ b/types/decompress/decompress-tests.ts @@ -19,3 +19,24 @@ decompress('unicorn.zip', 'dist', { }).then((files: decompress.File[]) => { console.log('done!'); }); + +// Test decompress with no output to filesystem +decompress('unicorn.zip') + .then( + (files: decompress.File[]) => { + console.log(`Decompressed ${files.length} files with no write to filesystem`); + } + ); + +// Test decompress with DecompressOptions as second argument +decompress( + 'unicorn.zip', + { + filter: file => path.extname(file.path) !== '.exe' + } +) + .then( + (files: decompress.File[]) => { + console.log(`Decompressed ${files.length} files with filter options`); + } + ); diff --git a/types/decompress/index.d.ts b/types/decompress/index.d.ts old mode 100644 new mode 100755 index 745bebcd2e..2c4f464558 --- a/types/decompress/index.d.ts +++ b/types/decompress/index.d.ts @@ -1,13 +1,14 @@ // Type definitions for decompress 4.2 // Project: https://github.com/kevva/decompress#readme // Definitions by: York Yao +// Jesse Bethke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// export = decompress; -declare function decompress(input: string | Buffer, output: string, opts?: decompress.DecompressOptions): Promise; +declare function decompress(input: string | Buffer, output?: string | decompress.DecompressOptions, opts?: decompress.DecompressOptions): Promise; declare namespace decompress { interface File { diff --git a/types/ethereumjs-util/index.d.ts b/types/ethereumjs-util/index.d.ts index eb47d3a6a9..c5ae356f5b 100644 --- a/types/ethereumjs-util/index.d.ts +++ b/types/ethereumjs-util/index.d.ts @@ -1,15 +1,15 @@ -// Type definitions for ethereumjs-util 5.1 +// Type definitions for ethereumjs-util 5.2 // Project: https://github.com/ethereumjs/ethereumjs-util#readme // Definitions by: Juan J. Jimenez-Anca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -// TODO: import types for [`BN`](https://github.com/indutny/bn.js) -// TODO: MAX_INTEGER as type of BN // TODO: import types for [`rlp`](https://github.com/ethereumjs/rlp) // TODO: import types for [`secp256k1`](https://github.com/cryptocoinjs/secp256k1-node/) +import BN = require("bn.js"); + export const SHA3_NULL_S: string; export const SHA3_RLP_ARRAY_S: string; @@ -18,13 +18,11 @@ export const SHA3_RLP_S: string; export function addHexPrefix(str: string): string; -export function arrayContainsArray(superset: any, subset: any, some: any): any; - -export function baToJSON(ba: Buffer | Uint8Array | string[]): Buffer | Uint8Array | string[]; +export function baToJSON(ba: Buffer | Uint8Array | string[]): Buffer | Uint8Array | string[] | null; export function bufferToHex(buf: Buffer | Uint8Array): string; -export function bufferToInt(buf: Buffer | Uint8Array): string; +export function bufferToInt(buf: Buffer | Uint8Array): number; export function defineProperties(self: {[k: string]: any}, fields: string[], data: {[k: string]: any}): {[k: string]: any}; @@ -34,14 +32,16 @@ export function ecsign(msgHash: Buffer | Uint8Array, privateKey: Buffer | Uint8A export function fromRpcSig(sig: string): {[k: string]: any}; -export function fromSigned(num: Buffer | Uint8Array): any; +export function fromSigned(num: Buffer | Uint8Array): BN; export function generateAddress(from: Buffer | Uint8Array, nonce: Buffer | Uint8Array): Buffer | Uint8Array; -export function hashPersonalMessage(message: string): Buffer | Uint8Array; +export function hashPersonalMessage(message: Buffer | Uint8Array | any[]): Buffer | Uint8Array; export function importPublic(publicKey: Buffer | Uint8Array): Buffer | Uint8Array; +export function isPrecompiled(address: Buffer | Uint8Array): boolean; + export function isValidAddress(address: string): boolean; export function isValidChecksumAddress(address: Buffer | Uint8Array): boolean; @@ -52,11 +52,17 @@ export function isValidPublic(publicKey: Buffer | Uint8Array, sanitize?: boolean export function isValidSignature(v: Buffer | Uint8Array, r: Buffer | Uint8Array, s: Buffer | Uint8Array, homestead?: boolean): boolean; +export function isZeroAddress(address: string): boolean; + +export function keccak(a: Buffer | Uint8Array | any[] | string | number, bits?: number): Buffer | Uint8Array; + +export function keccak256(a: Buffer | Uint8Array | any[] | string | number): Buffer | Uint8Array; + export function privateToAddress(privateKey: Buffer | Uint8Array): Buffer | Uint8Array; export function privateToPublic(privateKey: Buffer | Uint8Array): Buffer | Uint8Array; -export function pubToAddress(pubKey: Buffer | Uint8Array, sanitize: boolean): Buffer | Uint8Array; +export function pubToAddress(pubKey: Buffer | Uint8Array, sanitize?: boolean): Buffer | Uint8Array; export function ripemd160(a: Buffer | Uint8Array | any[] | string | number, padded: boolean): Buffer | Uint8Array; @@ -76,8 +82,10 @@ export function toChecksumAddress(address: string): string; export function toRpcSig(v: number, r: Buffer | Uint8Array, s: Buffer | Uint8Array): string; -export function toUnsigned(num: any): Buffer | Uint8Array; +export function toUnsigned(num: BN): Buffer | Uint8Array; export function unpad(a: T): T; export function zeros(bytes: number): Buffer | Uint8Array; + +export function zeroAddress(): string; diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index e556e5255a..048d7b884d 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -7,6 +7,7 @@ // Fernando Helwanger // Umidbek Karimov // Moshe Feuchtwanger +// Michael Prokopchuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -1390,12 +1391,24 @@ export namespace Font { } // #region GLView +export interface ExpoWebGLRenderingContext extends WebGLRenderingContext { + endFrameEXP(): void; +} + /** - * GLView + * A View that acts as an OpenGL ES render target. On mounting, an OpenGL ES + * context is created. Its drawing buffer is presented as the contents of + * the View every frame. */ export interface GLViewProps extends ViewProps { - onContextCreate(): void; - msaaSamples: number; + /** + * A function that will be called when the OpenGL ES context is created. + * Passes an object with a WebGLRenderingContext interface as an argument. + */ + onContextCreate(gl: ExpoWebGLRenderingContext): void; + + /** Number of MSAA samples to use on iOS. Defaults to 4. Ignored on Android. */ + msaaSamples?: number; } export class GLView extends Component { } diff --git a/types/google-apps-script/google-apps-script.card.d.ts b/types/google-apps-script/google-apps-script.card.d.ts index 62d497eb4f..d879d30091 100644 --- a/types/google-apps-script/google-apps-script.card.d.ts +++ b/types/google-apps-script/google-apps-script.card.d.ts @@ -82,6 +82,10 @@ declare namespace GoogleAppsScript { * Sets the URL to navigate to when the action is activated. */ setOpenLink(openLink: OpenLink): ActionResponseBuilder; + /** + * Sets a flag to indicate that this action changed the existing data state. + */ + setStateChanged(stateChanged: boolean): ActionResponseBuilder; } export interface AuthorizationAction { diff --git a/types/iframe-resizer/index.d.ts b/types/iframe-resizer/index.d.ts index 3858cab780..6e67a5b592 100644 --- a/types/iframe-resizer/index.d.ts +++ b/types/iframe-resizer/index.d.ts @@ -32,6 +32,11 @@ export interface IFrameOptions { * CSS margin attribute, for example '8px 3em'. A number value is converted into px. */ bodyMargin?: number | string; + /** + * Override the default body padding style in the iFrame. A string can be any valid value for the + * CSS margin attribute, for example '8px 3em'. A number value is converted into px. + */ + bodyPadding?: number | string; /** * When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag. * If your iFrame navigates between different domains, ports or protocols; then you will need to diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 2afe0eb750..4a2153b218 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jest 23.0 +// Type definitions for Jest 23.1 // Project: http://facebook.github.io/jest/ // Definitions by: Asana // Ivo Stratev @@ -12,9 +12,9 @@ // Douglas Duteil // Ahn // Josh Goldberg -// Bradley Ayers // Jeff Lau // Andrew Makarov +// Martin Hochel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -873,6 +873,164 @@ declare namespace jest { type SnapshotUpdateState = 'all' | 'new' | 'none'; + interface DefaultOptions { + automock: boolean; + bail: boolean; + browser: boolean; + cache: boolean; + cacheDirectory: Path; + changedFilesWithAncestor: boolean; + clearMocks: boolean; + collectCoverage: boolean; + collectCoverageFrom: Maybe; + coverageDirectory: Maybe; + coveragePathIgnorePatterns: string[]; + coverageReporters: string[]; + coverageThreshold: Maybe<{global: {[key: string]: number}}>; + errorOnDeprecated: boolean; + expand: boolean; + filter: Maybe; + forceCoverageMatch: Glob[]; + globals: ConfigGlobals; + globalSetup: Maybe; + globalTeardown: Maybe; + haste: HasteConfig; + detectLeaks: boolean; + detectOpenHandles: boolean; + moduleDirectories: string[]; + moduleFileExtensions: string[]; + moduleNameMapper: {[key: string]: string}; + modulePathIgnorePatterns: string[]; + noStackTrace: boolean; + notify: boolean; + notifyMode: string; + preset: Maybe; + projects: Maybe>; + resetMocks: boolean; + resetModules: boolean; + resolver: Maybe; + restoreMocks: boolean; + rootDir: Maybe; + roots: Maybe; + runner: string; + runTestsByPath: boolean; + setupFiles: Path[]; + setupTestFrameworkScriptFile: Maybe; + skipFilter: boolean; + snapshotSerializers: Path[]; + testEnvironment: string; + testEnvironmentOptions: object; + testFailureExitCode: string | number; + testLocationInResults: boolean; + testMatch: Glob[]; + testPathIgnorePatterns: string[]; + testRegex: string; + testResultsProcessor: Maybe; + testRunner: Maybe; + testURL: string; + timers: 'real' | 'fake'; + transform: Maybe<{[key: string]: string}>; + transformIgnorePatterns: Glob[]; + watchPathIgnorePatterns: string[]; + useStderr: boolean; + verbose: Maybe; + watch: boolean; + watchman: boolean; + } + + interface InitialOptions { + automock?: boolean; + bail?: boolean; + browser?: boolean; + cache?: boolean; + cacheDirectory?: Path; + clearMocks?: boolean; + changedFilesWithAncestor?: boolean; + changedSince?: string; + collectCoverage?: boolean; + collectCoverageFrom?: Glob[]; + collectCoverageOnlyFrom?: {[key: string]: boolean}; + coverageDirectory?: string; + coveragePathIgnorePatterns?: string[]; + coverageReporters?: string[]; + coverageThreshold?: {global: {[key: string]: number}}; + detectLeaks?: boolean; + detectOpenHandles?: boolean; + displayName?: string; + expand?: boolean; + filter?: Path; + findRelatedTests?: boolean; + forceCoverageMatch?: Glob[]; + forceExit?: boolean; + json?: boolean; + globals?: ConfigGlobals; + globalSetup?: Maybe; + globalTeardown?: Maybe; + haste?: HasteConfig; + reporters?: Array; + logHeapUsage?: boolean; + lastCommit?: boolean; + listTests?: boolean; + mapCoverage?: boolean; + moduleDirectories?: string[]; + moduleFileExtensions?: string[]; + moduleLoader?: Path; + moduleNameMapper?: {[key: string]: string}; + modulePathIgnorePatterns?: string[]; + modulePaths?: string[]; + name?: string; + noStackTrace?: boolean; + notify?: boolean; + notifyMode?: string; + onlyChanged?: boolean; + outputFile?: Path; + passWithNoTests?: boolean; + preprocessorIgnorePatterns?: Glob[]; + preset?: Maybe; + projects?: Glob[]; + replname?: Maybe; + resetMocks?: boolean; + resetModules?: boolean; + resolver?: Maybe; + restoreMocks?: boolean; + rootDir?: Path; + roots?: Path[]; + runner?: string; + runTestsByPath?: boolean; + scriptPreprocessor?: string; + setupFiles?: Path[]; + setupTestFrameworkScriptFile?: Path; + silent?: boolean; + skipFilter?: boolean; + skipNodeResolution?: boolean; + snapshotSerializers?: Path[]; + errorOnDeprecated?: boolean; + testEnvironment?: string; + testEnvironmentOptions?: object; + testFailureExitCode?: string | number; + testLocationInResults?: boolean; + testMatch?: Glob[]; + testNamePattern?: string; + testPathDirs?: Path[]; + testPathIgnorePatterns?: string[]; + testRegex?: string; + testResultsProcessor?: Maybe; + testRunner?: string; + testURL?: string; + timers?: 'real' | 'fake'; + transform?: {[key: string]: string}; + transformIgnorePatterns?: Glob[]; + watchPathIgnorePatterns?: string[]; + unmockedModulePathPatterns?: string[]; + updateSnapshot?: boolean; + useStderr?: boolean; + verbose?: Maybe; + watch?: boolean; + watchAll?: boolean; + watchman?: boolean; + watchPlugins?: string[]; + } + interface GlobalConfig { bail: boolean; collectCoverage: boolean; diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index bfaaec6259..bf1620f313 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -617,126 +617,132 @@ describe("", () => { /* Test framework and config */ +const globalConfig: jest.GlobalConfig = { + bail: true, + collectCoverage: false, + collectCoverageFrom: ["glob"], + collectCoverageOnlyFrom: { + abc: true, + def: false, + }, + coverageDirectory: "", + coverageReporters: [""], + coverageThreshold: { + global: { + abc: 90, + def: 100, + }, + }, + expand: true, + forceExit: false, + logHeapUsage: true, + mapCoverage: false, + noStackTrace: true, + notify: false, + projects: ["projects"], + replname: "", + reporters: [ + ["abc", {}], + ["def", {}], + ], + rootDir: "path", + silent: true, + testNamePattern: "", + testPathPattern: "", + testResultsProcessor: "", + updateSnapshot: "all" as "all" | "new" | "none", + useStderr: true, + verbose: false, + watch: true, + watchman: false, +}; + +const projectConfig: jest.ProjectConfig = { + automock: true, + browser: false, + cache: true, + cacheDirectory: "", + clearMocks: true, + coveragePathIgnorePatterns: [""], + cwd: "", + detectLeaks: true, + displayName: "", + forceCoverageMatch: ["abc", "def"], + globals: { + "ts-jest": {}, + }, + haste: { + defaultPlatform: "", + hasteImplModulePath: "", + platforms: ["win95", "win2000", "clippy"], + providesModuleNodeModules: ["abc", "def"], + }, + moduleDirectories: ["", ""], + moduleFileExtensions: [".ts", ".json"], + moduleLoader: "laoder", + moduleNameMapper: [ + ["abc", "def"], + ["ghi", "jkl"], + ], + modulePathIgnorePatterns: ["abc", "def"], + modulePaths: ["abc", "def"], + name: "", + resetMocks: true, + resetModules: false, + resolver: "", + rootDir: "", + roots: ["", ""], + runner: "", + setupFiles: ["abc", "def"], + setupTestFrameworkScriptFile: "", + skipNodeResolution: true, + snapshotSerializers: ["abc", "def"], + testEnvironment: "", + testEnvironmentOptions: {}, + testLocationInResults: true, + testMatch: [".test.ts"], + testPathIgnorePatterns: ["*.spec.*"], + testRegex: "abc", + testRunner: "m", + testURL: "localhost:3000", + timers: "real", + transform: [ + ["abc", "def"], + ], + transformIgnorePatterns: ["", ""], + unmockedModulePathPatterns: ["abc"], + watchPathIgnorePatterns: ["def"], +}; + +const environment = { + global: {}, + fakeTimers: { + clearAllTimers() { }, + runAllImmediates() { }, + runAllTicks() { }, + runAllTimers() { }, + runTimersToTime(time: number) { }, + advanceTimersByTime(time: number) { }, + runOnlyPendingTimers() { }, + runWithRealTimers(callback: () => void) { + callback(); + }, + useFakeTimers() { }, + useRealTimers() { }, + }, + testFilePath: "", + moduleMocker: {}, + dispose() {}, + runScript(script: "") { + return {}; + }, +}; + const workTestFramework = async (testFramework: jest.TestFramework): Promise => { return testFramework( - { - bail: true, - collectCoverage: false, - collectCoverageFrom: ["glob"], - collectCoverageOnlyFrom: { - abc: true, - def: false, - }, - coverageDirectory: "", - coverageReporters: [""], - coverageThreshold: { - global: { - abc: 90, - def: 100, - }, - }, - expand: true, - forceExit: false, - logHeapUsage: true, - mapCoverage: false, - noStackTrace: true, - notify: false, - projects: ["projects"], - replname: "", - reporters: [ - ["abc", {}], - ["def", {}], - ], - rootDir: "path", - silent: true, - testNamePattern: "", - testPathPattern: "", - testResultsProcessor: "", - updateSnapshot: "all" as "all" | "new" | "none", - useStderr: true, - verbose: false, - watch: true, - watchman: false, - }, - { - automock: true, - browser: false, - cache: true, - cacheDirectory: "", - clearMocks: true, - coveragePathIgnorePatterns: [""], - cwd: "", - detectLeaks: true, - displayName: "", - forceCoverageMatch: ["abc", "def"], - globals: { - "ts-jest": {}, - }, - haste: { - defaultPlatform: "", - hasteImplModulePath: "", - platforms: ["win95", "win2000", "clippy"], - providesModuleNodeModules: ["abc", "def"], - }, - moduleDirectories: ["", ""], - moduleFileExtensions: [".ts", ".json"], - moduleLoader: "laoder", - moduleNameMapper: [ - ["abc", "def"], - ["ghi", "jkl"], - ], - modulePathIgnorePatterns: ["abc", "def"], - modulePaths: ["abc", "def"], - name: "", - resetMocks: true, - resetModules: false, - resolver: "", - rootDir: "", - roots: ["", ""], - runner: "", - setupFiles: ["abc", "def"], - setupTestFrameworkScriptFile: "", - skipNodeResolution: true, - snapshotSerializers: ["abc", "def"], - testEnvironment: "", - testEnvironmentOptions: {}, - testLocationInResults: true, - testMatch: [".test.ts"], - testPathIgnorePatterns: ["*.spec.*"], - testRegex: "abc", - testRunner: "m", - testURL: "localhost:3000", - timers: "real", - transform: [ - ["abc", "def"], - ], - transformIgnorePatterns: ["", ""], - unmockedModulePathPatterns: ["abc"], - watchPathIgnorePatterns: ["def"], - }, - { - global: {}, - fakeTimers: { - clearAllTimers() { }, - runAllImmediates() { }, - runAllTicks() { }, - runAllTimers() { }, - runTimersToTime(time: number) { }, - advanceTimersByTime(time: number) { }, - runOnlyPendingTimers() { }, - runWithRealTimers(callback: () => void) { - callback(); - }, - useFakeTimers() { }, - useRealTimers() { }, - }, - testFilePath: "", - moduleMocker: {}, - dispose() {}, - runScript(script: "") { - return {}; - }, - }, + globalConfig, + projectConfig, + environment, {}, "testPath" ); @@ -932,4 +938,21 @@ let matchersUtil2: jasmine.MatchersUtil = { equals: (a: {}, b: {}, customTesters?: jasmine.CustomEqualityTester[]) => false, }; -matchersUtil2 = matchersUtil1; +// Jest config + +const testJestConfig = (defaults: jest.DefaultOptions) => { + const config: jest.InitialOptions = { + transform: { + '^.+\\.(ts|tsx)$': 'ts-jest' + }, + testMatch: [ + ...defaults.testMatch, + '**/__tests__/**/*.ts?(x)', + '**/?(*.)+(spec|test).ts?(x)' + ], + moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'], + globals: { + 'ts-jest': {} + } + }; +}; diff --git a/types/jquery-mockjax/index.d.ts b/types/jquery-mockjax/index.d.ts index 54cc036416..f1333b1028 100644 --- a/types/jquery-mockjax/index.d.ts +++ b/types/jquery-mockjax/index.d.ts @@ -1,11 +1,28 @@ -// Type definitions for jQuery Mockjax 2.0.1 +// Type definitions for jQuery Mockjax 2.3.0 // Project: https://github.com/jakerella/jquery-mockjax -// Definitions by: Laszlo Jakab , Vladimir Đokić +// Definitions by: +// Laszlo Jakab , +// Vladimir Đokić , +// James Johnson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// +type MockJaxLoggingFunction = (message?: any, ...additionalParameters: any[]) => void; + +interface MockJaxStandardLogger { + error?: MockJaxLoggingFunction; + warn?: MockJaxLoggingFunction; + info?: MockJaxLoggingFunction; + log?: MockJaxLoggingFunction; + debug?: MockJaxLoggingFunction; +} + +interface MockJaxCustomLogger { + [key: string]: MockJaxLoggingFunction; +} + interface MockJaxSettingsHeaders { [key: string]: string; } @@ -33,15 +50,22 @@ interface MockJaxSettings { onAfterSuccess?: Function; onAfterError?: Function; onAfterComplete?: Function; + logger?: MockJaxStandardLogger | MockJaxCustomLogger; + logLevelMethods?: string[]; + namespace?: string; + throwUnmocked?: boolean; + retainAjaxCalls?: boolean; } interface MockJaxStatic { (options: MockJaxSettings): number; + (options: MockJaxSettings[]): number[]; handler(id?: number): any; clear(id?: number): void; mockedAjaxCalls(): any[]; unfiredHandlers(): any[]; unmockedAjaxCalls(): any[]; + clearRetainedAjaxCalls(): void; } interface JQueryStatic { diff --git a/types/jquery-mockjax/jquery-mockjax-tests.ts b/types/jquery-mockjax/jquery-mockjax-tests.ts index 3090a1c3cc..31babd9cd8 100644 --- a/types/jquery-mockjax/jquery-mockjax-tests.ts +++ b/types/jquery-mockjax/jquery-mockjax-tests.ts @@ -192,6 +192,81 @@ class Tests { } }); }); + + t('Standard logger type gets called', (assert) => { + let done = assert.async(); + let wasLoggerCalled = false; + + let logFunction = () => wasLoggerCalled = true; + + let settings: MockJaxSettings = { + url: '/custom-logging-function', + logging: true, + logger: { + error: logFunction, + warn: logFunction, + info: logFunction, + log: logFunction, + debug: logFunction + } + }; + + $.mockjax(settings); + + $.ajax({ + url: '/custom-logging-function', + error: self._noErrorCallbackExpected, + complete: (xhr) => { + assert.equal(wasLoggerCalled, true, 'Standard logger was called'); + done(); + } + }); + }); + + t('Custom logger object gets called', (assert) => { + let done = assert.async(); + let wasLoggerCalled = false; + + let logFunction = () => wasLoggerCalled = true; + + let settings: MockJaxSettings = { + url: '/custom-logging-function', + logging: true, + logger: { + customName: logFunction + }, + logLevelMethods: ['customName', 'customName', 'customName', 'customName', 'customName'] + }; + + $.mockjax(settings); + + $.ajax({ + url: '/custom-logging-function', + error: self._noErrorCallbackExpected, + complete: (xhr) => { + assert.equal(wasLoggerCalled, true, 'Custom logger was called'); + done(); + } + }); + }); + + t('Throws when ajax call is not mocked', (assert) => { + let done = assert.async(); + + $.mockjaxSettings.throwUnmocked = true; + + $.ajax({ + url: '/unmocked-ajax-call', + error: (error) => { + assert.ok(error, 'Expected the call to fail because it was not mocked'); + done(); + }, + complete: (xhr) => { + assert.ok(false, 'Expected a failure'); + done(); + } + }); + }); } } diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index d90ba90b13..94623c5abb 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -208,6 +208,7 @@ declare module 'luxon' { toLocaleParts(options?: DateTimeFormatOptions): any[]; toLocaleString(options?: DateTimeFormatOptions): string; toObject(options?: { includeConfig?: boolean }): DateObject; + toMillis(): number; toRFC2822(): string; toSQL(options?: Object): string; toSQLDate(): string; diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index ce9d09ac8f..4396e8d7a2 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -54,6 +54,8 @@ DateTime.utc(); DateTime.local().toUTC(); DateTime.utc().toLocal(); +DateTime.fromMillis(1527780819458).toMillis(); + /* Duration */ const dur = Duration.fromObject({ hours: 2, minutes: 7 }); dt.plus(dur); diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index cdecc3e1b4..886e6da20e 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -36,6 +36,7 @@ declare namespace math { // tslint:disable-line strict-export-declare-modifiers version: string; expression: MathNode; + json: MathJsJson; config: (options: any) => void; @@ -543,7 +544,7 @@ declare namespace math { // tslint:disable-line strict-export-declare-modifiers /** * Create a number or convert a string, boolean, or unit to a number. When value is a matrix, all elements will be converted to number. */ - number(value?: string|number|boolean|MathArray|Matrix|Unit|BigNumber): number|MathArray|Matrix; + number(value?: string|number|boolean|MathArray|Matrix|Unit|BigNumber|Fraction): number|MathArray|Matrix; number(unit: Unit, valuelessUnit: Unit|string): number|MathArray|Matrix; /** @@ -2249,4 +2250,11 @@ declare namespace math { // tslint:disable-line strict-export-declare-modifiers valueOf(): any; toString(): string; } + + interface MathJsJson { + /** + * Returns reviver function that can be used as reviver in JSON.parse function. + */ + reviver(): (key: any, value: any) => any; + } } diff --git a/types/mathjs/mathjs-tests.ts b/types/mathjs/mathjs-tests.ts index 6cf43dc698..09202e0599 100644 --- a/types/mathjs/mathjs-tests.ts +++ b/types/mathjs/mathjs-tests.ts @@ -365,3 +365,15 @@ Expression tree examples } }); } + +/* +JSON serialization/deserialization +*/ +{ + const data = { + bigNumber: math.bignumber('1.5') + }; + const stringified = JSON.stringify(data); + const parsed = JSON.parse(stringified, math.json.reviver); + parsed.bigNumber === math.bignumber('1.5'); // true +} diff --git a/types/meteor/meteor-tests.ts b/types/meteor/meteor-tests.ts index f9cf039c84..a321e4a409 100644 --- a/types/meteor/meteor-tests.ts +++ b/types/meteor/meteor-tests.ts @@ -781,3 +781,8 @@ DDPRateLimiter.addRule({ userId: 'foo' }, 5, 1000); DDPRateLimiter.addRule({ userId: userId => userId == 'foo' }, 5, 1000); Template.instance().autorun(() => { }).stop(); + +// Mongo Collection without connection (local collection) +const collectionWithoutConnection = new Mongo.Collection("monkey", { + connection: null +}); diff --git a/types/meteor/mongo.d.ts b/types/meteor/mongo.d.ts index 248f5a22af..771d24edc1 100644 --- a/types/meteor/mongo.d.ts +++ b/types/meteor/mongo.d.ts @@ -124,7 +124,7 @@ declare module Mongo { var Collection: CollectionStatic; interface CollectionStatic { new (name: string, options?: { - connection?: Object; + connection?: Object | null; idGeneration?: string; transform?: Function; }): Collection; @@ -348,7 +348,7 @@ declare module "meteor/mongo" { var Collection: CollectionStatic; interface CollectionStatic { new (name: string, options?: { - connection?: Object; + connection?: Object | null; idGeneration?: string; transform?: Function; }): Collection; diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 59a5c95989..a94f3a691d 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -103,7 +103,10 @@ declare module "mongoose" { export function createConnection(): Connection; export function createConnection(uri: string, options?: ConnectionOptions - ): Connection; + ): Connection & { + then: Promise["then"]; + catch: Promise["catch"]; + }; /** * Disconnects all connections. @@ -201,7 +204,7 @@ declare module "mongoose" { */ open(connection_string: string, database?: string, port?: number, options?: ConnectionOpenOptions, callback?: (err: any) => void): any; - + /** * Opens the connection to MongoDB. * @param mongodb://uri or the host to which you are connecting @@ -451,9 +454,6 @@ declare module "mongoose" { /** Expose the possible connection states. */ static STATES: any; - - then: Promise["then"]; - catch: Promise["catch"]; } /* @@ -2727,9 +2727,9 @@ declare module "mongoose" { * This function does not trigger save middleware. * @param docs Documents to insert. * @param options Optional settings. - * @param options.ordered if true, will fail fast on the first error encountered. + * @param options.ordered if true, will fail fast on the first error encountered. * If false, will insert all the documents it can and report errors later. - * @param options.rawResult if false, the returned promise resolves to the documents that passed mongoose document validation. + * @param options.rawResult if false, the returned promise resolves to the documents that passed mongoose document validation. * If `false`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback) * with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`. */ diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 90b6fc2561..90259483f2 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -161,6 +161,13 @@ mongoose.Connection.STATES.hasOwnProperty(''); conn1.on('data', cb); conn1.addListener('close', cb); +// The connection returned by useDb is *not* thenable. +// From https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26057#issuecomment-396150819 +const getDB = async (tenant: string)=> { + return conn1.useDb(tenant); +}; + + /* * section error/validation.js * http://mongoosejs.com/docs/api.html#error-validation-js diff --git a/types/multer/index.d.ts b/types/multer/index.d.ts index d019b9fdcb..7d2bfefc26 100644 --- a/types/multer/index.d.ts +++ b/types/multer/index.d.ts @@ -71,6 +71,8 @@ declare namespace multer { fields(fields: Field[]): express.RequestHandler; /** Accepts all files that comes over the wire. An array of files will be stored in req.files. */ any(): express.RequestHandler; + /** Accept only text fields. If any file upload is made, error with code “LIMIT_UNEXPECTED_FILE” will be issued. This is the same as doing upload.fields([]). */ + none(): express.RequestHandler; } } diff --git a/types/next/app.d.ts b/types/next/app.d.ts new file mode 100644 index 0000000000..18bca653cf --- /dev/null +++ b/types/next/app.d.ts @@ -0,0 +1,18 @@ +import * as React from "react"; +import { NextContext } from "."; +import { SingletonRouter } from "./router"; + +export interface AppComponentProps { + Component: React.ComponentType; + pageProps: any; +} + +export interface AppComponentContext { + Component: React.ComponentType; + router: SingletonRouter; + ctx: NextContext; +} + +export class Container extends React.Component {} + +export default class App extends React.Component {} diff --git a/types/next/document.d.ts b/types/next/document.d.ts index b8ae0864ba..38e20e00c0 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -1,30 +1,5 @@ import * as React from "react"; -import * as http from "http"; - -export interface Context { - err?: Error; - req: http.IncomingMessage; - res: http.ServerResponse; - pathname: string; - query?: { - [key: string]: - | boolean - | boolean[] - | number - | number[] - | string - | string[]; - }; - asPath: string; - - renderPage( - enhancer?: (page: React.Component) => React.ComponentType - ): { - html?: string; - head: Array>; - errorHtml: string; - }; -} +import { NextContext } from "."; export interface DocumentProps { __NEXT_DATA__?: any; @@ -38,9 +13,21 @@ export interface DocumentProps { [key: string]: any; } +/** + * Context object used inside `Document` + */ +export interface NextDocumentContext extends NextContext { + /** A callback that executes the actual React rendering logic (synchronously) */ + renderPage( + cb?: (enhancer: () => JSX.Element) => React.ComponentType + ): { + [key: string]: any + }; +} + export class Head extends React.Component {} export class Main extends React.Component {} export class NextScript extends React.Component {} export default class extends React.Component { - static getInitialProps(ctx: Context): DocumentProps; + static getInitialProps(ctx: NextContext): DocumentProps; } diff --git a/types/next/index.d.ts b/types/next/index.d.ts index fe44537f5f..95395bc2b8 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -1,7 +1,9 @@ -// Type definitions for next 2.4 +// Type definitions for next 6.0 // Project: https://github.com/zeit/next.js // Definitions by: Drew Hays // Brice BERNARD +// James Hegedus +// Resi Respati // Scott Jones // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -11,7 +13,44 @@ import * as http from "http"; import * as url from "url"; +import { Response as NodeResponse } from "node-fetch"; + declare namespace next { + /** + * Context object used in methods like `getInitialProps()` + * <> + */ + interface NextContext { + /** path section of URL */ + pathname: string; + /** query string section of URL parsed as an object */ + query: { + [key: string]: + | boolean + | boolean[] + | number + | number[] + | string + | string[]; + }; + /** String of the actual path (including the query) shows in the browser */ + asPath: string; + /** HTTP request object (server only) */ + req?: http.IncomingMessage; + /** HTTP response object (server only) */ + res?: http.ServerResponse; + /** Fetch Response object (client only) - from https://developer.mozilla.org/en-US/docs/Web/API/Response */ + jsonPageRes?: NodeResponse; + /** Error object if any error is encountered during the rendering */ + err?: Error; + } + + type NextSFC = NextStatelessComponent; + interface NextStatelessComponent + extends React.StatelessComponent { + getInitialProps?: (ctx: NextContext) => Promise; + } + type UrlLike = url.UrlObject | url.Url; interface ServerConfig { @@ -41,12 +80,12 @@ declare namespace next { handleRequest( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ): Promise; getRequestHandler(): ( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ) => Promise; prepare(): Promise; close(): Promise; @@ -55,7 +94,7 @@ declare namespace next { run( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl: UrlLike, + parsedUrl: UrlLike ): Promise; render( @@ -71,7 +110,7 @@ declare namespace next { | string | string[]; }, - parsedUrl?: UrlLike, + parsedUrl?: UrlLike ): Promise; renderError( err: any, @@ -86,12 +125,12 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; render404( req: http.IncomingMessage, res: http.ServerResponse, - parsedUrl: UrlLike, + parsedUrl: UrlLike ): Promise; renderToHTML( req: http.IncomingMessage, @@ -105,7 +144,7 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; renderErrorToHTML( err: any, @@ -120,13 +159,13 @@ declare namespace next { | number[] | string | string[]; - }, + } ): Promise; serveStatic( req: http.IncomingMessage, res: http.ServerResponse, - path: string, + path: string ): Promise; isServeableUrl(path: string): boolean; isInternalUrl(req: http.IncomingMessage): boolean; @@ -135,12 +174,12 @@ declare namespace next { getCompilationError( page: string, req: http.IncomingMessage, - res: http.ServerResponse, + res: http.ServerResponse ): Promise; handleBuildHash( filename: string, hash: string, - res: http.ServerResponse, + res: http.ServerResponse ): void; send404(res: http.ServerResponse): void; } diff --git a/types/next/test/next-app-tests.tsx b/types/next/test/next-app-tests.tsx new file mode 100644 index 0000000000..3e7c56f87c --- /dev/null +++ b/types/next/test/next-app-tests.tsx @@ -0,0 +1,27 @@ +import * as React from "react"; +import App, { Container } from "next/app"; + +interface NextComponentProps { + example: string; +} + +class TestApp extends App { + static async getInitialProps({ Component, router, ctx }: any) { + let pageProps = {}; + + if (Component.getInitialProps) { + pageProps = await Component.getInitialProps(ctx); + } + + return { pageProps }; + } + + render() { + const { Component, pageProps } = this.props; + return ( + + + + ); + } +} diff --git a/types/next/test/next-component-tests.tsx b/types/next/test/next-component-tests.tsx new file mode 100644 index 0000000000..55173fd25c --- /dev/null +++ b/types/next/test/next-component-tests.tsx @@ -0,0 +1,28 @@ +import * as React from "react"; +import { NextStatelessComponent, NextContext } from "next"; + +interface NextComponentProps { + example: string; +} + +class ClassNext extends React.Component { + static async getInitialProps(ctx: NextContext) { + const { example } = ctx.query; + return { example }; + } + + render() { + return ( +
I'm a class component! {this.props.example}
+ ); + } +} + +const StatelessNext: NextStatelessComponent = ({ example }) => ( +
I'm a stateless component! {example}
+); + +StatelessNext.getInitialProps = async ({ query }: NextContext) => { + const { example } = query; + return { example: example as string }; +}; diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index 0177d1d451..2b3257cd25 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -1,12 +1,40 @@ -import Document, * as document from "next/document"; +import Document, { Head, Main, NextScript, NextDocumentContext } from 'next/document'; import * as React from "react"; const results = ( - + - - - + +
+ ); + +const Wrapper: React.SFC = ({ children }) => {children}; + +export default class MyDocument extends Document { + static async getInitialProps({ renderPage }: NextDocumentContext) { + // Without callback + const page = renderPage(); + // With callback + const differentPage = renderPage(App => props => ); + const style = {}; + return { ...page, style }; + } + + render() { + return ( + + + My page +