diff --git a/README.md b/README.md index 5c218aaa19..279be10799 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Please see the [contribution guide](http://definitelytyped.org/guides/contributi ## Requested definitions -Here is are the [currently requested definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest). +Here are the [currently requested definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest). ## License diff --git a/adal-angular/adal-tests.ts b/adal-angular/adal-tests.ts index 598134d0a0..3b9e46c961 100644 --- a/adal-angular/adal-tests.ts +++ b/adal-angular/adal-tests.ts @@ -12,4 +12,12 @@ var config : adal.Config = { var auth = new AuthenticationContext(config); +Logging.log = (message: string) => { + console.log(message); +} + +Logging.level = 4; + +auth.info("Logging message"); + var userName: string = auth.getCachedUser().userName; \ No newline at end of file diff --git a/adal-angular/adal.d.ts b/adal-angular/adal.d.ts index c5a64efd0b..76b86e7150 100644 --- a/adal-angular/adal.d.ts +++ b/adal-angular/adal.d.ts @@ -4,9 +4,10 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var AuthenticationContext: adal.AuthenticationContextStatic; +declare var Logging: adal.Logging; declare module 'adal' { - export = AuthenticationContext; + export = { AuthenticationContext, Logging }; } declare namespace adal { @@ -36,6 +37,18 @@ declare namespace adal { stateResponse: string, requestType: string } + + interface Logging { + log: (message: string) => void; + level: LoggingLevel; + } + + enum LoggingLevel { + ERROR = 0, + WARNING = 1, + INFO = 2, + VERBOSE = 3 + } interface AuthenticationContextStatic { new (config: Config): AuthenticationContext; diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 045f2f5994..51946281ce 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -72,7 +72,7 @@ declare namespace angular.translate { } interface ITranslateProvider extends angular.IServiceProvider { - translations(): ITranslationTable; + translations(key?: string): ITranslationTable; translations(key: string, translationTable: ITranslationTable): ITranslateProvider; cloakClassName(): string; cloakClassName(name: string): ITranslateProvider; diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index c804519727..7eaf0be763 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -869,7 +869,7 @@ angular.module('docsTabsExample', []) angular.module('componentExample', []) .component('counter', { - require: ['^ctrl'], + require: {'ctrl': '^ctrl'}, bindings: { count: '=' }, diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 94d6678a24..1ae64c8e45 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -156,7 +156,7 @@ declare namespace angular { noop(...args: any[]): void; reloadWithDebugInfo(): void; - toJson(obj: any, pretty?: boolean): string; + toJson(obj: any, pretty?: boolean | number): string; uppercase(str: string): string; version: { full: string; @@ -1716,7 +1716,7 @@ declare namespace angular { * Whether transclusion is enabled. Enabled by default. */ transclude?: boolean | string | {[slot: string]: string}; - require?: string | string[] | {[controller: string]: string}; + require?: {[controller: string]: string}; } interface IComponentTemplateFn { diff --git a/applicationinsights-js/applicationinsights-js-tests.ts b/applicationinsights-js/applicationinsights-js-tests.ts index a852259539..b90ec6c6fe 100644 --- a/applicationinsights-js/applicationinsights-js-tests.ts +++ b/applicationinsights-js/applicationinsights-js-tests.ts @@ -27,7 +27,26 @@ var config: Microsoft.ApplicationInsights.IConfig = { cookieDomain: "" }; -var appInsights = new Microsoft.ApplicationInsights.AppInsights(config); +var appInsights: Microsoft.ApplicationInsights.IAppInsights = { + config: config, + context: null, + queue: null, + + startTrackPage(name?: string) { return null; }, + stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, + trackPageView(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, duration?: number) { return null; }, + startTrackEvent(name: string) { return null }, + stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null }, + trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null }, + trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string) { return null }, + trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null }, + trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null }, + trackTrace(message: string, properties?: { [name: string]: string; }) { return null }, + flush() { return null }, + setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null }, + clearAuthenticatedUserContext() { return null }, + _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { return null } +}; // trackPageView appInsights.trackPageView("page1"); @@ -68,7 +87,7 @@ appInsights.config.instrumentationKey = ""; // TelementryContext -var context = appInsights.context; +var context: Microsoft.ApplicationInsights.ITelemetryContext = appInsights.context; context.application.ver = "v0.0.0"; context.application.build = "1.1.1"; @@ -89,7 +108,7 @@ context.operation.syntheticSource = "testAgent"; // track var data = new Microsoft.Telemetry.Base(); -var envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data, "name"); +var envelope = new Microsoft.Telemetry.Envelope(); context.track(envelope); diff --git a/applicationinsights-js/applicationinsights-js.d.ts b/applicationinsights-js/applicationinsights-js.d.ts index f49863b35a..5bb2a535f9 100644 --- a/applicationinsights-js/applicationinsights-js.d.ts +++ b/applicationinsights-js/applicationinsights-js.d.ts @@ -3,399 +3,297 @@ // Definitions by: Kamil Szostak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module AI { + enum SeverityLevel { + Verbose = 0, + Information = 1, + Warning = 2, + Error = 3, + Critical = 4, + } +} + declare module Microsoft.ApplicationInsights.Context { - class Application { + interface IApplication { /** * The application version. */ ver: string; - /** * The application build version. */ build: string; } - - class Device { + + interface IDevice { /** * The type for the current device. */ type: string; - /** * A device unique ID. */ id: string; - /** * The device OEM for the current device. */ oemName: string; - /** * The device model for the current device. */ model: string; - /** * The IANA interface type for the internet connected network adapter. */ network: number; - /** * The application screen resolution. */ resolution: string; - /** * The current display language of the operating system. */ locale: string; - /** * The IP address. */ ip: string; - /** * The device language. */ language: string; - /** * The OS name. */ os: string; - /** * The OS version. */ osversion: string; - - /** - * Constructs a new instance of the Device class - */ - constructor(); } - - class User { - /** - * The user ID. - */ - id: string; - - /** - * Authenticated user id - */ - authenticatedId: string; - - /** - * The account ID. - */ - accountId: string; - - /** - * The account acquisition date. - */ - accountAcquisitionDate: string; - - /** - * The user agent string. - */ - agent: string; - - /** - * The store region. - */ - storeRegion: string; - - /** - * Sets the autheticated user id and the account id in this session. - * - * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. - * @param accountId {string} - An optional string to represent the account associated with the authenticated user. - */ - setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): void; - - /** - * Clears the authenticated user id and the account id from the user context. - * @returns {} - */ - clearAuthenticatedUserContext(): void; - - constructor(config: ITelemetryConfig); - } - - class Session { - /** - * The session ID. - */ - id: string; - - /** - * The true if this is the first session - */ - isFirst: boolean; - - /** - * The date at which this guid was genereated. - * Per the spec the ID will be regenerated if more than acquisitionSpan milliseconds ellapse from this time. - */ - acquisitionDate: number; - - /** - * The date at which this session ID was last reported. - * This value should be updated whenever telemetry is sent using this ID. - * Per the spec the ID will be regenerated if more than renewalSpan milliseconds elapse from this time with no activity. - */ - renewalDate: number; - } - - class Location { + + interface ILocation { /** * Client IP address for reverse lookup */ ip: string; } - class Operation { + interface IInternal { /** - * Unique id + * The SDK version used to create this telemetry item. + */ + sdkVersion: string; + /** + * The SDK agent version. + */ + agentVersion: string; + } + + interface ISample { + /** + * Sample rate + */ + sampleRate: number; + } + + interface ISession { + /** + * The session ID. + */ + id: string; + /** + * The true if this is the first session + */ + isFirst: boolean; + /** + * The date at which this guid was genereated. + * Per the spec the ID will be regenerated if more than acquisitionSpan milliseconds ellapse from this time. + */ + acquisitionDate: number; + /** + * The date at which this session ID was last reported. + * This value should be updated whenever telemetry is sent using this ID. + * Per the spec the ID will be regenerated if more than renewalSpan milliseconds elapse from this time with no activity. + */ + renewalDate: number; + } + + interface IOperation { + /** + * Operation id */ id: string; - - name: string; - - parentId: string; - - rootId: string; - /** - * String identifying the bot or test agent. + * Operation name + */ + name: string; + /** + * Parent operation id + */ + parentId: string; + /** + * Root operation id + */ + rootId: string; + /** + * Synthetic source of the operation */ syntheticSource: string; } + + interface IUser { + /** + * The telemetry configuration. + */ + config: any; + /** + * The user ID. + */ + id: string; + /** + * Authenticated user id + */ + authenticatedId: string; + /** + * The account ID. + */ + accountId: string; + /** + * The account acquisition date. + */ + accountAcquisitionDate: string; + /** + * The user agent string. + */ + agent: string; + /** + * The store region. + */ + storeRegion: string; + } } declare module Microsoft.Telemetry { - export class Base { - public baseType: string; - constructor() + class Base { + baseType: string; + constructor(); } - - class Envelope { - public ver: number; - public name: string; - public time: string; - public sampleRate: number; - public seq: string; - public iKey: string; - public flags: number; - public deviceId: string; - public os: string; - public osVer: string; - public appId: string; - public appVer: string; - public userId: string; - public tags: any; - public data: Base; - + + class Envelope { + ver: number; + name: string; + time: string; + sampleRate: number; + seq: string; + iKey: string; + flags: number; + deviceId: string; + os: string; + osVer: string; + appId: string; + appVer: string; + userId: string; + tags: any; + data: Base; constructor(); } } -declare module Microsoft.ApplicationInsights.Telemetry.Common { - class Envelope extends Microsoft.Telemetry.Envelope { - /** - * The data contract for serializing this object. - */ - aiDataContract: any; - - /** - * Constructs a new instance of telemetry data. - */ - constructor(data: Microsoft.Telemetry.Base, name: string); - } -} - - declare module Microsoft.ApplicationInsights { - - var Version: string; - interface IConfig { - // The key of your Application Insights resource in Azure - instrumentationKey: string; - - // The Application Insights server - endpointUrl: string; - - emitLineDelimitedJson: boolean; - - accountId: string; - - // A session is logged if the user is inactive for this time in milliseconds. Default 30 mins. - sessionRenewalMs: number; - - // A session is logged if it has continued for this time in milliseconds. Default 24h. - sessionExpirationMs: number; - - //Default 100k - maxBatchSizeInBytes: number; - - // Default 15s - maxBatchInterval: number; - - // If true, data is sent immediately and not batched. - enableDebug: boolean; - - // If true, telemetry data is not collected or sent. Default false. - disableTelemetry: boolean; - - verboseLogging: boolean; - - // Default 10s: - diagnosticLogInterval: number; - - samplingPercentage: number; - - autoTrackPageVisitTime: boolean; - - // If true, exceptions are not monitored. - disableExceptionTracking: boolean; - - // If true, ajax calls are not monitored. - disableAjaxTracking: boolean; - - // If true, default behavior of trackPageView is changed to record end of page view duration interval when - // trackPageView is called. If false and no custom duration is provided to trackPageView, the page view - // performance is calculated using the navigation timing API. - overridePageViewDuration: boolean; - - // Default 500 - controls how many ajax calls will be monitored per page view. - // Set to -1 to monitor all ajax calls on the page. - maxAjaxCallsPerView: number; - - disableDataLossAnalysis: boolean; - - disableCorrelationHeaders: boolean; - - disableFlushOnBeforeUnload: boolean; - - enableSessionStorageBuffer: boolean; - - // Custom cookie domain. This is helpful if you want to share Application Insights cookies across subdomains. - cookieDomain: string; + instrumentationKey?: string; + endpointUrl?: string; + emitLineDelimitedJson?: boolean; + accountId?: string; + sessionRenewalMs?: number; + sessionExpirationMs?: number; + maxBatchSizeInBytes?: number; + maxBatchInterval?: number; + enableDebug?: boolean; + disableExceptionTracking?: boolean; + disableTelemetry?: boolean; + verboseLogging?: boolean; + diagnosticLogInterval?: number; + samplingPercentage?: number; + autoTrackPageVisitTime?: boolean; + disableAjaxTracking?: boolean; + overridePageViewDuration?: boolean; + maxAjaxCallsPerView?: number; + disableDataLossAnalysis?: boolean; + disableCorrelationHeaders?: boolean; + disableFlushOnBeforeUnload?: boolean; + enableSessionStorageBuffer?: boolean; + cookieDomain?: string; + url?: string; } - interface ISenderConfig { + interface ITelemetryContext { /** - * The url to which payloads will be sent - */ - endpointUrl: () => string; - /** - * The JSON format (normal vs line delimited). True means line delimited JSON. + * The object describing a component tracked by this object. */ - emitLineDelimitedJson: () => boolean; - /** - * The maximum size of a batch in bytes - */ - maxBatchSizeInBytes: () => number; - /** - * The maximum interval allowed between calls to batchInvoke - */ - maxBatchInterval: () => number; - /** - * The master off switch. Do not send any data if set to TRUE - */ - disableTelemetry: () => boolean; - /** - * Store a copy of a send buffer in the session storage - */ - enableSessionStorageBuffer: () => boolean; - } - - interface ITelemetryConfig extends ISenderConfig { - instrumentationKey: () => string; - accountId: () => string; - sessionRenewalMs: () => number; - sessionExpirationMs: () => number; - sampleRate: () => number; - endpointUrl: () => string; - cookieDomain: () => string; - } - - - class TelemetryContext { - /** - * The object describing a component tracked by this object. - */ - application: Context.Application; - + application: Context.IApplication; /** * The object describing a device tracked by this object. */ - device: Context.Device; - + device: Context.IDevice; /** - * The object describing a user tracked by this object. - */ - user: Context.User; - - /** - * The object describing a session tracked by this object. - */ - session: Context.Session; - + * The object describing internal settings. + */ + internal: Context.IInternal; /** * The object describing a location tracked by this object. */ - location: Context.Location; - + location: Context.ILocation; /** * The object describing a operation tracked by this object. */ - operation: Context.Operation; - + operation: Context.IOperation; /** - * Use Sender.ts to send telemetry object to the endpoint + * The object describing sampling settings. + */ + sample: Context.ISample; + /** + * The object describing a user tracked by this object. */ - track(envelope: Telemetry.Common.Envelope): Telemetry.Common.Envelope; - + user: Context.IUser; + /** + * The object describing a session tracked by this object. + */ + session: Context.ISession; /** * Adds telemetry initializer to the collection. Telemetry initializers will be called one by one * before telemetry item is pushed for sending and in the order they were added. */ - addTelemetryInitializer(telemetryInitializer: (envelope: Telemetry.Common.Envelope) => boolean): void; + addTelemetryInitializer(telemetryInitializer: (envelope: Microsoft.Telemetry.Envelope) => boolean): any; + /** + * Tracks telemetry object. + */ + track(envelope: Microsoft.Telemetry.Envelope): any; } - /** - * The main API that sends telemetry to Application Insights. - * Learn more: http://go.microsoft.com/fwlink/?LinkID=401493 - */ - class AppInsights { - constructor(config: IConfig); - + interface IAppInsights { config: IConfig; - - context: TelemetryContext; - + context: ITelemetryContext; + queue: (() => void)[]; /** - * Starts timing how long the user views a page or other item. Call this when the page opens. - * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. - * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title. - */ - startTrackPage(name?: string): void; - + * Starts timing how long the user views a page or other item. Call this when the page opens. + * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. + * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title. + */ + startTrackPage(name?: string): any; /** - * Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes. - * @param name The string you used as the name in startTrackPage. Defaults to the document title. - * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. - * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. - * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. - */ - stopTrackPage(name?: string, url?: string, properties?: Object, measurements?: Object): void; - + * Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes. + * @param name The string you used as the name in startTrackPage. Defaults to the document title. + * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. + * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. + */ + stopTrackPage(name?: string, url?: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }): any; /** * Logs that a page or other item was viewed. * @param name The string you used as the name in startTrackPage. Defaults to the document title. @@ -404,39 +302,61 @@ declare module Microsoft.ApplicationInsights { * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. * @param duration number - the number of milliseconds it took to load the page. Defaults to undefined. If set to default value, page load time is calculated internally. */ - trackPageView(name?: string, url?: string, properties?: Object, measurements?: Object, duration?: number): void; - + trackPageView(name?: string, url?: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }, duration?: number): any; /** * Start timing an extended event. Call {@link stopTrackEvent} to log the event when it ends. * @param name A string that identifies this event uniquely within the document. */ - startTrackEvent(name: string): void; - + startTrackEvent(name: string): any; /** * Log an extended event that you started timing with {@link startTrackEvent}. * @param name The string you used to identify this event in startTrackEvent. * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. */ - stopTrackEvent(name: string, properties?: Object, measurements?: Object): void; - + stopTrackEvent(name: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }): any; /** - * Log a user action or other occurrence. - * @param name A string to identify this event in the portal. - * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. - * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. - */ - trackEvent(name: string, properties?: Object, measurements?: Object): void; - - trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string): void; - + * Log a user action or other occurrence. + * @param name A string to identify this event in the portal. + * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. + */ + trackEvent(name: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }): any; + /** + * Log an AJAX request + * @param id Event id + * @param absoluteUrl Full url + * @param pathName Leave this parameter blank + * @param totalTime Total time it took for AJAX request to complete + * @param success Whether AJAX request succeeded or failed + * @param resultCode Result code returned from AJAX call + * @param method HTTP verb that was used (GET, POST) + */ + trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string): any; /** * Log an exception you have caught. * @param exception An Error from a catch clause, or the string error message. * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. + * @param severityLevel AI.SeverityLevel - severity level */ - trackException(exception: Error, handledAt?: string, properties?: Object, measurements?: Object): void; + trackException(exception: Error, handledAt?: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }, severityLevel?: AI.SeverityLevel): any; /** * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators. * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the @@ -447,34 +367,34 @@ declare module Microsoft.ApplicationInsights { * @param min The smallest measurement in the sample. Defaults to the average. * @param max The largest measurement in the sample. Defaults to the average. */ - trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: Object): void; - + trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { + [name: string]: string; + }): any; /** * Log a diagnostic message. * @param message A message string * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. */ - trackTrace(message: string, properties?: Object): void; - + trackTrace(message: string, properties?: { + [name: string]: string; + }): any; /** * Immediately send all queued telemetry. */ - flush(): void; - + flush(): any; /** - * Sets the autheticated user id and the account id in this session. - * User auth id and account id should be of type string. They should not contain commas, semi-colons, equal signs, spaces, or vertical-bars. - * - * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. - * @param accountId {string} - An optional string to represent the account associated with the authenticated user. - */ - setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): void; - + * Sets the autheticated user id and the account id in this session. + * User auth id and account id should be of type string. They should not contain commas, semi-colons, equal signs, spaces, or vertical-bars. + * + * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. + * @param accountId {string} - An optional string to represent the account associated with the authenticated user. + */ + setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): any; /** * Clears the authenticated user id and the account id from the user context. */ - clearAuthenticatedUserContext(): void; - + clearAuthenticatedUserContext(): any; + downloadAndSetup?(config: Microsoft.ApplicationInsights.IConfig): void; /** * The custom error handler for Application Insights * @param {string} message - The error message @@ -483,6 +403,6 @@ declare module Microsoft.ApplicationInsights { * @param {number} columnNumber - The column number for the line where the error was raised * @param {Error} error - The Error object */ - _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error): void; + _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error): any; } } diff --git a/base64-js/base64-js-tests.ts b/base64-js/base64-js-tests.ts new file mode 100644 index 0000000000..6852ddb626 --- /dev/null +++ b/base64-js/base64-js-tests.ts @@ -0,0 +1,6 @@ +/// + +import * as base64js from 'base64-js'; + +const bytes: Uint8Array = base64js.toByteArray('shemp'); +const decoded: string = base64js.fromByteArray(new Uint8Array(0)); diff --git a/base64-js/base64-js.d.ts b/base64-js/base64-js.d.ts new file mode 100644 index 0000000000..cc7d2165c8 --- /dev/null +++ b/base64-js/base64-js.d.ts @@ -0,0 +1,10 @@ +// Type definitions for base64-js v1.1.2 +// Project: https://github.com/beatgammit/base64-js +// Definitions by: Peter Safranek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'base64-js' { + + export function toByteArray(encoded: string): Uint8Array; + export function fromByteArray(bytes: Uint8Array): string; +} diff --git a/bingmaps/Microsoft.Maps.d.ts b/bingmaps/Microsoft.Maps.d.ts index 95e39a043e..1e7e464930 100644 --- a/bingmaps/Microsoft.Maps.d.ts +++ b/bingmaps/Microsoft.Maps.d.ts @@ -174,6 +174,7 @@ declare namespace Microsoft.Maps { fixedMapPosition?: boolean; height?: number; inertiaIntensity?: number; + navigationBarMode?: number; showBreadcrumb?: boolean; showCopyright?: boolean; showDashboard?: boolean; @@ -216,6 +217,12 @@ declare namespace Microsoft.Maps { getY(): number; } + export enum NavigationBarMode { + default, + compact, + minified + } + export enum PixelReference { control, page, @@ -307,6 +314,7 @@ declare namespace Microsoft.Maps { getZIndex(): number; setHtmlContent(content: string): void; setLocation(location: Location): void; + setMap(map: Map): void; setOptions(options: InfoboxOptions): void; toString(): string; } diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index 16f639dfaf..f7e691a365 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -33,7 +33,7 @@ declare module "body-parser" { /** * passed to JSON.parse(). */ - receiver?: (key: string, value: any) => any; + reviver?: (key: string, value: any) => any; /** * parse extended syntax with the qs module. (default: true) */ @@ -65,7 +65,7 @@ declare module "body-parser" { /** * passed to JSON.parse(). */ - receiver?: (key: string, value: any) => any; + reviver?: (key: string, value: any) => any; }): express.RequestHandler; export function raw(options?: { diff --git a/bootstrap.datepicker/bootstrap.datepicker.d.ts b/bootstrap.datepicker/bootstrap.datepicker.d.ts index 686cc6b423..f60a0ffed6 100644 --- a/bootstrap.datepicker/bootstrap.datepicker.d.ts +++ b/bootstrap.datepicker/bootstrap.datepicker.d.ts @@ -15,7 +15,7 @@ * http://bootstrap-datepicker.readthedocs.org/en/release/options.html */ interface DatepickerOptions { - format?: string; + format?: string | DatepickerCustomFormatOptions; weekStart?: number; startDate?: any; endDate?: any; @@ -38,6 +38,11 @@ interface DatepickerOptions { assumeNearbyYear?: any; } +interface DatepickerCustomFormatOptions { + toDisplay?(date: string, format: any, language: any): string; + toValue?(date: string, format: any, language: any): Date; +} + interface DatepickerEventObject extends JQueryEventObject { date: Date; format(format?: string): string; diff --git a/bootstrap/bootstrap-tests.ts b/bootstrap/bootstrap-tests.ts index c497e0abcd..f7cfdeab43 100644 --- a/bootstrap/bootstrap-tests.ts +++ b/bootstrap/bootstrap-tests.ts @@ -44,3 +44,8 @@ $('.typeahead').typeahead({ }); $('#navbar').affix(); + +$('.item').emulateTransitionEnd(2000); + +$.support.transition = false; +console.log(($.support.transition as TransitionEventNames).end === "transitionend"); diff --git a/bootstrap/bootstrap.d.ts b/bootstrap/bootstrap.d.ts index b0e8fbf858..ae84454332 100644 --- a/bootstrap/bootstrap.d.ts +++ b/bootstrap/bootstrap.d.ts @@ -53,7 +53,7 @@ interface PopoverOptions { } interface CollapseOptions { - parent?: any; + parent?: any; toggle?: boolean; } @@ -79,6 +79,10 @@ interface AffixOptions { target?: any; } +interface TransitionEventNames { + end: string; +} + interface JQuery { modal(options?: ModalOptions): JQuery; modal(options?: ModalOptionsBackdropString): JQuery; @@ -114,6 +118,12 @@ interface JQuery { typeahead(options?: TypeaheadOptions): JQuery; affix(options?: AffixOptions): JQuery; + + emulateTransitionEnd(duration: number): JQuery; +} + +interface JQuerySupport { + transition: boolean | TransitionEventNames; } declare module "bootstrap" { diff --git a/browser-pack/browser-pack-tests.ts b/browser-pack/browser-pack-tests.ts new file mode 100644 index 0000000000..4cf20249e8 --- /dev/null +++ b/browser-pack/browser-pack-tests.ts @@ -0,0 +1,33 @@ +/// + +import browserPack = require("browser-pack"); + +module BrowserPackTest { + + export function packIt(opts?: BrowserPack.Options) { + var packOpts: BrowserPack.Options = { + basedir: opts.basedir || "./", + externalRequireName: opts.externalRequireName || "require", + hasExports: opts.hasExports || false, + prelude: opts.prelude || undefined, + preludePath: opts.preludePath || undefined, + raw: opts.raw || false, + sourceMapPrefix: opts.sourceMapPrefix || '//#', + standalone: opts.standalone || undefined, + standaloneModule: opts.standaloneModule || undefined, + }; + + var res = browserPack(); // 'opts' are optional + var res2 = browserPack(packOpts); + + // ensure return value is a stream + var res3 = res.pipe(res2); + + res.on("error", function (err: any) { + console.error("browser-pack error: ", err); + }); + } + +} + +export = BrowserPackTest; \ No newline at end of file diff --git a/browser-pack/browser-pack.d.ts b/browser-pack/browser-pack.d.ts new file mode 100644 index 0000000000..52b96ce134 --- /dev/null +++ b/browser-pack/browser-pack.d.ts @@ -0,0 +1,61 @@ +// Type definitions for browser-pack v6.0.1 +// Project: https://github.com/substack/browser-pack +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** pack node-style source files from a json stream into a browser bundle + */ +declare module BrowserPack { + + export interface Options { + /** Whether the bundle should include require= (or the opts.externalRequireName) so that + * require() is available outside the bundle + */ + hasExports?: boolean; + + /** A string to use in place of 'require' if opts.hasExports is specified, default is 'require' + */ + externalRequireName?: string; + + /** Specify a custom prelude, but know what you're doing first. See the prelude.js file in + * this repo for the default prelude. If you specify a custom prelude, you must also specify + * a valid opts.preludePath to the prelude source file for sourcemaps to work + */ + prelude?: string; + + /** prelude.js path if a custom opts.prelude is specified + */ + preludePath?: string; + + /** Used if opts.preludePath is undefined, this is used to resolve the prelude.js file location, default: 'process.cwd()' + */ + basedir?: string; + + /** if given, the writable end of the stream will expect objects to be written to + * it instead of expecting a stream of json text it will need to parse, default false + */ + raw?: boolean; + + /** External string name to use for UMD, if not provided, UMD declaration is not wrapped around output + */ + standalone?: string; + + /** Sets the internal module name to export for standalone + */ + standaloneModule?: string; + + /** If given and source maps are computed, the opts.sourceMapPrefix string will be used instead of default: '//#' + */ + sourceMapPrefix?: string; + } + +} + +declare module "browser-pack" { + /** pack node-style source files from a json stream into a browser bundle + */ + function browserPack(opts?: BrowserPack.Options): NodeJS.ReadWriteStream; + export = browserPack; +} \ No newline at end of file diff --git a/chartist/chartist.d.ts b/chartist/chartist.d.ts index 6c679dc1d8..0e92364812 100644 --- a/chartist/chartist.d.ts +++ b/chartist/chartist.d.ts @@ -105,7 +105,7 @@ declare namespace Chartist { plugins?: Array; // all of these plugins seem to be functions with options, but keeping type any for now update(data: Object, options?: T, override?: boolean): void; - detatch(): void; + detach(): void; /** * Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop. diff --git a/ckeditor/ckeditor.d.ts b/ckeditor/ckeditor.d.ts index bba377090f..9d8728338f 100644 --- a/ckeditor/ckeditor.d.ts +++ b/ckeditor/ckeditor.d.ts @@ -641,7 +641,7 @@ declare namespace CKEDITOR { filebrowserImageBrowseLinkUrl?: string; filebrowserImageBrowseUrl?: string; filebrowserImageUploadUrl?: string; - filebrowserUploadUr?: string; + filebrowserUploadUrl?: string; filebrowserWindowFeatures?: string; filebrowserWindowHeight?: number | string; filebrowserWindowWidth?: number | string; diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index f513057216..b1bf33e2d2 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -220,14 +220,7 @@ declare namespace CodeMirror { /** Get an { left , top , width , height , clientWidth , clientHeight } object that represents the current scroll position, the size of the scrollable area, and the size of the visible area(minus scrollbars). */ - getScrollInfo(): { - left: any; - top: any; - width: any; - height: any; - clientWidth: any; - clientHeight: any; - } + getScrollInfo(): CodeMirror.ScrollInfo; /** Scrolls the given element into view. pos is a { line , ch } position, referring to a given character, null, to refer to the cursor. The margin parameter is optional. When given, it indicates the amount of pixels around the given area that should be made visible as well. */ @@ -609,6 +602,15 @@ declare namespace CodeMirror { text: string; } + interface ScrollInfo { + left: any; + top: any; + width: any; + height: any; + clientWidth: any; + clientHeight: any; + } + interface TextMarker { /** Remove the mark. */ clear(): void; diff --git a/common-tags/common-tags-tests.ts b/common-tags/common-tags-tests.ts new file mode 100644 index 0000000000..9114f4414c --- /dev/null +++ b/common-tags/common-tags-tests.ts @@ -0,0 +1,156 @@ +/// + +import * as commonTags from 'common-tags'; + +/* Test Built-in Tags */ + +commonTags.commaLists ` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.commaListsAnd` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.commaListsOr` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +let fruits = ['apple', 'orange', 'watermelon']; + +commonTags.html` +
+
    + ${fruits.map(fruit => `
  • ${fruit}
  • `)} + ${'
  • kiwi
  • \n
  • guava
  • '} +
+
+`; + +commonTags.codeBlock` +
+
    + ${fruits.map(fruit => `
  • ${fruit}
  • `)} + ${'
  • kiwi
  • \n
  • guava
  • '} +
+
+`; + +commonTags.source` +
+
    + ${fruits.map(fruit => `
  • ${fruit}
  • `)} + ${'
  • kiwi
  • \n
  • guava
  • '} +
+
+`; + +commonTags.oneLine` + foo + bar + baz +`; + +commonTags.oneLineTrim` + https://news.com/article + ?utm_source=designernews.co +`; + +commonTags.oneLineCommaLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.oneLineCommaListsOr` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.oneLineCommaListsAnd` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.inlineLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.oneLineInlineLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +let verb = 'notice'; + +commonTags.stripIndent` + This is a multi-line string. + You'll ${verb} that it is indented. + We don't want to output this indentation. + But we do want to keep this line indented. +`; + +commonTags.stripIndents` + This is a multi-line string. + You'll ${verb} that it is indented. + We don't want to output this indentation. + We don't want to keep this line indented either. +`; + +/* Test Tag Constructor */ + +new commonTags.TemplateTag(); + +const substitutionReplacer = (oldValue : string, newValue : string) => ({ + onSubstitution(substitution : string, resultSoFar : string) { + if (substitution === oldValue) { + return newValue; + } + return substitution; + } +}); + +new commonTags.TemplateTag(substitutionReplacer('fizz', 'buzz')); + +new commonTags.TemplateTag( + substitutionReplacer('fizz', 'buzz'), + substitutionReplacer('foo', 'bar') +); + +new commonTags.TemplateTag([ + substitutionReplacer('fizz', 'buzz'), + substitutionReplacer('foo', 'bar') +]); + +new commonTags.TemplateTag({}); + +new commonTags.TemplateTag({ + onEndResult: endResult => `${endResult}!` +}); + +new commonTags.TemplateTag({ + onSubstitution: substitution => `${substitution}!`, + onEndResult: endResult => `${endResult}!` +}); + +/* Tests Built-in Transformers */ + +new commonTags.TemplateTag(commonTags.trimResultTransformer()); +new commonTags.TemplateTag(commonTags.trimResultTransformer('left')); +new commonTags.TemplateTag(commonTags.trimResultTransformer('right')); + +new commonTags.TemplateTag(commonTags.stripIndentTransformer()); +new commonTags.TemplateTag(commonTags.stripIndentTransformer('initial')); +new commonTags.TemplateTag(commonTags.stripIndentTransformer('all')); + +new commonTags.TemplateTag(commonTags.replaceResultTransformer('foo', 'bar')); + +new commonTags.TemplateTag(commonTags.inlineArrayTransformer()); +new commonTags.TemplateTag(commonTags.inlineArrayTransformer({})); +new commonTags.TemplateTag(commonTags.inlineArrayTransformer({separator: 'foo'})); +new commonTags.TemplateTag(commonTags.inlineArrayTransformer({conjunction: 'bar'})); + +new commonTags.TemplateTag(commonTags.splitStringTransformer('foo')); diff --git a/common-tags/common-tags.d.ts b/common-tags/common-tags.d.ts new file mode 100644 index 0000000000..aa443ac33d --- /dev/null +++ b/common-tags/common-tags.d.ts @@ -0,0 +1,62 @@ +// Type definitions for common-tags v1.2.1 +// Project: https://github.com/declandewet/common-tags +// Definitions by: Viktor Zozuliak +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'common-tags' { + type TemplateTag = (literals: string[], ...placeholders: any[]) => string; + + type TemplateTransformer = { + onSubstitution?: (substitution: string, resultSoFar: string) => string; + onEndResult?: (endResult : string) => string; + } + + /* Built-in Tags */ + export var commaLists: TemplateTag; + + export var commaListsAnd: TemplateTag; + + export var commaListsOr: TemplateTag; + + export var html: TemplateTag; + + export var codeBlock: TemplateTag; + + export var source: TemplateTag; + + export var oneLine: TemplateTag; + + export var oneLineTrim: TemplateTag; + + export var oneLineCommaLists: TemplateTag; + + export var oneLineCommaListsOr: TemplateTag; + + export var oneLineCommaListsAnd: TemplateTag; + + export var inlineLists: TemplateTag; + + export var oneLineInlineLists: TemplateTag; + + export var stripIndent: TemplateTag; + + export var stripIndents: TemplateTag; + + /* New Tag Constructor */ + export var TemplateTag: { + new(): TemplateTag; + new(...transformers: TemplateTransformer[]): TemplateTag; + new(transformers: TemplateTransformer[]): TemplateTag; + }; + + /* Built-in Transformers */ + export var trimResultTransformer: (side?: 'left'|'right') => TemplateTransformer; + + export var stripIndentTransformer: (type?: 'initial'|'all') => TemplateTransformer; + + export var replaceResultTransformer: (replaceWhat: string, replaceWith: string) => TemplateTransformer; + + export var inlineArrayTransformer: (opts?: {separator?: string, conjunction?: string}) => TemplateTransformer; + + export var splitStringTransformer: (splitBy: string) => TemplateTransformer; +} diff --git a/component-emitter/component-emitter-tests.ts b/component-emitter/component-emitter-tests.ts new file mode 100644 index 0000000000..e6c6a5b1ab --- /dev/null +++ b/component-emitter/component-emitter-tests.ts @@ -0,0 +1,52 @@ +/// // only for require +/// +// These are all of the examples from https://www.npmjs.com/package/component-emitter as of June 18, 2016 + + +// These are all of the examples from https://www.npmjs.com/package/component-emitter as of June 18, 2016 + +var Emitter = require('component-emitter'); +var emitter = new Emitter; +emitter.emit('something'); + + + + +var user = { name: 'tobi' }; +Emitter(user); + +(user).emit('im a user'); + + + +// this example modified from the one on https://www.npmjs.com/package/component-emitter +var User = Object.create({ + someUserFunction: () => {console.log('someUserFunction called!')} +}) +var another_user = Emitter(User); +another_user.someUserFunction() +another_user.on('hi', () => {console.log('Hi called')}) +another_user.emit('hi') + + +// Additional sample code for this test +function handleSomeRecurringEvent(event_data: any) { + console.log('handle some-recurring-event') +} +emitter.on('some-recurring-event', handleSomeRecurringEvent) + + +emitter.once('some-single-shot-event', (event_data: any) => {console.log('handle some-single-shot-event')}) + + +emitter.off() +emitter.off('some-recurring-event') +emitter.off('some-recurring-event', handleSomeRecurringEvent) + +var event_data = {some: 'data'} +emitter.emit('some-recurring-event') +emitter.emit('some-recurring-event', event_data) + +emitter.listeners('some-recurring-event') + +emitter.hasListeners('some-recurring-event') diff --git a/component-emitter/component-emitter.d.ts b/component-emitter/component-emitter.d.ts new file mode 100644 index 0000000000..28ce4f4bc9 --- /dev/null +++ b/component-emitter/component-emitter.d.ts @@ -0,0 +1,19 @@ +// Type definitions for component-emitter v1.2.1 +// Project: https://www.npmjs.com/package/component-emitter +// Definitions by: Peter Snider +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/emitter-component + + +interface Emitter { + (obj?: Object): Emitter; + on(event: string, listener: Function): Emitter; + once(event: string, listener: Function): Emitter; + off(event?: string, listener?: Function): Emitter; + emit(event: string, ...args: any[]): boolean; + listeners(event: string): Function[]; + hasListeners(event: string): boolean; +} + +declare module 'component-emitter' { + var Emitter: Emitter; +} diff --git a/cucumber/cucumber.d.ts b/cucumber/cucumber.d.ts index d0e742d9c2..6c4273e4e0 100644 --- a/cucumber/cucumber.d.ts +++ b/cucumber/cucumber.d.ts @@ -29,8 +29,20 @@ declare namespace cucumber { } interface HookScenario{ - attach(text: string, mimeType?: string, callback?: (err?:any) => void): void; - isFailed() : boolean; + getKeyword():string; + getName():string; + getDescription():string; + getUri():string; + getLine():number; + getTags():string[]; + getException():Error; + getAttachments():any[]; + attach(data:any, mimeType?:string, callback?:(err?:any) => void):void; + isSuccessful():boolean; + isFailed():boolean; + isPending():boolean; + isUndefined():boolean; + isSkipped():boolean; } interface HookCode { diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 683fb8532c..b35d898522 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -292,17 +292,17 @@ declare namespace d3 { */ datum(): Datum; - /** - * Set the data item for each node in the selection. - * @param value the constant element to use for each node - */ - datum(value: NewDatum): Update; - /** * Derive the data item for each node in the selection. Useful for situations such as the HTML5 'dataset' attribute. * @param value the function to compute data for each node */ datum(value: (datum: Datum, index: number, outerIndex: number) => NewDatum): Update; + + /** + * Set the data item for each node in the selection. + * @param value the constant element to use for each node + */ + datum(value: NewDatum): Update; /** * Reorders nodes in the selection based on the given comparator. Nodes are re-inserted into the document once sorted. @@ -1111,8 +1111,7 @@ declare namespace d3 { export function deviation(array: number[]): number; export function deviation(array: T[], accessor: (datum: T, index: number) => number): number; - export function bisectLeft(array: number[], x: number, lo?: number, hi?: number): number; - export function bisectLeft(array: string[], x: string, lo?: number, hi?: number): number; + export function bisectLeft(array: T[], x: T, lo?: number, hi?: number): number; export var bisect: typeof bisectRight; @@ -3064,6 +3063,8 @@ declare namespace d3 { } export interface Partition { + (root: T): T[]; + nodes(root: T): T[]; links(nodes: T[]): partition.Link[]; diff --git a/d3kit/d3kit-tests.ts b/d3kit/d3kit-tests.ts new file mode 100644 index 0000000000..1b8d2a24f9 --- /dev/null +++ b/d3kit/d3kit-tests.ts @@ -0,0 +1,1112 @@ +/// +/// +/// +/// + +/* jshint expr: true */ + +var expect = chai.expect; +describe('Skeleton', function(){ + var element: Element, $element: d3.Selection, $svg: d3.Selection, skeleton: d3kit.Skeleton; + + beforeEach(function(done){ + element = document.body.appendChild(document.createElement('div')) as Element; + skeleton = new d3kit.Skeleton(element, null, ['custom1', 'custom2']); + $element = d3.select(element); + $svg = $element.select('svg'); + done(); + }); + + describe('new Skeleton()', function(){ + it('should create inside the element', function(){ + expect($element.select('svg').size()).to.be.equal(1); + }); + it('should create inside inside the element', function(){ + expect($element.select('svg').select('g').size()).to.be.equal(1); + }); + }); + + describe('#getCustomEventNames()', function(){ + it('should return custom event names', function(){ + expect(skeleton.getCustomEventNames()).to.deep.equal(['custom1', 'custom2']); + }); + }); + + describe('#getDispatcher()', function(){ + it('should return event dispatcher', function(){ + expect(skeleton.getDispatcher()).to.be.an('Object'); + expect(skeleton.getDispatcher().data).to.be.a('Function'); + }); + }); + + describe('#getInnerWidth()', function(){ + it('should return width of the skeleton excluding margin', function(){ + skeleton.options({ + margin: {left: 10, right: 10} + }); + skeleton.width(100); + expect(skeleton.getInnerWidth()).to.equal(80); + }); + }); + + describe('#getInnerHeight()', function(){ + it('should return height of the skeleton excluding margin', function(){ + skeleton.options({ + margin: {top: 10, bottom: 20} + }); + skeleton.height(100); + expect(skeleton.getInnerHeight()).to.equal(70); + }); + }); + + describe('#getLayerOrganizer()', function(){ + it('should return the LayerOrganizer', function(){ + expect(skeleton.getLayerOrganizer()).to.be.an('Object'); + }); + }); + + describe('#getRootG()', function(){ + it('should return d3 selection of the root ', function(){ + var g = skeleton.getRootG(); + expect(g.size()).to.equal(1); + expect((g[0][0] as Element).tagName).to.equal('g'); + }); + }); + + describe('#getSvg()', function(){ + it('should return d3 selection of the ', function(){ + var svg = skeleton.getSvg(); + expect(svg.size()).to.equal(1); + expect((svg[0][0] as Element).tagName).to.equal('svg'); + }); + }); + + describe('#data(data, doNotDispatch)', function(){ + it('should return data when called without argument', function(){ + skeleton.data({a: 1}); + expect(skeleton.data()).to.deep.equal({a: 1}); + }); + it('should set data when called with at least one argument', function(){ + skeleton.data('test'); + expect(skeleton.data()).to.equal('test'); + }); + it('after setting, should dispatch "data" event', function(done){ + skeleton.on('data.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.data({a: 1}); + }); + it('after setting, should not dispatch "data" event if doNotDispatch is true', function(done){ + skeleton.on('data.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.data({a: 1}, true); + setTimeout(done, 100); + }); + }); + + describe('#options(options, doNotDispatch)', function(){ + it('should return options when called without argument', function(){ + skeleton.options({a: 2}); + expect(skeleton.options()).to.include.keys(['a']); + expect(skeleton.options().a).to.equal(2); + }); + it('should set options when called with at least one argument', function(){ + skeleton.options({a: 1}); + expect(skeleton.options()).to.include.keys(['a']); + expect(skeleton.options().a).to.equal(1); + }); + it('should not overwrite but extend existing options when setting', function(){ + skeleton.options({a: 1}); + skeleton.options({b: 2}); + expect(skeleton.options()).to.include.keys(['a', 'b']); + expect(skeleton.options().a).to.equal(1); + expect(skeleton.options().b).to.equal(2); + }); + it('after setting, should dispatch "options" event', function(done){ + skeleton.on('options.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.options({a: 1}); + }); + it('after setting, should not dispatch "options" event if doNotDispatch is true', function(done){ + skeleton.on('options.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.options({a: 1}, true); + setTimeout(done, 100); + }); + }); + + describe('#margin(margin, doNotDispatch)', function(){ + it('should return margin when called without argument', function(){ + var margin = {left: 10, right: 10, top: 10, bottom: 10}; + skeleton.margin(margin); + expect(skeleton.margin()).to.deep.equal(margin); + }); + it('should set margin when called with at least one argument', function(){ + var margin = {left: 10, right: 10, top: 10, bottom: 10}; + skeleton.margin(margin); + + skeleton.margin({left: 20}); + expect(skeleton.margin().left).to.equal(20); + expect(skeleton.margin().right).to.equal(10); + skeleton.margin({right: 20}); + expect(skeleton.margin().right).to.equal(20); + skeleton.margin({top: 20}); + expect(skeleton.margin().top).to.equal(20); + skeleton.margin({bottom: 20}); + expect(skeleton.margin().bottom).to.equal(20); + }); + it('should update innerWidth after setting margin', function(){ + skeleton.width(100); + skeleton.margin({left: 10, right:10}); + expect(skeleton.getInnerWidth()).to.equal(80); + skeleton.margin({left: 15, right:15}); + expect(skeleton.getInnerWidth()).to.equal(70); + }); + it('should update innerHeight after setting margin', function(){ + skeleton.height(100); + skeleton.margin({top: 10, bottom:10}); + expect(skeleton.getInnerHeight()).to.equal(80); + skeleton.margin({top: 15, bottom:15}); + expect(skeleton.getInnerHeight()).to.equal(70); + }); + it('should update the root transform/translate', function(){ + skeleton.margin({left: 30, top: 30}); + skeleton.offset([0.5, 0.5]); + skeleton.margin({left: 10, top: 10}); + var translate = skeleton.getRootG().attr('transform'); + expect(translate).to.equal('translate(10.5,10.5)'); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.margin({left: 33}); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.margin({left: 33}, true); + setTimeout(done, 100); + }); + }); + + describe('#offset(offset)', function(){ + it('should return offset when called without argument', function(){ + var offset = [1,1]; + skeleton.offset(offset); + expect(skeleton.offset()).to.deep.equal(offset); + }); + it('should set offset when called with at least one argument', function(){ + var offset = [1,1]; + skeleton.offset(offset); + skeleton.offset([2,3]); + expect(skeleton.offset()).to.deep.equal([2,3]); + }); + it('should update the root transform/translate', function(){ + skeleton.offset([0.5, 0.5]); + skeleton.margin({left: 10, top: 10}); + skeleton.offset([2,3]); + var translate = skeleton.getRootG().attr('transform'); + expect(translate).to.equal('translate(12,13)'); + }); + }); + + describe('#width(width, doNotDispatch)', function(){ + it('should return width when called without argument', function(){ + var w = $svg.attr('width'); + expect(skeleton.width()).to.equal(+w); + }); + it('should set width when called with Number as the first argument', function(){ + skeleton.width(300); + expect(+$svg.attr('width')).to.equal(300); + }); + it('should set width when called with a Number and "px" such as "100px" as the first argument', function(){ + skeleton.width('299px'); + expect(+$svg.attr('width')).to.equal(299); + }); + it('should set width to container\'s width when called with "auto" as the first argument', function(){ + var w = element.clientWidth; + skeleton.width('auto'); + expect(+$svg.attr('width')).to.equal(w); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.width(200); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.width(200, true); + setTimeout(done, 100); + }); + }); + + describe('#height(height, doNotDispatch)', function(){ + it('should return height when called without argument', function(){ + var w = $svg.attr('height'); + expect(skeleton.height()).to.equal(+w); + }); + it('should set height when called with Number as the first argument', function(){ + skeleton.height(300); + expect(+$svg.attr('height')).to.equal(300); + }); + it('should set height when called with a Number and "px" such as "100px" as the first argument', function(){ + skeleton.height('299px'); + expect(+$svg.attr('height')).to.equal(299); + }); + it('should set height to container\'s height when called with "auto" as the first argument', function(){ + var w = element.clientHeight; + skeleton.height('auto'); + expect(+$svg.attr('height')).to.equal(w); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.height(200); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.height(200, true); + setTimeout(done, 100); + }); + }); + + describe('#dimension(dimension, doNotDispatch)', function(){ + it('should return an array [width, height] when called without argument', function(){ + var dim = [+$svg.attr('width'), +$svg.attr('height')]; + expect(skeleton.dimension()).to.deep.equal(dim); + }); + it('should set width and height of the when called with an array [width, height] as the first argument', function(){ + skeleton.dimension([118, 118]); + expect([+$svg.attr('width'), +$svg.attr('height')]).to.deep.equal([118, 118]); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.dimension([150, 150]); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.dimension([150, 150], true); + setTimeout(done, 100); + }); + }); + + describe('#hasData()', function(){ + it('should return true when data are not null nor undefined', function(){ + skeleton.data({}); + expect(skeleton.hasData()).to.be.true; + skeleton.data({test: 1}); + expect(skeleton.hasData()).to.be.true; + skeleton.data([]); + expect(skeleton.hasData()).to.be.true; + skeleton.data(['test']); + expect(skeleton.hasData()).to.be.true; + }); + it('should return false when data are null or undefined', function(){ + skeleton.data(null); + expect(skeleton.hasData()).to.be.false; + skeleton.data(undefined); + expect(skeleton.hasData()).to.be.false; + }); + }); + + describe('#hasNonZeroArea()', function(){ + it('should return true if \'s width & height excluding margin is more than zero', function(){ + skeleton.options({ + margin: {left: 10, right: 10} + }); + skeleton.width(80); + skeleton.options({ + margin: {top: 10, bottom: 20} + }); + skeleton.height(50); + expect(skeleton.hasNonZeroArea()).to.be.true; + }); + it('should return false otherwise', function(){ + skeleton.options({ + margin: {left: 10, right: 10} + }); + skeleton.width(20); + skeleton.options({ + margin: {top: 10, bottom: 20} + }); + skeleton.height(30); + expect(skeleton.hasNonZeroArea()).to.be.false; + }); + }); + + describe('#mixin({})', function(){ + it('should extend this skeleton with new fields/functions', function(){ + skeleton.mixin({ + a: 1, + b: 2 + }); + expect(skeleton).to.include.keys(['a', 'b']); + expect((skeleton).a).to.equal(1); + expect((skeleton).b).to.equal(2); + }); + it('should overwrite existing fields', function(){ + skeleton.mixin({ + b: 2 + }); + skeleton.mixin({ + b: 3 + }); + expect(skeleton).to.include.keys(['b']); + expect((skeleton).b).to.equal(3); + }); + it('should keep original fields if not overwritten', function(){ + skeleton.mixin({ + a: 1, + b: 2 + }); + skeleton.mixin({ + c: 20, + b: 3 + }); + expect(skeleton).to.include.keys(['a', 'b', 'c']); + expect((skeleton).a).to.equal(1); + expect((skeleton).b).to.equal(3); + expect((skeleton).c).to.equal(20); + }); + }); + + describe('#resizeToFitContainer(mode)', function(){ + it('when mode is "all" should resize to fit both width and height', function(){ + skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); + var w = element.clientWidth; + var h = element.clientHeight; + skeleton.resizeToFitContainer('all'); + expect(skeleton.dimension()).to.deep.equal([w, h]); + }); + it('when mode is "both" should resize to fit both width and height', function(){ + skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); + var w = element.clientWidth; + var h = element.clientHeight; + skeleton.resizeToFitContainer('both'); + expect(skeleton.dimension()).to.deep.equal([w, h]); + }); + it('when mode is "full" should resize to fit both width and height', function(){ + skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); + var w = element.clientWidth; + var h = element.clientHeight; + skeleton.resizeToFitContainer('full'); + expect(skeleton.dimension()).to.deep.equal([w, h]); + }); + it('when mode is "width" should resize width to fit container but keep original height', function(){ + var w1 = element.clientWidth/2; + var h1 = element.clientHeight/2; + + skeleton.dimension([w1, h1]); + + var w2 = element.clientWidth; + var h2 = element.clientHeight; + + skeleton.resizeToFitContainer('width'); + + expect(skeleton.width()).to.equal(Math.floor(w2)); + expect(skeleton.height()).to.equal(Math.floor(h1)); + expect(skeleton.width()).to.not.equal(w1); + expect(skeleton.height()).to.not.equal(h2); + }); + it('when mode is "height" should resize height to fit container but keep original width', function(){ + var w1 = element.clientWidth/2; + var h1 = element.clientHeight*2; + + skeleton.dimension([w1, h1]); + + var w2 = element.clientWidth; + var h2 = element.clientHeight; + + skeleton.resizeToFitContainer('height'); + + expect(skeleton.width()).to.equal(Math.floor(w1)); + expect(skeleton.height()).to.equal(Math.floor(h2)); + expect(skeleton.width()).to.not.equal(w2); + expect(skeleton.height()).to.not.equal(h1); + }); + }); + + describe('#resizeToAspectRatio(ratio)', function(){ + // todo + }); + + describe('#autoResize(mode)', function(){ + it('should return current mode when called without argument', function(){ + skeleton.autoResize(false); + expect(skeleton.autoResize()).to.be.false; + skeleton.autoResize('width'); + expect(skeleton.autoResize()).to.equal('width'); + }); + it('should enable auto resize when set mode to "width/height/both/etc.", similar to parameters of resizeToFitContainer()', function(done){ + // set initial size + skeleton.width(50); + skeleton.autoResize('width'); + setTimeout(function(){ + expect(skeleton.width()).to.equal(element.clientWidth); + done(); + }, 500); + }); + it('should disable auto resize when set mode to false', function(done){ + // set initial size + skeleton.width(50); + skeleton.autoResize('width'); + setTimeout(function(){ + expect(skeleton.width()).to.equal(element.clientWidth); + // disable resize and + skeleton.autoResize(false); + skeleton.width(50); + setTimeout(function(){ + expect(skeleton.width()).to.not.equal(element.clientWidth); + done(); + }, 500); + }, 500); + }); + }); + + describe('#autoResizeDetection(detection)', function(){ + // todo + }); + + describe('#autoResizeToAspectRatio(ratio)', function(){ + // todo + }); + + +}); + +describe.only('LayerOrganizer', function(){ + + describe('new LayerOrganizer(container) will create layers as by default', function(){ + var container: d3.Selection, layers: d3kit.LayerOrganizer; + before(function(done){ + container = d3.select('body').append('svg').append('g'); + layers = new d3kit.LayerOrganizer(container); + done(); + }); + + describe('#create(names)', function(){ + it('should create single layer given a String', function(){ + layers.create('single'); + expect(container.select('g.single-layer').size()).to.be.equal(1); + }); + + it('should create multiple layers given an array', function(){ + layers.create(['a', 'b', 'c']); + expect(container.select('g.a-layer').size()).to.be.equal(1); + expect(container.select('g.b-layer').size()).to.be.equal(1); + expect(container.select('g.c-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with a String inside', function(){ + layers.create({d: 'e'}); + expect(container.select('g.d-layer').size()).to.be.equal(1); + expect(container.select('g.d-layer g.e-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with an Array inside', function(){ + layers.create({f: ['g', 'h']}); + expect(container.select('g.f-layer').size()).to.be.equal(1); + expect(container.select('g.f-layer g.g-layer').size()).to.be.equal(1); + expect(container.select('g.f-layer g.h-layer').size()).to.be.equal(1); + }); + + it('should create multiple nested layers given an array of objects', function(){ + layers.create([{'i': ['x']}, {'j': 'x'}, {'k': ['x','y']}]); + expect(container.select('g.i-layer').size()).to.be.equal(1); + expect(container.select('g.j-layer').size()).to.be.equal(1); + expect(container.select('g.k-layer').size()).to.be.equal(1); + expect(container.select('g.i-layer g.x-layer').size()).to.be.equal(1); + expect(container.select('g.i-layer g.x-layer').size()).to.be.equal(1); + expect(container.select('g.k-layer g.x-layer').size()).to.be.equal(1); + expect(container.select('g.k-layer g.y-layer').size()).to.be.equal(1); + }); + + it('should create multi-level nested layers given a nested plain Object', function(){ + layers.create({ + l: [ + 'm', + {'n': [ + {'o': ['p']}, 'q' + ]} + ] + }); + expect(container.select('g.l-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.m-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer g.o-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer g.o-layer g.p-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer g.q-layer').size()).to.be.equal(1); + }); + + }); + + describe('#has(name)', function(){ + it('should be able to check first-level layer', function(){ + expect(layers.has('single')).to.be.true; + expect(layers.has('test')).to.be.false; + }); + it('should be able to check second-level layer', function(){ + expect(layers.has('l.m')).to.be.true; + expect(layers.has('l.x')).to.be.false; + }); + it('should be able to check third-level layer', function(){ + expect(layers.has('l.n.q')).to.be.true; + expect(layers.has('l.n.x')).to.be.false; + }); + }); + + describe('#get(name)', function(){ + it('should be able to get first-level layer', function(){ + expect(layers.get('single')).to.exist; + expect(layers.get('test')).to.be.not.exist; + }); + it('should be able to get second-level layer', function(){ + expect(layers.get('l.m')).to.exist; + expect(layers.get('l.x')).to.not.exist; + }); + it('should be able to get third-level layer', function(){ + expect(layers.get('l.n.o')).to.exist; + expect(layers.get('l.n.x')).to.not.exist; + }); + }); + }); + + describe('new LayerOrganizer(container, tag) will create layers with the given tag instead of ', function(){ + var container: d3.Selection, layers: d3kit.LayerOrganizer; + before(function(done){ + container = d3.select('body').append('div'); + layers = new d3kit.LayerOrganizer(container, 'div'); + done(); + }); + + describe('#create(names)', function(){ + it('should create single layer given a String', function(){ + layers.create('single'); + expect(container.select('div.single-layer').size()).to.be.equal(1); + }); + + it('should create multiple layers given an array', function(){ + layers.create(['a', 'b', 'c']); + expect(container.select('div.a-layer').size()).to.be.equal(1); + expect(container.select('div.b-layer').size()).to.be.equal(1); + expect(container.select('div.c-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with a String inside', function(){ + layers.create({d: 'e'}); + expect(container.select('div.d-layer').size()).to.be.equal(1); + expect(container.select('div.d-layer div.e-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with an Array inside', function(){ + layers.create({f: ['g', 'h']}); + expect(container.select('div.f-layer').size()).to.be.equal(1); + expect(container.select('div.f-layer div.g-layer').size()).to.be.equal(1); + expect(container.select('div.f-layer div.h-layer').size()).to.be.equal(1); + }); + + it('should create multiple nested layers given an array of objects', function(){ + layers.create([{'i': ['x']}, {'j': 'x'}, {'k': ['x','y']}]); + expect(container.select('div.i-layer').size()).to.be.equal(1); + expect(container.select('div.j-layer').size()).to.be.equal(1); + expect(container.select('div.k-layer').size()).to.be.equal(1); + expect(container.select('div.i-layer div.x-layer').size()).to.be.equal(1); + expect(container.select('div.i-layer div.x-layer').size()).to.be.equal(1); + expect(container.select('div.k-layer div.x-layer').size()).to.be.equal(1); + expect(container.select('div.k-layer div.y-layer').size()).to.be.equal(1); + }); + + it('should create multi-level nested layers given a nested plain Object', function(){ + layers.create({ + l: [ + 'm', + {'n': [ + {'o': ['p']}, 'q' + ]} + ] + }); + expect(container.select('div.l-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.m-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer div.o-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer div.o-layer div.p-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer div.q-layer').size()).to.be.equal(1); + }); + + }); + + describe('#has(name)', function(){ + it('should be able to check first-level layer', function(){ + expect(layers.has('single')).to.be.true; + expect(layers.has('test')).to.be.false; + }); + it('should be able to check second-level layer', function(){ + expect(layers.has('l.m')).to.be.true; + expect(layers.has('l.x')).to.be.false; + }); + it('should be able to check third-level layer', function(){ + expect(layers.has('l.n.q')).to.be.true; + expect(layers.has('l.n.x')).to.be.false; + }); + }); + + describe('#get(name)', function(){ + it('should be able to get first-level layer', function(){ + expect(layers.get('single')).to.exist; + expect(layers.get('test')).to.be.not.exist; + }); + it('should be able to get second-level layer', function(){ + expect(layers.get('l.m')).to.exist; + expect(layers.get('l.x')).to.not.exist; + }); + it('should be able to get third-level layer', function(){ + expect(layers.get('l.n.o')).to.exist; + expect(layers.get('l.n.x')).to.not.exist; + }); + }); + }); + +}); + +describe('Chartlet', function(){ + interface ConfigureFunction { + (parent: d3kit.Chartlet, child: d3kit.Chartlet): void; + } + var enter: d3kit.ChartletEventFunction, update: d3kit.ChartletEventFunction, exit: d3kit.ChartletEventFunction, chartlet: d3kit.Chartlet; + var customEvents: Array = ['fooEvent']; + var ChildChartlet: () => d3kit.Chartlet; + var ParentChartlet: (configureFunction: ConfigureFunction) => d3kit.Chartlet; + + var callback = function(selection?: d3.Selection, done?: any) { return (sel: d3.Selection) => {done();};}; + beforeEach(function(done){ + ChildChartlet = function() { + var chartlet = new d3kit.Chartlet(callback, callback, callback); + (chartlet).runTest = function (testFunction: any) { + testFunction(chartlet); + }; + return chartlet; + }; + + ParentChartlet = function(configureFunction: ConfigureFunction) { + var chartlet = new d3kit.Chartlet(callback, callback, callback); + var child = ChildChartlet(); + configureFunction(chartlet, child); + (chartlet).runTest = (child).runTest; + return chartlet; + }; + + enter = callback; + update = callback; + exit = callback; + chartlet = new d3kit.Chartlet(enter, update, exit, customEvents); + done(); + }); + + describe('new Chartlet(enter, update, exit, customEvents)', function(){ + it('should create a chartlet', function(){ + expect(chartlet).to.be.an('Object'); + expect(chartlet).to.include.keys(['property', 'on']); + expect(chartlet.enter).to.be.a('Function'); + expect(chartlet.update).to.be.a('Function'); + expect(chartlet.exit).to.be.a('Function'); + expect(function(){ chartlet.enter(); }).to.not.throw(Error); + expect(function(){ chartlet.update(); }).to.not.throw(Error); + expect(function(){ chartlet.exit(); }).to.not.throw(Error); + expect(chartlet.getCustomEventNames()).to.deep.equal(customEvents); + }); + it('arguments "update", "exit" and "customEvents" are optional', function(){ + var comp = new d3kit.Chartlet(enter); + expect(comp).to.be.an('Object'); + expect(comp).to.include.keys(['property', 'on']); + expect(comp.enter).to.be.a('Function'); + expect(comp.update).to.be.a('Function'); + expect(comp.exit).to.be.a('Function'); + expect(function(){ comp.enter(); }).to.not.throw(Error); + expect(function(){ comp.update(); }).to.not.throw(Error); + expect(function(){ comp.exit(); }).to.not.throw(Error); + }); + }); + + describe('#getDispatcher()', function(){ + it('should return a dispatcher', function(){ + var dispatcher = chartlet.getDispatcher(); + expect(dispatcher).to.exist; + }); + it('returned dispatcher should handle enter/update/exit events', function(){ + var dispatcher = chartlet.getDispatcher(); + expect(dispatcher).to.include.keys(['enterDone', 'updateDone', 'exitDone'].concat(customEvents)); + }); + }); + + describe('#getPropertyValue(name, d, i)', function(){ + it('should return computed value for specified property name, d and i', function(){ + var d = {a: 99}; + var i = 2; + + chartlet.property('foo', 1); + chartlet.property('bar', 'two'); + chartlet.property('baz', function(d:{a:number}, i: number) {return 3;}); + chartlet.property('qux', function(d:{a:number}, i: number) {return 'four';}); + chartlet.property('nux', function(d:{a:number}, i: number) {return d.a * i;}); + + expect(chartlet.getPropertyValue('foo', d, i)).to.equal(1); + expect(chartlet.getPropertyValue('bar', d, i)).to.equal('two'); + expect(chartlet.getPropertyValue('baz', d, i)).to.equal(3); + expect(chartlet.getPropertyValue('qux', d, i)).to.equal('four'); + expect(chartlet.getPropertyValue('nux', d, i)).to.equal(198); + }); + }); + + describe('#property(name, valueOrFn)', function(){ + describe('should act as a getter when called with one argument', function(){ + it('should always return a function', function(){ + chartlet.property('foo', 1); + expect(chartlet.property('foo')).to.be.a('Function'); + chartlet.property('bar', function(){ return 100; }); + expect(chartlet.property('bar')).to.be.a('Function'); + }); + it('should return a function that return undefined for unknown property name', function(){ + expect(chartlet.property('unknown name')).to.be.a('Function'); + expect(chartlet.property('unknown name')()).to.equal(undefined); + }); + }); + + describe('should act as a setter when called with two arguments', function(){ + it('should set specified property to a functor of given value', function(){ + chartlet.property('foo', 1); + expect(chartlet.property('foo')).to.be.a('Function'); + expect(chartlet.property('foo')()).to.equal(1); + chartlet.property('bar', function(){ return 100; }); + expect(chartlet.property('bar')).to.be.a('Function'); + expect(chartlet.property('bar')()).to.equal(100); + }); + it('should overwrite previous value when set property with the same name', function(){ + chartlet.property('foo', 1); + expect(chartlet.property('foo')()).to.equal(1); + chartlet.property('foo', 100); + expect(chartlet.property('foo')()).to.equal(100); + }); + }); + }); + + describe('#on(eventName, listener)', function(){ + it('event "enterDone" should be triggered after chartlet.enter() is completed.', function(done){ + chartlet.on('enterDone', function(){ return (sel: d3.Selection) => {done();} }); + chartlet.enter(); + }); + it('event "updateDone" should be triggered after chartlet.update() is completed.', function(done){ + chartlet.on('updateDone', function(){ return (sel: d3.Selection) => {done();} }); + chartlet.update(); + }); + it('event "exitDone" should be triggered after chartlet.exit() is completed.', function(done){ + chartlet.on('exitDone', function(){ return (sel: d3.Selection) => {done();} }); + chartlet.exit(); + }); + }); + + describe('#inheritPropertyFrom(parentChartlet, parentPropertyName, childPropertyName)', function(){ + it('it should cause a child to inherit a parent property', function() { + var parent = ParentChartlet(function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertyFrom(parent, 'foo', 'bar'); + }) + .property('foo', function(d:number) {return 2 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('bar', 4, 0)).to.be.equal(8); + }); + }); + + it('it should default to the parent property name', function() { + var parent = ParentChartlet( + function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertyFrom(parent, 'foo'); + }) + .property('foo', function(d:number) {return 2 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('foo', 4, 0)).to.be.equal(8); + }); + }); + }); + + describe('#inheritProperties(parentChartlet, parentPropertyNames, childPropertyNames)', function(){ + it('it should cause a child to inherit many parent properties', function() { + var parent = ParentChartlet( + function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertiesFrom(parent, ['foo', 'bar', 'baz'], ['foo-x', 'bar-x', 'baz-x']); + }) + .property('foo', function(d:number) {return 2 * d;}) + .property('bar', function(d:number) {return 3 * d;}) + .property('baz', function(d:number) {return 4 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('foo-x', 1, 0)).to.be.equal(2); + expect(child.getPropertyValue('bar-x', 1, 0)).to.be.equal(3); + expect(child.getPropertyValue('baz-x', 1, 0)).to.be.equal(4); + }); + }); + + it('it should default to the parent property names', function() { + var parent = ParentChartlet( + function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertiesFrom(parent, ['foo', 'bar', 'baz']); + }) + .property('foo', function(d:number) {return 2 * d;}) + .property('bar', function(d:number) {return 3 * d;}) + .property('baz', function(d:number) {return 4 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('foo', 1, 0)).to.be.equal(2); + expect(child.getPropertyValue('bar', 1, 0)).to.be.equal(3); + expect(child.getPropertyValue('baz', 1, 0)).to.be.equal(4); + }); + }); + }); + + describe('#publishEventsTo(foreignDispatcher)', function(){ + it('should map events to a foreignDispatcher', function(done) { + + var parent = new d3kit.Chartlet(callback, callback, callback, ['foo']); + parent.getDispatcher().on('foo', function(value:number) { + expect(value).to.be.equal(99); + done(); + }); + + var child = new d3kit.Chartlet(callback, callback, callback, ['foo']) + .publishEventsTo(parent.getDispatcher()); + + (child.getDispatcher()).foo(99); + }); + }); +}); + +describe('#createChart', function(){ + var Chart = d3kit.factory.createChart({}, ['test'], function(skeleton: d3kit.Skeleton){ + return skeleton; + }); + + it('should return a function to create a chart', function(){ + expect(Chart).to.be.a('Function'); + }); + + // // Don't think it's possible to define these in a d.ts file; skipping + // it('results should have function getCustomEvents()', function(){ + // expect(Chart.getCustomEvents).to.exist; + // expect(Chart.getCustomEvents()).to.deep.equal(['test']); + // }); +}); + +describe('d3kit.helper', function(){ + + describe('#dasherize(str)', function(){ + it('should convert input to dash-case', function(){ + expect(d3kit.helper.dasherize('camelCase')).to.equal('camel-case'); + }); + }); + + describe('#deepExtend(target, src1, src2, ...)', function(){ + it('should copy fields from sources into target', function(){ + expect(d3kit.helper.deepExtend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + })).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + + expect(d3kit.helper.deepExtend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + }, null)).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + }); + + it('should copy arrays and functions correctly from sources into target', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.deepExtend({}, { + a: fn1, + b: [1,2] + },{ + b: [3,4], + c: fn2 + })).to.deep.equal({ + a: fn1, + b: [3,4], + c: fn2 + }); + }); + + it('should perform "deep" copy', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.deepExtend({}, { + a: { d: fn1 }, + b: [1,2], + c: { f: 3 }, + h: { i: [1,2,3], j: [3,4,5] } + },{ + a: { e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } + })).to.deep.equal({ + a: { d: fn1, e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], j: [3,4,5], k: [3,4,5], l: {m: 2} } + }); + }); + }); + + describe('#extend(target, src1, src2, ...)', function(){ + it('should copy fields from sources into target', function(){ + expect(d3kit.helper.extend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + })).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + + expect(d3kit.helper.extend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + }, null)).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + }); + + it('should copy arrays and functions correctly from sources into target', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.extend({}, { + a: fn1, + b: [1,2] + },{ + b: [3,4], + c: fn2 + })).to.deep.equal({ + a: fn1, + b: [3,4], + c: fn2 + }); + }); + + it('should NOT perform "deep" copy', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.extend({}, { + a: { d: fn1 }, + b: [1,2], + c: { f: 3 }, + h: { i: [1,2,3], j: [3,4,5] } + },{ + a: { e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } + })).to.deep.equal({ + a: { e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } + }); + }); + }); + + describe('#isFunction(function)', function(){ + it('should return true if the value is a function', function(){ + var fn1 = function(d:number){return d + 1;}; + function fn2(d:number){return d + 2;} + + expect(d3kit.helper.isFunction(fn1)).to.be.true; + expect(d3kit.helper.isFunction(fn2)).to.be.true; + }); + it('should return false if the value is not a function', function(){ + expect(d3kit.helper.isFunction(0)).to.be.false; + expect(d3kit.helper.isFunction(1)).to.be.false; + expect(d3kit.helper.isFunction(true)).to.be.false; + expect(d3kit.helper.isFunction('what')).to.be.false; + expect(d3kit.helper.isFunction(null)).to.be.false; + expect(d3kit.helper.isFunction(undefined)).to.be.false; + }); + }); + + describe('#isNumber(value)', function(){ + it('should return true for number', function(){ + expect(d3kit.helper.isNumber(1)).to.be.true; + expect(d3kit.helper.isNumber(0)).to.be.true; + expect(d3kit.helper.isNumber(-1)).to.be.true; + }); + it('should return false for string even if it is a number', function(){ + expect(d3kit.helper.isNumber('')).to.be.false; + expect(d3kit.helper.isNumber('1')).to.be.false; + expect(d3kit.helper.isNumber('0')).to.be.false; + expect(d3kit.helper.isNumber('what')).to.be.false; + }); + it('should return false for null and undefined', function(){ + expect(d3kit.helper.isNumber(null)).to.be.false; + expect(d3kit.helper.isNumber(undefined)).to.be.false; + }); + }); +}); + diff --git a/d3kit/d3kit.d.ts b/d3kit/d3kit.d.ts new file mode 100644 index 0000000000..4e53472b7b --- /dev/null +++ b/d3kit/d3kit.d.ts @@ -0,0 +1,155 @@ +// Type definitions for d3Kit v1.1.0 +// Project: https://www.npmjs.com/package/d3kit +// Definitions by: Morgan Benton +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace d3kit { + + export interface ChartMargin { + top?: number; + right?: number; + bottom?: number; + left?: number; + } + + export interface ChartOptions { + margin?: ChartMargin; + offset?: [number,number]; + initialWidth?: number; + initialHeight?: number; + [name: string]: any; + } + + export interface ChartMixin { + [name: string]: any; + } + + export class Skeleton { + + constructor(selector: string|Element, options?: ChartOptions, customEvents?: Array); + + // Getters + getCustomEventNames(): Array; + getDispatcher(): any; // should be d3.Dispatch but this throws error for user-created events + getInnerWidth(): number; + getInnerHeight(): number; + getLayerOrganizer(): LayerOrganizer; + getRootG(): d3.Selection; + getSvg(): d3.Selection; + + // Getter/Setters + data(): any; + data(data?: any, doNotDispatch?: boolean): Skeleton; + options(): any; // wish this could be ChartOptions + options(options: ChartOptions, doNotDispatch?: boolean): Skeleton; + margin(): ChartMargin; + margin(margin: ChartMargin, doNotDispatch?: boolean): Skeleton; + offset(): [number, number]; + offset(offset: Array, doNotDispatch?: boolean): Skeleton; + width(): number; + width(value: number|string, doNotDispatch?: boolean): Skeleton; + height(): number; + height(value: number|string, doNotDispatch?: boolean): Skeleton; + dimension(): [number, number]; + dimension(dimension: [number|string, number|string], doNotDispatch?: boolean): Skeleton; + autoResize(mode?: string|boolean): string|boolean|void; + autoResizeDetection(method?:string): string|void; + autoResizeToAspectRatio(ratio?: number|boolean): number|boolean|void; + + // Other functions + on(eventName: string, listener: (...args: Array) => void): void; + hasData(): boolean; + hasNonZeroArea(): boolean; + mixin(fn: ChartMixin): void; + resizeToFitContainer(mode: string|boolean, doNotDispatch?: boolean): void; + resizeToAspectRatio(ratio: number, doNotDispatch?: boolean): void; + } + + interface ChartletPropertyCallback { + (datum?: any, datum_index?: number): any; + } + + export interface ChartletEventFunction { + (sel?: d3.Selection, done?: string): (sel: d3.Selection) => void; + } + + export class Chartlet { + + constructor( + enterFunction?: ChartletEventFunction, + updateFunction?: ChartletEventFunction, + exitFunction?: ChartletEventFunction, + customEventName?: Array); + + // Getter functions + getDispatcher(): d3.Dispatch; + getCustomEventNames(): Array; + getPropertyValue(name: string, datum: any, datum_index: number): any; + + // Getter/Setter functions + property(name: string): ChartletPropertyCallback; + property(name: string, value: any): Chartlet; + + // Enter/Update/Exit functions + enter( sel?: d3.Selection, done?: string): (sel: d3.Selection) => void; + update(sel?: d3.Selection, done?: string): (sel: d3.Selection) => void; + exit( sel?: d3.Selection, done?: string): (sel: d3.Selection) => void; + + // Inheritance functions + inheritPropertyFrom(parent_chartlet: Chartlet, parent_property_name: string, child_property_name?: string): void; + inheritPropertiesFrom(parent_chartlet: Chartlet, parent_property_names: Array, child_property_names?: Array): void; + publishEventsTo(dispatcher: d3.Dispatch): Chartlet; + + // Events + on(eventName: string, handlerFunction: ChartletEventFunction): void; + } + + interface LayerConfig { + name?: string, + names?: Array, + sublayers?: LayerConfig + } + + export class LayerOrganizer { + + constructor(container: d3.Selection, tag?: string); + + create(config: string|Array|LayerConfig|Array): d3.Selection|Array>; + get(name: string): d3.Selection; + has(name: string): boolean; + } + + export namespace factory { + export function createChart( + defaultOptions: ChartOptions, + customEvents: Array, + constructor: (skeleton: Skeleton) => void + ): (selector: string|Element, options?: ChartOptions, customEvents?: Array) => Skeleton; + } + + export namespace helper { + export function debounce(fn: (...args: Array) => void, wait: number, immediate: boolean): (...args: Array) => void; + export function extend(target: Object, ...args: Object[]): Object; + export function deepExtend(target: Object, ...args: Object[]): Object; + export function bindMouseEventsToDispatcher(selection: d3.Selection, dispatch: d3.Dispatch, prefix: string): void; + export function removeAllChildren(selection: d3.Selection, noTransition: boolean): d3.Selection; + export function on(element: Element, type: string, listener: (...args: Array) => void): void; + export function off(element: Element, type: string, listener: (...args: Array) => void): void; + export function trim(str: string, characters: string): string; + export function dasherize(str: string): string; + export function $(s: Element|string): Element; + export function $$(s: Array|NodeList): Array; + export function isArray(value: any): boolean; + export function isNumber(value: any): boolean; + export function isObject(value: any): boolean; + export function isElement(o: any): boolean; + export function isFunction(functionToCheck: any): boolean; + } + +} + +declare module 'd3kit' { + export = d3kit; +} \ No newline at end of file diff --git a/d3pie/d3pie-tests.ts b/d3pie/d3pie-tests.ts new file mode 100644 index 0000000000..4d8a38280f --- /dev/null +++ b/d3pie/d3pie-tests.ts @@ -0,0 +1,146 @@ +/// + +let chart = new d3pie('test', + { + header: { + title: { + text: '', + color: '#333333', + fontSize: 18, + font: 'arial' + }, + subtitle: { + color: '#666666', + fontSize: 14, + font: 'arial' + }, + location: 'top-center', + titleSubtitlePadding: 8 + }, + footer: { + text: '', + color: '#666666', + fontSize: 14, + font: 'arial', + location: 'left' + }, + size: { + canvasHeight: 500, + canvasWidth: 500, + pieInnerRadius: 0, + pieOuterRadius: null + }, + data: { + sortOrder: 'none', + smallSegmentGrouping: { + enabled: false, + value: 1, + valueType: 'percentage', + label: 'Other', + color: '#cccccc' + }, + content: [] + }, + labels: { + outer: { + format: 'label', + hideWhenLessThanPercentage: null, + pieDistance: 30 + }, + inner: { + format: 'percentage', + hideWhenLessThanPercentage: null + }, + mainLabel: { + color: '#333333', + font: 'arial', + fontSize: 10 + }, + percentage: { + color: '#dddddd', + font: 'arial', + fontSize: 10, + decimalPlaces: 0 + }, + value: { + color: '#cccc44', + font: 'arial', + fontSize: 10 + }, + lines: { + enabled: true, + style: 'curved', + color: 'segment' // 'segment' or a hex color + } + }, + effects: { + load: { + effect: 'default', // none / default + speed: 1000 + }, + pullOutSegmentOnClick: { + effect: 'bounce', // none / linear / bounce / elastic / back + speed: 300, + size: 10 + }, + highlightSegmentOnMouseover: true, + highlightLuminosity: -0.2 + }, + tooltips: { + enabled: false, + type: 'placeholder', // caption|placeholder + string: '', + placeholderParser: null, + styles: { + fadeInSpeed: 250, + backgroundColor: '#000000', + backgroundOpacity: 0.5, + color: '#efefef', + borderRadius: 2, + font: 'arial', + fontSize: 10, + padding: 4 + } + }, + + misc: { + colors: { + background: null, // transparent + segments: [ + '#2484c1', '#65a620', '#7b6888', '#a05d56', '#961a1a', + '#d8d23a', '#e98125', '#d0743c', '#635222', '#6ada6a', + '#0c6197', '#7d9058', '#207f33', '#44b9b0', '#bca44a', + '#e4a14b', '#a3acb2', '#8cc3e9', '#69a6f9', '#5b388f', + '#546e91', '#8bde95', '#d2ab58', '#273c71', '#98bf6e', + '#4daa4b', '#98abc5', '#cc1010', '#31383b', '#006391', + '#c2643f', '#b0a474', '#a5a39c', '#a9c2bc', '#22af8c', + '#7fcecf', '#987ac6', '#3d3b87', '#b77b1c', '#c9c2b6', + '#807ece', '#8db27c', '#be66a2', '#9ed3c6', '#00644b', + '#005064', '#77979f', '#77e079', '#9c73ab', '#1f79a7' + ], + segmentStroke: '#ffffff' + }, + gradient: { + enabled: false, + percentage: 95, + color: '#000000' + }, + canvasPadding: { + top: 5, + right: 5, + bottom: 5, + left: 5 + }, + pieCenterOffset: { + x: 0, + y: 0 + }, + cssPrefix: null + }, + callbacks: { + onload: null, + onMouseoverSegment: null, + onMouseoutSegment: null, + onClickSegment: null + } + }) \ No newline at end of file diff --git a/d3pie/d3pie.d.ts b/d3pie/d3pie.d.ts new file mode 100644 index 0000000000..2bfe5d6525 --- /dev/null +++ b/d3pie/d3pie.d.ts @@ -0,0 +1,146 @@ +// Type definitions for d3pie 0.1.9 +// Project: https://github.com/benkeen/d3pie +// Definitions by: Petryshyn Sergii +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace d3pie { + interface ID3PieChart { + redraw(): void + openSegment(index: number): void + closeSegment(index: void): void + getOpenSegment(): any + updateProp(propKey: string, value: any): void + destroy(): void + } + + interface ID3PieStyleOptions { + color?: string + fontSize?: number + font?: string + } + + interface ID3PieTextOptions extends ID3PieStyleOptions { + text?: string + } + + interface ID3PieLabelsOptions { + format?: 'label' | 'value' | 'percentage' | 'label-value1' | 'label-value2' | 'label-percentage1' | 'label-percentage2' + hideWhenLessThanPercentage?: number + } + + interface ID3PieOptions { + header?: { + title?: ID3PieTextOptions + subtitle?: ID3PieTextOptions + location?: 'top-center' | 'top-left' | 'pie-center' + titleSubtitlePadding?: number + } + footer?: { location?: 'left' } & ID3PieTextOptions + size?: { + canvasHeight?: number + canvasWidth?: number + pieOuterRadius?: string | number + pieInnerRadius?: string | number + } + data: { + sortOrder?: 'none' | 'random' | 'value-asc' | 'value-desc' | 'label-asc' | 'label-desc' + smallSegmentGrouping?: { + enabled?: boolean + value?: number + valueType?: 'percentage' | 'value' + label?: string + color?: string + } + content: { + label: string + value: number + color?: string + }[] + } + labels?: { + outer?: { pieDistance?: number } & ID3PieLabelsOptions + inner?: ID3PieLabelsOptions + mainLabel?: ID3PieStyleOptions + percentage?: { decimalPlaces?: number } & ID3PieStyleOptions + value?: ID3PieStyleOptions + lines?: { + enabled?: boolean + style?: 'curved' | 'straight' + color?: string + } + truncation?: { + enabled?: boolean + truncateLength?: number + } + formatter?: (context: { + section: 'outer' | 'inner' + value: number + label: string + }) => string + } + effects?: { + load?: { + effect?: 'none' | 'default' + speed?: number + } + pullOutSegmentOnClick?: { + effect?: 'none' | 'linear' | 'bounce' | 'elastic' | 'back' + speed?: number + size?: number + } + highlightSegmentOnMouseover?: boolean + highlightLuminosity?: number + } + tooltips?: { + enabled?: boolean + type?: 'placeholder' | 'caption' + string?: string + placeholderParser?: (index: number, data: { label?: string, percentage?: number, value?: number }) => void + styles?: { + fadeInSpeed?: number + backgroundColor?: string + backgroundOpacity?: number + color?: string + borderRadius?: number + font?: string + fontSize?: number + padding?: number + } + } + misc?: { + colors?: { + background?: string + segments?: string[] + segmentStroke?: string + } + gradient?: { + enabled?: boolean + percentage?: number + color?: string + } + canvasPadding?: { + top?: number + right?: number + bottom?: number + left?: number + } + pieCenterOffset?: { + x?: number + y?: number + } + cssPrefix?: string + } + callbacks?: { + onload?: Function + onMouseoverSegment?: Function + onMouseoutSegment?: Function + onClickSegment?: Function + } + } + + interface ID3PieClass { + new (id: string | HTMLElement, options: ID3PieOptions): ID3PieChart + } +} + +declare const d3pie: d3pie.ID3PieClass \ No newline at end of file diff --git a/dagre-d3/dagre-d3-tests.ts b/dagre-d3/dagre-d3-tests.ts index 836ae6f291..d5e712a66c 100644 --- a/dagre-d3/dagre-d3-tests.ts +++ b/dagre-d3/dagre-d3-tests.ts @@ -11,6 +11,9 @@ namespace DagreD3Tests { predecessors["a"] = graph.predecessors("a"); successors["a"] = graph.successors("a"); + graph.transition = (selection: d3.Selection) => { + return d3.transition(); + }; const render = new dagreD3.render(); const svg = d3.select("svg"); diff --git a/dagre-d3/dagre-d3.d.ts b/dagre-d3/dagre-d3.d.ts index cbf3bf458a..9248222e98 100644 --- a/dagre-d3/dagre-d3.d.ts +++ b/dagre-d3/dagre-d3.d.ts @@ -19,6 +19,8 @@ declare namespace Dagre { height: number; predecessors(id: string): string[]; successors(id: string): string[]; + // see source of http://cpettitt.github.io/project/dagre-d3/latest/demo/interactive-demo.html + transition?(selection: d3.Selection): d3.Transition; width: number; } diff --git a/express-serve-static-core/express-serve-static-core.d.ts b/express-serve-static-core/express-serve-static-core.d.ts index 2662222d00..e15dbcb5b6 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -17,21 +17,23 @@ declare namespace Express { declare module "express-serve-static-core" { import * as http from "http"; + type RequestHandlerParams = RequestHandler | RequestHandler[]; + interface IRoute { path: string; stack: any; - all(...handler: RequestHandler[]): IRoute; - get(...handler: RequestHandler[]): IRoute; - post(...handler: RequestHandler[]): IRoute; - put(...handler: RequestHandler[]): IRoute; - delete(...handler: RequestHandler[]): IRoute; - patch(...handler: RequestHandler[]): IRoute; - options(...handler: RequestHandler[]): IRoute; - head(...handler: RequestHandler[]): IRoute; + all(...handler: RequestHandlerParams[]): IRoute; + get(...handler: RequestHandlerParams[]): IRoute; + post(...handler: RequestHandlerParams[]): IRoute; + put(...handler: RequestHandlerParams[]): IRoute; + delete(...handler: RequestHandlerParams[]): IRoute; + patch(...handler: RequestHandlerParams[]): IRoute; + options(...handler: RequestHandlerParams[]): IRoute; + head(...handler: RequestHandlerParams[]): IRoute; } interface IRouterMatcher { - (name: string | RegExp, ...handlers: RequestHandler[]): T; + (name: string | RegExp, ...handlers: RequestHandlerParams[]): T; } interface IRouter extends RequestHandler { @@ -88,13 +90,13 @@ declare module "express-serve-static-core" { route(path: string): IRoute; - use(...handler: RequestHandler[]): T; - use(handler: ErrorRequestHandler | RequestHandler): T; - use(path: string, ...handler: RequestHandler[]): T; - use(path: string, handler: ErrorRequestHandler | RequestHandler): T; - use(path: string[], ...handler: RequestHandler[]): T; + use(...handler: RequestHandlerParams[]): T; + use(handler: ErrorRequestHandler | RequestHandlerParams): T; + use(path: string, ...handler: RequestHandlerParams[]): T; + use(path: string, handler: ErrorRequestHandler | RequestHandlerParams): T; + use(path: string[], ...handler: RequestHandlerParams[]): T; use(path: string[], handler: ErrorRequestHandler): T; - use(path: RegExp, ...handler: RequestHandler[]): T; + use(path: RegExp, ...handler: RequestHandlerParams[]): T; use(path: RegExp, handler: ErrorRequestHandler): T; use(path: string, router: Router): T; } @@ -860,7 +862,7 @@ declare module "express-serve-static-core" { set(setting: string, val: any): Application; get: { (name: string): any; // Getter - (name: string | RegExp, ...handlers: RequestHandler[]): Application; + (name: string | RegExp, ...handlers: RequestHandlerParams[]): Application; }; /** diff --git a/fbemitter/fbemitter.d.ts b/fbemitter/fbemitter.d.ts index b26b1a3162..0f5f6af528 100644 --- a/fbemitter/fbemitter.d.ts +++ b/fbemitter/fbemitter.d.ts @@ -3,7 +3,7 @@ // Definitions by: kmxz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'fbemitter' { +declare namespace FBEmitter { export class EventSubscription { @@ -64,4 +64,8 @@ declare module 'fbemitter' { } -} \ No newline at end of file +} + +declare module 'fbemitter' { + export = FBEmitter; +} diff --git a/flux/flux-tests.ts b/flux/flux-tests.ts index 24369ef2dd..6bb4350dc6 100644 --- a/flux/flux-tests.ts +++ b/flux/flux-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// import flux = require('flux') import FluxUtils = require('flux/utils') @@ -88,7 +88,7 @@ export = customDispatcher // Sample Reduce Store -class CounterStore extends FluxUtils.ReduceStore { +class CounterStore extends FluxUtils.ReduceStore { getInitialState(): number { return 0; } @@ -126,4 +126,4 @@ class CounterContainer extends Component { } } -const container = Container.create(CounterContainer); +const container = Container.create(CounterContainer); diff --git a/flux/flux.d.ts b/flux/flux.d.ts index 944d23b011..944aa54f3a 100644 --- a/flux/flux.d.ts +++ b/flux/flux.d.ts @@ -4,6 +4,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// +/// declare namespace Flux { @@ -71,6 +73,29 @@ declare module "flux" { declare namespace FluxUtils { import React = __React; + import fbEmitter = FBEmitter; + import immutable = Immutable; + + /** + * Default options to create a Container with + * + * @interface RealOptions + */ + interface RealOptions { + /** + * Default value: true + * + * @type {boolean} + */ + pure?: boolean; + /** + * Default value: false + * + * @type {boolean} + */ + withProps?: boolean; + } + export class Container { constructor(); /** @@ -78,14 +103,13 @@ declare namespace FluxUtils { * that updates its state when relevant stores change. * The provided base class must have static methods getStores() and calculateState(). */ - static create(base: React.ComponentClass, options?: any): React.ComponentClass; + static create(base: React.ComponentClass, options?: RealOptions): React.ComponentClass; } /** * This class extends ReduceStore and defines the state as an immutable map. */ - // TODO: Change to > - export class MapStore extends ReduceStore { + export class MapStore extends ReduceStore, TPayload> { /** * Access the value at the given key. * Throws an error if the key does not exist in the cache. @@ -108,12 +132,10 @@ declare namespace FluxUtils { * it allows providing a previous result to update instead of generating a new map. * Providing a previous result allows the possibility of keeping the same reference if the keys did not change. */ - // TODO: Update with Immutable interface. - // getAll(keys: Immutable.IndexedIterable, prev?: Immutable.Map): Immutable.Map; - getAll(keys: any, prev?: any): any; + getAll(keys: immutable.Iterable.Indexed, prev?: immutable.Map): immutable.Map; } - export class ReduceStore extends Store { + export class ReduceStore extends Store { /** * Getter that exposes the entire state of this store. * If your state is not immutable you should override this and not expose state directly. @@ -131,7 +153,7 @@ declare namespace FluxUtils { * All subclasses must implement this method. * This method should be pure and have no side-effects. */ - reduce(state: T, action: any): T; + reduce(state: T, action: TPayload): T; /** * Checks if two versions of state are the same. @@ -141,24 +163,24 @@ declare namespace FluxUtils { } - export class Store { + export class Store { /** * Constructs and registers an instance of this store with the given dispatcher. */ - constructor(dispatcher: Flux.Dispatcher); + constructor(dispatcher: Flux.Dispatcher); /** * Adds a listener to the store, when the store changes the given callback will be called. * A token is returned that can be used to remove the listener. * Calling the remove() function on the returned token will remove the listener. */ - addListener(callback: Function): { remove: Function }; + addListener(callback: Function): fbEmitter.EventSubscription; /** * Returns the dispatcher this store is registered with. */ - getDispatcher(): Flux.Dispatcher; + getDispatcher(): Flux.Dispatcher; /** * Returns the dispatch token that the dispatcher recognizes this store by. @@ -185,7 +207,7 @@ declare namespace FluxUtils { * This is how the store receives actions from the dispatcher. * All state mutation logic must be done during this method. */ - __onDispatch(payload: any): void; + __onDispatch(payload: TPayload): void; } } diff --git a/geojson/geojson-tests.ts b/geojson/geojson-tests.ts index ce38b654b2..75cf6ffd54 100644 --- a/geojson/geojson-tests.ts +++ b/geojson/geojson-tests.ts @@ -72,6 +72,11 @@ var point: GeoJSON.Point = { coordinates: [100.0, 0.0] }; + +// This type is commonly used in the turf package +var pointCoordinates: number[] = point.coordinates + + var lineString: GeoJSON.LineString = { type: "LineString", coordinates: [ [100.0, 0.0], [101.0, 1.0] ] @@ -126,4 +131,4 @@ var geometryCollection: GeoJSON.GeometryCollection = { coordinates: [ [101.0, 0.0], [102.0, 1.0] ] } ] -} \ No newline at end of file +} diff --git a/geojson/geojson.d.ts b/geojson/geojson.d.ts index 4b4c2b56cf..38715a9a27 100644 --- a/geojson/geojson.d.ts +++ b/geojson/geojson.d.ts @@ -18,10 +18,7 @@ declare namespace GeoJSON { /*** * http://geojson.org/geojson-spec.html#positions */ - export interface Position - { - [index: number]: number; - } + export type Position = number[] /*** * http://geojson.org/geojson-spec.html#geometry-objects diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index c1a1fbfaf0..9a75f9699e 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -322,6 +322,11 @@ app.on('login', function(event, webContents, request, authInfo, callback) { callback('username', 'secret'); }); +var win = new BrowserWindow({show: false}) +win.once('ready-to-show', () => { + win.show(); +}); + app.relaunch({args: process.argv.slice(1).concat(['--relaunch'])}); app.exit(0); @@ -354,6 +359,8 @@ win.show(); var toolbarRect = document.getElementById('toolbar').getBoundingClientRect(); win.setSheetOffset(toolbarRect.height); +var installed = BrowserWindow.getDevToolsExtensions().hasOwnProperty('devtron'); + // content-tracing // https://github.com/atom/electron/blob/master/docs/api/content-tracing.md @@ -728,6 +735,8 @@ var image = clipboard.readImage(); var appIcon3 = new Tray(image); var appIcon4 = new Tray('/Users/somebody/images/icon.png'); +let image2 = nativeImage.createFromPath('/Users/somebody/images/icon.png'); + // process // https://github.com/electron/electron/blob/master/docs/api/process.md @@ -828,15 +837,23 @@ session.defaultSession.on('will-download', (event, item, webContents) => { console.log(item.getFilename()); console.log(item.getTotalBytes()); - item.on('updated', function() { - console.log('Received bytes: ' + item.getReceivedBytes()); + item.on('updated', (event, state) => { + if (state === 'interrupted') { + console.log('Download is interrupted but can be resumed'); + } else if (state === 'progressing') { + if (item.isPaused()) { + console.log('Download is paused'); + } else { + console.log(`Received bytes: ${item.getReceivedBytes()}`); + } + } }); item.on('done', function(e, state) { if (state == "completed") { console.log("Download successfully"); } else { - console.log("Download is cancelled or interrupted that can't be resumed"); + console.log(`Download failed: ${state}`) } }); }); @@ -884,3 +901,15 @@ session.defaultSession.webRequest.onBeforeSendHeaders(filter, function(details, details.requestHeaders['User-Agent'] = "MyAgent"; callback({cancel: false, requestHeaders: details.requestHeaders}); }); + +app.on('ready', function () { + const protocol = session.defaultSession.protocol + protocol.registerFileProtocol('atom', function (request, callback) { + var url = request.url.substr(7); + callback({path: path.normalize(__dirname + '/' + url)}); + }, function (error) { + if (error) { + console.error('Failed to register protocol'); + } + }) +}); diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 00730cb680..f7dd206708 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.2.2 +// Type definitions for Electron v1.2.3 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -115,6 +115,10 @@ declare namespace Electron { * Emitted when a new browserWindow is created. */ on(event: 'browser-window-created', listener: (event: Event, browserWindow: BrowserWindow) => void): this; + /** + * Emitted when a new webContents is created. + */ + on(event: 'web-contents-created', listener: (event: Event, webContents: WebContents) => void): this; /** * Emitted when failed to verify the certificate for url, to trust the certificate * you should prevent the default behavior with event.preventDefault() and call callback(true). @@ -344,7 +348,7 @@ declare namespace Electron { dock: Dock; } - type AppPathName = 'home'|'appData'|'userData'|'temp'|'exe'|'module'|'desktop'|'documents'|'downloads'|'music'|'pictures'|'videos'; + type AppPathName = 'home'|'appData'|'userData'|'temp'|'exe'|'module'|'desktop'|'documents'|'downloads'|'music'|'pictures'|'videos'|'pepperFlashSystemPlugin'; interface ImportCertificateOptions { /** @@ -498,9 +502,8 @@ declare namespace Electron { on(event: string, listener: Function): this; /** * Set the url and initialize the auto updater. - * The url cannot be changed once it is set. */ - setFeedURL(url: string): void; + setFeedURL(url: string, requestHeaders?: Headers): void; /** * Ask the server whether there is an update, you have to call setFeedURL * before using this API @@ -559,6 +562,10 @@ declare namespace Electron { * Emitted when the window is hidden. */ on(event: 'hide', listener: Function): this; + /** + * Emitted when the web page has been rendered and window can be displayed without visual flash. + */ + on(event: 'ready-to-show', listener: Function): this; /** * Emitted when window is maximized. */ @@ -650,6 +657,10 @@ declare namespace Electron { * @param name The name of the devtools extension to remove. */ static removeDevToolsExtension(name: string): void; + /** + * @returns devtools extensions. + */ + static getDevToolsExtensions(): DevToolsExtensions; /** * The WebContents object this window owns, all web page related events and * operations would be done via it. @@ -996,7 +1007,7 @@ declare namespace Electron { */ setThumbarButtons(buttons: ThumbarButton[]): boolean; /** - * Shows pop-up dictionary that searches the selected word on the page. + * Same as webContents.showDefinitionForSelection(). * Note: This API is available only on OS X. */ showDefinitionForSelection(): void; @@ -1042,6 +1053,11 @@ declare namespace Electron { * but if this window has focus, it will still receive keyboard events. */ setIgnoreMouseEvents(ignore: boolean): void; + /** + * Changes whether the window can be focused. + * Note: This API is available only on Windows. + */ + setFocusable(focusable: boolean): void; } type SwipeDirection = 'up' | 'right' | 'down' | 'left'; @@ -1055,6 +1071,13 @@ declare namespace Electron { flags?: ThumbarButtonFlags[]; } + interface DevToolsExtensions { + [name: string]: { + name: string; + value: string; + } + } + interface WebPreferences { /** * Whether node integration is enabled. @@ -1290,6 +1313,14 @@ declare namespace Electron { * Default: true. */ closable?: boolean; + /** + * Whether the window can be focused. + * On Windows setting focusable: false also implies setting skipTaskbar: true. + * On Linux setting focusable: false makes the window stop interacting with wm, + * so the window will always stay on top in all workspaces. + * Default: true. + */ + focusable?: boolean; /** * Whether the window should always stay on top of other windows. * Default: false. @@ -1832,9 +1863,9 @@ declare namespace Electron { */ interface DownloadItem extends NodeJS.EventEmitter { /** - * Emits when the downloadItem gets updated. + * Emitted when the download has been updated and is not done. */ - on(event: 'updated', listener: Function): this; + on(event: 'updated', listener: (event: Event, state: 'progressing' | 'interrupted') => void): this; /** * Emits when the download is in a terminal state. This includes a completed download, * a cancelled download (via downloadItem.cancel()), and interrupted download that can’t be resumed. @@ -1852,10 +1883,18 @@ declare namespace Electron { * Pauses the download. */ pause(): void; + /** + * @returns Whether the download is paused. + */ + isPaused(): boolean; /** * Resumes the download that has been paused. */ resume(): void; + /** + * @returns Whether the download can resume. + */ + canResume(): boolean; /** * Cancels the download operation. */ @@ -1891,6 +1930,10 @@ declare namespace Electron { * @returns The Content-Disposition field from the response header. */ getContentDisposition(): string; + /** + * @returns The current state. + */ + getState(): 'progressing' | 'completed' | 'cancelled' | 'interrupted'; } // https://github.com/electron/electron/blob/master/docs/api/global-shortcut.md @@ -2042,7 +2085,7 @@ declare namespace Electron { type MenuItemType = 'normal' | 'separator' | 'submenu' | 'checkbox' | 'radio'; type MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteandmatchstyle' | 'selectall' | 'delete' | 'minimize' | 'close'; - type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'front' | 'window' | 'help' | 'services'; + type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'front' | 'zoom' | 'window' | 'help' | 'services'; interface MenuItemOptions { /** @@ -2635,6 +2678,10 @@ declare namespace Electron { * The webRequest API set allows to intercept and modify contents of a request at various stages of its lifetime. */ webRequest: WebRequest; + /** + * @returns An instance of protocol module for this session. + */ + protocol: Protocol; } type Permission = 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal'; @@ -3643,6 +3690,11 @@ declare namespace Electron { * @returns If the process of saving page has been initiated successfully. */ savePage(fullPath: string, saveType: 'HTMLOnly' | 'HTMLComplete' | 'MHTML', callback?: (eror: Error) => void): boolean; + /** + * Shows pop-up dictionary that searches the selected word on the page. + * Note: This API is available only on OS X. + */ + showDefinitionForSelection(): void; /** * @returns The unique ID of this WebContents. */ @@ -4428,6 +4480,11 @@ declare namespace Electron { * See webContents.sendInputEvent for detailed description of event object. */ sendInputEvent(event: SendInputEvent): void + /** + * Shows pop-up dictionary that searches the selected word on the page. + * Note: This API is available only on OS X. + */ + showDefinitionForSelection(): void; /** * @returns The WebContents associated with this webview. */ diff --git a/globalize/globalize.d.ts b/globalize/globalize.d.ts index 8eeec964eb..d3bf7997d5 100644 --- a/globalize/globalize.d.ts +++ b/globalize/globalize.d.ts @@ -1,28 +1,330 @@ -// Type definitions for Globalize +// Type definitions for Globalize // Project: https://github.com/jquery/globalize -// Definitions by: Aram Taieb -// Definitions: https://github.com/afromogli/DefinitelyTyped +// Definitions by: Grégoire Castre , Aram Taieb +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Note: You'll need the cldr.js definition file to use the globalize (https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/cldr.js) -interface NumberFormatterOptions { - minimumIntegerDigits?: number; - minimumFractionDigits?: number; - maximumFractionDigits?: number; - minimumSignificantDigits?: number; - maximumSignificantDigits?: number; - round?: string; - useGrouping?: boolean; +/// + +interface DateFormatterOptions { + /** + * String value indicating a skeleton (see description above), eg. { skeleton: "GyMMMd" }. + * Skeleton provides a more flexible formatting mechanism than the predefined list full, long, medium, or short represented by date, time, or datetime. + * Instead, they are an open-ended list of patterns containing only date field information, and in a canonical order. + */ + skeleton?: string; + /** + * One of the following String values: full, long, medium, or short, eg. { date: "full" }. + */ + date?: "full" | "long" | "medium" | "short"; + /** + * One of the following String values: full, long, medium, or short, eg. { time: "full" }. + */ + time?: "full" | "long" | "medium" | "short"; + /** + * One of the following String values: full, long, medium, or short, eg. { datetime: "full" } + */ + datetime?: "full" | "long" | "medium" | "short"; + /** + * String value indicating a machine raw pattern (anything in the "Sym." column) eg. { raw: "dd/mm" }. + * Note this is NOT recommended for i18n in general. Use skeleton instead. + */ + raw?: string; } -interface Cldr { - /* TODO: add typings */ +interface CommonNumberFormatterOptions { + /** + * Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary. + */ + minimumIntegerDigits?: number; + /** + * Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. + * Numbers will be rounded or padded with trailing zeroes if necessary. + * Either one or both of these properties must be present. + * If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns. + */ + minimumFractionDigits?: number; + /** + * Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. + * Numbers will be rounded or padded with trailing zeroes if necessary. + * Either one or both of these properties must be present. + * If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns. + */ + maximumFractionDigits?: number; + /** + * Positive integer Number values indicating the minimum and maximum fraction digits to be shown. + * Either none or both of these properties are present + * If they are, they override minimum and maximum integer and fraction digits. + * The formatter uses however many integer and fraction digits are required to display the specified number of significant digits. + */ + minimumSignificantDigits?: number; + /** + * Positive integer Number values indicating the minimum and maximum fraction digits to be shown. + * Either none or both of these properties are present. + * If they are, they override minimum and maximum integer and fraction digits. + * The formatter uses however many integer and fraction digits are required to display the specified number of significant digits. + */ + maximumSignificantDigits?: number; + /** + * String with rounding method ceil, floor, round (default), or truncate. + */ + round?: "ceil" | "floor" | "round" | "truncate"; + /** + * Boolean (default is true) value indicating whether a grouping separator should be used. + */ + useGrouping?: boolean; +} + +interface NumberFormatterOptions extends CommonNumberFormatterOptions { + /** + * decimal (default), or percent + */ + style?: "decimal" | "percent"; +} + +interface CurrencyFormatterOptions extends CommonNumberFormatterOptions { + /** + * symbol (default), accounting, code or name. + */ + style?: "symbol" | "accounting" | "code" | "name"; +} + +interface NumberParserOptions { + /** + * decimal (default), or percent. + */ + style?: "decimal" | "percent"; +} + +interface PluralGeneratorOptions { + /** + * cardinal (default), or ordinal. + */ + type?: "cardinal" | "ordinal"; +} + +interface RelativeTimeFormatterOptions { + /** + * eg. "short" or "narrow". Or falsy for default long form + */ + form?: "short" | "narrow"; +} + +interface UnitFormatterOptions { + /** + * form: [String] eg. "long", "short" or "narrow". + */ + form?: "long" | "short" | "narrow"; + + /** + * numberFormatter: [Function] a number formatter function. Defaults to Globalize .numberFormatter() for the current locale using the default options. + */ + numberFormatter?: NumberFormatterOptions; } interface GlobalizeStatic { - load(jsonData: any): void; - locale(locale: string): Cldr; - numberFormatter(options?: NumberFormatterOptions): (value: number) => string; - formatNumber(value:number, options?: NumberFormatterOptions): string; + cldr: cldr.CldrStatic; + + /** + * Globalize.load( json, ... ) + * @param {Object} [JSON] + * Load resolved or unresolved cldr data. + * Somewhat equivalent to previous Globalize.addCultureInfo(...). + */ + load(json: Object): void; + + /** + * Globalize.locale() + * Return the default Cldr instance. + */ + locale(): cldr.CldrStatic; + + /** + * Globalize.locale( [locale] ) + * @param {string} locale + * Set default Cldr instance + * Return the default Cldr instance. + */ + + locale(locale: string): cldr.CldrStatic; + /** + * Globalize.locale( cldr ) + * @param {Cldr} cldr [Cldr instance] + * Set default Cldr instance + * Return the default Cldr instance. + */ + locale(cldr: cldr.CldrStatic): cldr.CldrStatic; + + /** + * .dateFormatter( options ) + * @param {DateFormatterOptions} options see date/expand_pattern for more info. + * @returns {Function} Return a function that formats a date according to the given `options` and the default/instance locale. + */ + dateFormatter(options?: DateFormatterOptions): (value: Date) => string; + + //Return a function that parses a string representing a date into a JavaScript Date object according to the given options. The default parsing assumes numeric year, month, and day (i.e., { skeleton: "yMd" }). + dateParser(options?: DateFormatterOptions): (value: string) => Date; + + //Alias for .dateFormatter( [options] )( value ). + formatDate(value: Date, options?: DateFormatterOptions): string; + /** + * Alias for .dateParser( [options] )( value ). + * @param {string} value The object whose module id you wish to determine. + * @param {DateFormatterOptions} options The object whose module id you wish to determine. + * @returns {Date} Return the value as a Date. + */ + parseDate(value: string, options?: DateFormatterOptions): Date; + + /** + * Load messages data. + * @param {Object} json JSON object of messages data. Keys can use any character, except /, { and }. Values (i.e., the message content itself) can contain any character. + * @returns {void} + */ + loadMessages(json: Object): void; + /** + * Return a function that formats a message (using ICU message format pattern) given its path and a set of variables into a user-readable string. It supports pluralization and gender inflections. + * @param path String or Array containing the path of the message content, eg. "greetings/bye", or [ "greetings", "bye" ]. + * @returns {Function} Return A function that formats a message (using ICU message format pattern) given its path and a set of variables into a user-readable string. It supports pluralization and gender inflections. + */ + messageFormatter(path: string | string[]): (variables?: string | string[] | Object) => string; + + /** + * Formats a message (using ICU message format pattern) given its path and a set of variables into a user-readable string + * @param path String or Array containing the path of the message content, eg. "greetings/bye", or [ "greetings", "bye" ]. + * @param variables Variables can be Objects, where each property can be referenced by name inside a message; or Arrays, where each entry of the Array can be used inside a message, using numeric indices. When passing one or more arguments of other types, they're converted to an Array and used as such. + * @returns {string} Return a user-readable string. + */ + formatMessage(path: string | string[], variables?: string | string[] | Object): string + + /** + * Return a function that formats a number according to the given options or locale's defaults. + * @param {NumberFormatterOptions} options A JSON object including none or any of the following options. + * style Optional String decimal (default), or percent. + * minimumIntegerDigits Optional Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary. + * minimumFractionDigits and maximumFractionDigits Optional Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. Numbers will be rounded or padded with trailing zeroes if necessary. Either one or both of these properties must be present. If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns. + * minimumSignificantDigits and maximumSignificantDigits Optional Positive integer Number values indicating the minimum and maximum fraction digits to be shown. Either none or both of these properties are present. If they are, they override minimum and maximum integer and fraction digits. The formatter uses however many integer and fraction digits are required to display the specified number of significant digits. + * round Optional String with rounding method ceil, floor, round (default), or truncate. + * useGrouping Optional Boolean (default is true) value indicating whether a grouping separator should be used. + * @returns {Function} Return a function that formats a number according to the given options. + */ + numberFormatter(options?: NumberFormatterOptions): (value: number) => string; + + /** + * Return a function that parses a string representing a number according to the given options or locale's defaults. + * @param {NumberParserOptions} options A JSON object including none or any of the following options. + * style Optional String decimal (default), or percent. + * @returns {Function} Return a function that parses a String representing a number according to the given options. If value is invalid, NaN is returned. + */ + numberParser(options?: NumberParserOptions): (value: string) => number + + /** + * Return a number formatted according to the given options or locale's defaults. + * @param {number} value The number to format + * @param {NumberFormatterOptions} options A JSON object including none or any of the following options. + * style Optional String decimal (default), or percent. + * minimumIntegerDigits Optional Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary. + * minimumFractionDigits and maximumFractionDigits Optional Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. Numbers will be rounded or padded with trailing zeroes if necessary. Either one or both of these properties must be present. If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns. + * minimumSignificantDigits and maximumSignificantDigits Optional Positive integer Number values indicating the minimum and maximum fraction digits to be shown. Either none or both of these properties are present. If they are, they override minimum and maximum integer and fraction digits. The formatter uses however many integer and fraction digits are required to display the specified number of significant digits. + * round Optional String with rounding method ceil, floor, round (default), or truncate. + * useGrouping Optional Boolean (default is true) value indicating whether a grouping separator should be used. + * @returns {string} Return the number formatted + */ + formatNumber(value: number, options?: NumberFormatterOptions): string; + + /** + * A function that parses a string representing a number according to the given options or locale's defaults. + * @param {string} value The number as string to parse + * @param {NumberParserOptions} options A JSON object including none or any of the following options. + * style Optional String decimal (default), or percent. + * @returns {number} Return a number according to the given options. If value is invalid, NaN is returned. + */ + parseNumber(value: string, options?: NumberParserOptions): number; + + /** + * Return a function that formats a currency according to the given options or locale's defaults. + * The returned function is invoked with one argument: the Number value to be formatted. + * @param {string} currency 3-letter currency code as defined by ISO 4217, eg. USD. + * @param {CurrencyFormatterOptions} options A JSON object including none or any of the following options. + * @returns {Function} Return a function that formats a currency + */ + currencyFormatter(currency: string, options?: CurrencyFormatterOptions): (value: number) => string; + + /** + * Return a currency formatted according to the given options or locale's defaults. + * @param {number} value The value to format. + * @param {string} currency 3-letter currency code as defined by ISO 4217, eg. USD. + * @param {CurrencyFormatterOptions} options A JSON object including none or any of the following options. + * @returns {string} Return a string formatted in the currency according to the value and the options + */ + formatCurrency(value: number, currency: string, options?: CurrencyFormatterOptions): string; + + /** + * Return a function that returns the value's corresponding plural group: zero, one, two, few, many, or other. + * The returned function is invoked with one argument: the Number value for which to return the plural group. + * @param {PluralGeneratorOptions} options A JSON object including none or any of the following options. + * type Optional String cardinal (default), or ordinal. + * @returns {Function} Return a function that returns the value's corresponding plural group: zero, one, two, few, many, or other. + */ + pluralGenerator(options?: PluralGeneratorOptions): (value: number) => string; + + /** + * Returns the value's corresponding plural group: zero, one, two, few, many, or other. + * @param {number} value A Number for which to return the plural group. + * @param {PluralGeneratorOptions} options A JSON object including none or any of the following options. + * type Optional String cardinal (default), or ordinal. + * @returns {string} Returns the value's corresponding plural group: zero, one, two, few, many, or other. + */ + plural(value: number, options?: PluralGeneratorOptions): string; + + /** + * Returns a function that formats a relative time according to the given unit, options, and the default/instance locale. + * The returned function is invoked with one argument: the number value to be formatted. + * @param unit String value indicating the unit to be formatted. eg. "day", "week", "month", etc. + * @param options form: [String] eg. "short" or "narrow". Or falsy for default long form. + * @returns {Function} Returns a function that formats a relative time according to the given unit. + */ + relativeTimeFormatter(unit: string, options?: RelativeTimeFormatterOptions): (value: number) => string; + + /** + * Return a relative time according to the given unit + * @param {number} value The number to be formatted. + * @param {string} unit String value indicating the unit to be formatted. eg. "day", "week", "month", etc. + * @param options form: [String] eg. "short" or "narrow". Or falsy for default long form. + * @returns {string} Return a relative time according to the given unit. + */ + formatRelativeTime(value: number, unit: string, options?: RelativeTimeFormatterOptions): string; + + /** + * Returns a function that formats a unit according to the given unit, options, and the default/instance locale. + * The returned function is invoked with one argument: the number value to be formatted. + * @param unit String value indicating the unit to be formatted. eg. "day", "week", "month", etc. Could also be a compound unit, eg. "mile-per-hour" or "mile/hour" + * @param options form: [String] eg. "long", "short" or "narrow". + * @returns {Function} Returns a function that formats a unit according to the given unit, options, and the default/instance locale. + */ + unitFormatter(unit: string, options?: UnitFormatterOptions): (value: number) => string; + + /** + * Alias for .unitFormatter( unit, options )( value ). + * @param {number} value The number to be formatted. + * @param {string} unit String value indicating the unit to be formatted. eg. "day", "week", "month", etc. Could also be a compound unit, eg. "mile-per-hour" or "mile/hour" + * @param {UnitFormatterOptions} options form: [String] eg. "long", "short" or "narrow". + * @returns {string} Returns the unit formatted. + */ + formatUnit(value: number, unit: string, options?: UnitFormatterOptions): string + + /** + * Create a Globalize instance. + * @param {string} Locale string of the instance. + * @returns {Globalize} A Globalize instance + */ + new (locale: string): GlobalizeStatic; + /** + * Create a Globalize instance. + * @param cldr Cldr instance of the instance. + * @returns {Globalize} A Globalize instance + */ + new (cldr: cldr.CldrStatic): GlobalizeStatic; } declare var Globalize: GlobalizeStatic; diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 4d225779ce..f005582cb2 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1585,6 +1585,10 @@ declare namespace google.maps { setZoom(zoom: number): void; } + export interface FullscreenControlOptions { + position?: ControlPosition; + } + export interface StreetViewPanoramaOptions { addressControl?: boolean; addressControlOptions?: StreetViewAddressControlOptions; @@ -1592,8 +1596,11 @@ declare namespace google.maps { disableDefaultUi?: boolean; disableDoubleClickZoom?: boolean; enableCloseButton?: boolean; + fullscreenControl?: boolean; + fullscreenControlOptions?: FullscreenControlOptions; imageDateControl?: boolean; linksControl?: boolean; + mode?: "html4" | "html5" |"webgl"; panControl?: boolean; panControlOptions?: PanControlOptions; pano?: string; diff --git a/heatmap.js/heatmap.d.ts b/heatmap.js/heatmap.d.ts index 3a0bd2ba08..7cd14fc214 100644 --- a/heatmap.js/heatmap.d.ts +++ b/heatmap.js/heatmap.d.ts @@ -77,8 +77,9 @@ interface HeatmapConfiguration { /* * The property name of the value/weight in a datapoint + * Default value: 'value' */ - valueField: string; + valueField?: string; } /* diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index c7584f4e0d..45f69a0bda 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -4954,7 +4954,7 @@ interface HighchartsDataPoint { * The inner radius of an individual point in a solid gauge. Can be given as a number (pixels) or percentage string. * @since 4.1.6 */ - innerRadius?: number; + innerRadius?: number|string; /** * When this property is true, the points acts as a summary column for the values added or substracted since the * last intermediate sum, or since the start of the series. The y value is ignored. @@ -5005,7 +5005,7 @@ interface HighchartsDataPoint { * The outer radius of an individual point in a solid gauge. Can be given as a number (pixels) or percentage string. * @since 4.1.6 */ - radius?: number; + radius?: number|string; /** * Whether the data point is selected initially. * @default false diff --git a/intl-tel-input/intl-tel-input-tests.ts b/intl-tel-input/intl-tel-input-tests.ts new file mode 100644 index 0000000000..739fcc854b --- /dev/null +++ b/intl-tel-input/intl-tel-input-tests.ts @@ -0,0 +1,69 @@ +/// +/// + +$('#phone').intlTelInput(); + +$('#phone').intlTelInput({ + customPlaceholder: function(selectedCountryPlaceholder, selectedCountryData) { + return 'e.g. ' + selectedCountryPlaceholder; + } +}); + +$('#phone').intlTelInput({ + geoIpLookup: function(callback) { + $.get('http://ipinfo.io', function() {}, 'jsonp').always(function(resp) { + let countryCode = (resp && resp.country) ? resp.country : ''; + callback(countryCode); + }); + } +}); + +$('#phone').intlTelInput('destroy'); + +let extension = $('#phone').intlTelInput('getExtension'); + +let intlNumber = $('#phone').intlTelInput('getNumber'); +let ntlNumber = $('#phone').intlTelInput('getNumber', intlTelInputUtils.numberFormat.NATIONAL); + +let numberType = $('#phone').intlTelInput('getNumberType'); +if (numberType === intlTelInputUtils.numberType.MOBILE) {} + +let countryData = $('#phone').intlTelInput('getSelectedCountryData'); + +let error = $('#phone').intlTelInput('getValidationError'); +if (error === intlTelInputUtils.validationError.TOO_SHORT) {} + +let isValid = $('#phone').intlTelInput('isValidNumber'); + +$('#phone').intlTelInput('setCountry', 'gb'); + +$('#phone').intlTelInput('setNumber', '+447733123456'); + +let countryData3 = $.intlTelInput.getCountryData(); + +$.intlTelInput.loadUtils('build/js/utils.js'); + +$('#phone').intlTelInput({ + utilsScript: '../../build/js/utils.js' +}); + +$('#phone').intlTelInput({ + initialCountry: 'auto', + geoIpLookup: function(callback) { + $.get('http://ipinfo.io', function() {}, 'jsonp').always(function(resp) { + let countryCode = (resp && resp.country) ? resp.country : ''; + callback(countryCode); + }); + }, + utilsScript: '../../build/js/utils.js' +}); + +$('#phone').intlTelInput({ + nationalMode: true, + utilsScript: '../../build/js/utils.js' +}); + +$('#phone').intlTelInput({ + onlyCountries: ['al'], + utilsScript: '../../build/js/utils.js' +}); diff --git a/intl-tel-input/intl-tel-input.d.ts b/intl-tel-input/intl-tel-input.d.ts new file mode 100644 index 0000000000..7779f34bd4 --- /dev/null +++ b/intl-tel-input/intl-tel-input.d.ts @@ -0,0 +1,252 @@ +// Type definitions for intl-tel-input +// Project: https://github.com/jackocnr/intl-tel-input +// Definitions by: Fidan Hakaj +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace IntlTelInput { + + interface Options { + /** + * Whether or not to allow the dropdown. If disabled, there is no dropdown + * arrow, and the selected flag is not clickable. Also we display the + * selected flag on the right instead because it is just a marker of state. + */ + allowDropdown?: boolean; + /** + * If there is just a dial code in the input: remove it on blur or submit, + * and re-add it on focus. This is to prevent just a dial code getting + * submitted with the form. Requires nationalMode to be set to false. + */ + autoHideDialCode?: boolean; + /** + * Set the input's placeholder to an example number for the selected country. + * You can specify the number type using the numberType option. + * If there is already a placeholder attribute set on the input then that + * will take precedence. Requires the utilsScript option. + */ + autoPlaceholder?: boolean; + /** + * Change the placeholder generated by autoPlaceholder. Must return a string. + */ + customPlaceholder?: (selectedCountryPlaceholder: string, selectedCountryData: CountryData) => string; + /** + * Specify the container for the country dropdown (use a jQuery selector + * e.g. "body"). This is useful when the input is within a scrolling element, + * or an element with overflow: hidden. Wherever you put the dropdown it + * will automatically close on the window scroll event to prevent positioning + * issues. If you want it to close when a different element is scrolled + * (such as the input's parent), simply listen for the that scroll event, + * and trigger $(window).scroll() e.g. + */ + dropdownContainer?: string; + /** + * Don't display the countries you specify. + */ + excludeCountries?: Array; + /** + * Format the input value during initialisation. + */ + formatOnInit?: boolean; + /** + * When setting initialCountry to "auto", you must use this option to + * specify a custom function that looks up the user's location. Also note + * that when instantiating the plugin, we now return a deferred object, so + * you can use .done(callback) to know when initialisation requests like + * this have completed. + * Note that the callback must still be called in the event of an error. + */ + geoIpLookup?: (callback: (countryCode: string) => void) => void; + /** + * Set the initial country selection by specifying it's country code. + * You can also set it to "auto", which will lookup the user's country based + * on their IP address (requires the geoIpLookup option). + * Note that the "auto" option will not update the country selection if the + * input already contains a number. If you leave initialCountry blank, + * it will default to the first country in the list. + */ + initialCountry?: string; + /** + * Allow users to enter national numbers (and not have to think about + * international dial codes). Formatting, validation and placeholders still + * work. Then you can use getNumber to extract a full international number. + * This option now defaults to true, and it is recommended that you leave it + * that way as it provides a better experience for the user. + */ + nationalMode?: boolean; + /** + * Specify one of the keys from the global enum intlTelInputUtils.numberType + * e.g. "FIXED_LINE" to tell the plugin you're expecting that type of number. + * Currently this is only used to set the placeholder to the right type of number. + */ + numberType?: string; + /** + * Display only the countries you specify. + */ + onlyCountries?: Array; + /** + * Specify the countries to appear at the top of the list. + */ + preferredCountries?: Array; + /** + * Display the country dial code next to the selected flag so it's not part + * of the typed number. Note that this will disable nationalMode because + * technically we are dealing with international numbers, but with the + * dial code separated. + */ + separateDialCode?: boolean; + /** + * Enable formatting/validation etc. by specifying the path to the included + * utils.js script, which is fetched only when the page has finished loading + * (on window.load) to prevent blocking. When instantiating the plugin, + * we return a deferred object, so you can use .done(callback) to know when + * initialisation requests like this have finished. Note that if you're + * lazy loading the plugin script itself (intlTelInput.js) this will not + * work and you will need to use the loadUtils method instead. + */ + utilsScript?: string; + } + + interface CountryData { + name: string; + iso2: string; + dialCode: string; + } + + interface Static { + /** + * Get all of the plugin's country data. + * Note that any modifications must be done before initialising the plugin. + */ + getCountryData: () => Array; + /** + * Note: this is only needed if you're lazy loading the plugin script itself (intlTelInput.js). + * If not then just use the utilsScript option. Load the utils.js script + * (included in the lib directory) to enable formatting/validation etc. + * @param path path to the utils.js script. + */ + loadUtils: (path: string) => void; + } +} + +declare namespace intlTelInputUtils { + + const enum numberFormat { + E164 = 0, + INTERNATIONAL = 1, + NATIONAL = 2, + RFC3966 = 3 + } + + const enum numberType { + FIXED_LINE = 0, + MOBILE = 1, + FIXED_LINE_OR_MOBILE = 2, + TOLL_FREE = 3, + PREMIUM_RATE = 4, + SHARED_COST = 5, + VOIP = 6, + PERSONAL_NUMBER = 7, + PAGER = 8, + UAN = 9, + VOICEMAIL = 10, + UNKNOWN = -1 + } + + const enum validationError { + IS_POSSIBLE = 0, + INVALID_COUNTRY_CODE = 1, + TOO_SHORT = 2, + TOO_LONG = 3, + NOT_A_NUMBER = 4 + } +} + +interface JQueryStatic { + intlTelInput: IntlTelInput.Static; +} + +interface JQuery { + /** + * Remove the plugin from the input, and unbind any event listeners. + */ + intlTelInput(method: 'destroy'): void; + /** + * Get the extension from the current number. + * Requires the utilsScript option. + * e.g. if the input value was "(702) 555-5555 ext. 1234", this would + * return "1234". + */ + intlTelInput(method: 'getExtension'): string; + /** + * Get the current number in the given format (defaults to E.164 standard). + * The different formats are available in the enum + * intlTelInputUtils.numberFormat - taken from here. + * Requires the utilsScript option. + * Note that even if nationalMode is enabled, this can still return a full + * international number. + */ + intlTelInput(method: 'getNumber'): string; + /** + * Get the type (fixed-line/mobile/toll-free etc) of the current number. + * Requires the utilsScript option. + * Returns an integer, which you can match against the various options in the + * global enum intlTelInputUtils.numberType. + * Note that in the US there's no way to differentiate between fixed-line and + * mobile numbers, so instead it will return FIXED_LINE_OR_MOBILE. + */ + intlTelInput(method: 'getNumberType'): intlTelInputUtils.numberType; + /** + * Get the country data for the currently selected flag. + */ + intlTelInput(method: 'getSelectedCountryData'): IntlTelInput.CountryData; + /** + * Get more information about a validation error. + * Requires the utilsScript option. + * Returns an integer, which you can match against the various options in the + * global enum intlTelInputUtils.validationError + */ + intlTelInput(method: 'getValidationError'): intlTelInputUtils.validationError; + /** + * Validate the current number. Expects an internationally formatted number + * (unless nationalMode is enabled). If validation fails, you can use + * getValidationError to get more information. + * Requires the utilsScript option. + * Also see getNumberType if you want to make sure the user enters a certain + * type of number e.g. a mobile number. + */ + intlTelInput(method: 'isValidNumber'): boolean; + intlTelInput(method: string): void; + /** + * Change the country selection (e.g. when the user is entering their address). + * @param countryCode country code of the country to be set. + */ + intlTelInput(method: 'setCountry', countryCode: string): void; + /** + * Insert a number, and update the selected flag accordingly. + * Note that by default, if nationalMode is enabled it will try to use + * national formatting. + * @param aNumber number to be set. + */ + intlTelInput(method: 'setNumber', aNumber: string): void; + intlTelInput(method: string, value: string): void; + + /** + * Get the current number in the given format (defaults to E.164 standard). + * The different formats are available in the enum + * intlTelInputUtils.numberFormat - taken from here. + * Requires the utilsScript option. + * Note that even if nationalMode is enabled, this can still return a full + * international number. + * @param numberFormat the format in which the number will be returned. + */ + intlTelInput(method: 'getNumber', numberFormat: intlTelInputUtils.numberFormat): string; + intlTelInput(method: string, numberFormat: intlTelInputUtils.numberFormat): string; + + /** + * initialise the plugin with optional options. + * @param options options that can be provided during initialization. + */ + intlTelInput(options?: IntlTelInput.Options): JQueryDeferred; +} diff --git a/javascript-obfuscator/javascript-obfuscator-tests.ts b/javascript-obfuscator/javascript-obfuscator-tests.ts index 74d6363ffb..1c0753c3bf 100644 --- a/javascript-obfuscator/javascript-obfuscator-tests.ts +++ b/javascript-obfuscator/javascript-obfuscator-tests.ts @@ -5,11 +5,14 @@ import { JavaScriptObfuscator } from 'javascript-obfuscator'; let sourceCode1: string = JavaScriptObfuscator.obfuscate('var foo = 1;'); let sourceCode2: string = JavaScriptObfuscator.obfuscate('var foo = 1;', { compact: true, - debugProtection: false, - debugProtectionInterval: false, - disableConsoleOutput: true, - encodeUnicodeLiterals: true, - rotateUnicodeArray: true, - unicodeArray: true, - wrapUnicodeArrayCalls: true + debugProtection: false, + debugProtectionInterval: false, + disableConsoleOutput: true, + encodeUnicodeLiterals: false, + reservedNames: ['^foo$'], + rotateUnicodeArray: true, + selfDefending: true, + unicodeArray: true, + unicodeArrayThreshold: 0.8, + wrapUnicodeArrayCalls: true }); diff --git a/javascript-obfuscator/javascript-obfuscator.d.ts b/javascript-obfuscator/javascript-obfuscator.d.ts index 7b7a8438c5..17a91c4925 100644 --- a/javascript-obfuscator/javascript-obfuscator.d.ts +++ b/javascript-obfuscator/javascript-obfuscator.d.ts @@ -10,8 +10,11 @@ declare module 'javascript-obfuscator' { debugProtectionInterval?: boolean; disableConsoleOutput?: boolean; encodeUnicodeLiterals?: boolean; + reservedNames?: string[]; rotateUnicodeArray?: boolean; + selfDefending?: boolean; unicodeArray?: boolean; + unicodeArrayThreshold?: number; wrapUnicodeArrayCalls?: boolean; [id: string]: any; } diff --git a/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts b/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts index fcc3bac9da..9c13b5a28f 100644 --- a/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts +++ b/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts @@ -1,5 +1,5 @@ // Type definitions for Microsoft jQuery Unobtrusive Validation v3.2.3 -// Project: http://aspnetwebstack.codeplex.com/ +// Project: https://github.com/aspnet/jquery-validation-unobtrusive // Definitions by: Matt Brooks // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/jquery.slimScroll/jquery.SlimScroll-tests.ts b/jquery.slimScroll/jquery.SlimScroll-tests.ts index deb4f2406d..046eda840f 100644 --- a/jquery.slimScroll/jquery.SlimScroll-tests.ts +++ b/jquery.slimScroll/jquery.SlimScroll-tests.ts @@ -41,6 +41,21 @@ $('#slimtest3').slimScroll({ alwaysVisible: true }); +$('#slimtest3').slimScroll({ + color: '#00f', + size: '10px', + height: '180px', + alwaysVisible: true, + destroy: true +}); + $("div").slimScroll().bind('slimscroll', function(e){ console.log("Reached " + e); -}); \ No newline at end of file +}); + +var options : IJQuerySlimScrollOptions = { + destroy: true, + position: 'left' +}; + +$('#slimtest3').slimScroll(options); diff --git a/jquery.slimScroll/jquery.slimScroll.d.ts b/jquery.slimScroll/jquery.slimScroll.d.ts index 4d77d28817..b5d3dab17f 100644 --- a/jquery.slimScroll/jquery.slimScroll.d.ts +++ b/jquery.slimScroll/jquery.slimScroll.d.ts @@ -1,58 +1,110 @@ -// Type definitions for jQuery.slimScroll v1.3.3 +// Type definitions for jQuery.slimScroll v1.3.8 // Project: https://github.com/rochal/jQuery-slimScroll // Definitions by: Chintan Shah // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// interface IJQuerySlimScrollOptions { - // width in pixels of the visible scroll area + /** + * width in pixels of the visible scroll area + */ width? :string; - // height in pixels of the visible scroll area + /** + * height in pixels of the visible scroll area + */ height? :string; - // width in pixels of the scrollbar and rail + /** + * width in pixels of the scrollbar and rail + */ size? :string; - // scrollbar color, accepts any hex/color value + /** + * scrollbar color, accepts any hex/color value + */ color?:string; - // scrollbar position - left/right + /** + * scrollbar position - left/right + */ position?:string; - // distance in pixels between the side edge and the scrollbar + /** + * distance in pixels between the side edge and the scrollbar + */ distance?:string; - // default scroll position on load - top / bottom / $('selector') + /** + * default scroll position on load - top / bottom / $('selector') + */ start?:any; - // sets scrollbar opacity + /** + * sets scrollbar opacity + */ opacity? :number; - // enables always-on mode for the scrollbar + /** + * enables always-on mode for the scrollbar + */ alwaysVisible?: boolean; - // check if we should hide the scrollbar when user is hovering over + /** + * check if we should hide the scrollbar when user is hovering over + */ disableFadeOut?: boolean; - // sets visibility of the rail + /** + * sets visibility of the rail + */ railVisible?: boolean; - // sets rail color + /** + * sets rail color + */ railColor?: string; - // sets rail opacity + /** + * sets rail opacity + */ railOpacity?:number; - // whether we should use jQuery UI Draggable to enable bar dragging + /** + * whether we should use jQuery UI Draggable to enable bar dragging + */ railDraggable?: boolean; - // defautlt CSS class of the slimscroll rail + /** + * default CSS class of the slimscroll rail + */ railClass?: string; - // defautlt CSS class of the slimscroll bar + /** + * default CSS class of the slimscroll bar + */ barClass?: string; - // defautlt CSS class of the slimscroll wrapper + /** + * default CSS class of the slimscroll wrapper + */ wrapperClass?: string; - // check if mousewheel should scroll the window if we reach top/bottom + /** + * check if mousewheel should scroll the window if we reach top/bottom + */ allowPageScroll?: boolean; - // scroll amount applied to each mouse wheel step + /** + * scroll amount applied to each mouse wheel step + */ wheelStep?: number; - // scroll amount applied when user is using gestures + /** + * scroll amount applied when user is using gestures + */ touchScrollStep?: number; - // sets border radius + /** + * sets border radius + */ borderRadius?: string; - // sets border radius of the rail + /** + * sets border radius of the rail + */ railBorderRadius?: string; - // jumps to the specified scroll value + /** + * jumps to the specified scroll value + */ scrollTo?: string; - // increases/decreases current scroll value by specified amount + /** + * increases/decreases current scroll value by specified amount + */ scrollBy?: string; + /** + * release resources held by the plugin + */ + destroy?:boolean; } interface JQuery { diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 6478529dad..40ebf2ee6c 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -1987,6 +1987,24 @@ interface JQuery { */ click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Trigger the "contextmenu" event on an element. + */ + contextmenu(): JQuery; + /** + * Bind an event handler to the "contextmenu" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + contextmenu(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "contextmenu" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + contextmenu(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** * Trigger the "dblclick" event on an element. */ diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index b283f21c14..934a8cd8b1 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -1282,6 +1282,7 @@ declare namespace kendo.data { interface DataSourceRequestStartEvent extends DataSourceEvent { type?: string; + preventDefault(): void; } interface DataSourceRequestEndEvent extends DataSourceEvent { @@ -3334,6 +3335,7 @@ declare namespace kendo.ui { static fn: DropDownList; options: DropDownListOptions; + popup: kendo.ui.Popup; dataSource: kendo.data.DataSource; span: JQuery; diff --git a/kii-cloud-sdk/kii-cloud-sdk-tests.ts b/kii-cloud-sdk/kii-cloud-sdk-tests.ts index a7118d78d3..6ca7d611db 100644 --- a/kii-cloud-sdk/kii-cloud-sdk-tests.ts +++ b/kii-cloud-sdk/kii-cloud-sdk-tests.ts @@ -26,6 +26,9 @@ function main() { endpoint.installationID; }); + user.setLocale("en"); + var locale: string = user.getLocale(); + var anotherUser: KiiUser = KiiUserBuilder .builderWithIdentifier("id", "password") .setEmailAddress("mail@example.org") @@ -67,4 +70,30 @@ function main() { removeMembersArray: KiiUser[]) { } }); + + Kii.authenticateAsThing("thing id", "password", { + success: function (thingAuthContext: KiiThingContext) { + thingAuthContext.bucketWithName(""); + }, + failure: function (error) { + } + }) + .then(function (thingAuthContext: KiiThingContext) { + }); + + Kii.authenticateAsThingWithToken("thing id", "token", { + success: function (thingAuthContext: KiiThingContext) { + thingAuthContext.bucketWithName(""); + }, + failure: function (error) { + } + }) + .then(function (thingAuthContext: KiiThingContext) { + }); + + KiiThing.loadWithVendorThingID("thing ID") + .then(function (thing) { + var isOnline: boolean = thing.isOnline(); + var onlineStatusModifiedAt: Date = thing.getOnlineStatusModifiedAt(); + }); } diff --git a/kii-cloud-sdk/kii-cloud-sdk.d.ts b/kii-cloud-sdk/kii-cloud-sdk.d.ts index 550aa736fa..26decd07a0 100644 --- a/kii-cloud-sdk/kii-cloud-sdk.d.ts +++ b/kii-cloud-sdk/kii-cloud-sdk.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Kii Cloud SDK v2.4.4 +// Type definitions for Kii Cloud SDK v2.4.6 // Project: http://en.kii.com/ // Definitions by: Kii Consortium // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -17,7 +17,8 @@ declare namespace KiiCloud { JP, CN, SG, - CN3 + CN3, + EU } export enum KiiAnalyticsSite { @@ -25,7 +26,8 @@ declare namespace KiiCloud { JP, CN, SG, - CN3 + CN3, + EU } enum KiiSocialNetworkName { @@ -512,6 +514,104 @@ declare namespace KiiCloud { * ); */ static listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + + /** + * Authenticate as Thing. + *

+ * This api is intended to be used in a Thing device, where the user + * credentials or app admin context is not configured. This Thing must be + * already registered in Kii Cloud. + * + * + * @param vendorThingID vendorThingID of a registered Thing. + * @param password password for the registered Thing. + * @param callbacks The callback methods called when authentication succeeded/failed. + * + * @return return promise object. + *
    + *
  • fulfill callback function: function(thingAuthContext). thingAuthContext is a KiiThingContext instance.
  • + *
  • reject callback function: function(error). error is an Error instance. + *
      + *
    • error.message
    • + *
    + *
  • + *
+ * + * @example + * // example to use callbacks directly + * Kii.authenticateAsThing("vendor thing id", "password of this thing", { + * success: function(thingAuthContext) { + * // thingAuthContext : KiiThingContext instance + * // Operate entities with thingAuthContext. + * }, + * failure: function(error) { + * // Authentication failed. + * } + * ); + * + * // example to use Promise + * Kii.authenticateAsThing("vendor thing id", "password of this thing").then( + * function(thingAuthContext) { // fulfill callback function + * // thingAuthContext : KiiThingContext instance + * // Operate entities with thingAuthContext. + * + * }, + * function(error) { // reject callback function + * // Authentication failed. + * var errorString = error.message; + * } + * ); + */ + static authenticateAsThing(vendorThingID: string, password: string, callbacks?: { success(thingAuthContext: KiiThingContext): any; failure(error: Error): any; }): Promise; + + /** + * Create a KiiThingContext reference + *

+ * This api is intended to be used in a Thing device, where the user + * credentials or app admin context is not configured. This Thing must be + * already registered in Kii Cloud. + * + * + * @param thingID thingID of a registered Thing. + * @param token token for the registered Thing. + * @param callbacks The callback methods called when creation succeeded/failed. + * + * @return return promise object. + *
    + *
  • fulfill callback function: function(thingContext). thingContext is a KiiThingContext instance.
  • + *
  • reject callback function: function(error). error is an Error instance. + *
      + *
    • error.message
    • + *
    + *
  • + *
+ * + * @example + * // example to use callbacks directly + * Kii.authenticateAsThingWithToken("thing_id", "thing_token", { + * success: function(thingContext) { + * // thingContext : KiiThingContext instance + * // Operate entities with thingContext. + * }, + * failure: function(error) { + * // Creation failed. + * } + * ); + * + * // example to use Promise + * Kii.authenticateAsThingWithToken("thing_id", "thing_token").then( + * function(thingContext) { // fulfill callback function + * // thingContext : KiiThingContext instance + * // Operate entities with thingContext. + * + * }, + * function(error) { // reject callback function + * // Creation failed. + * var errorString = error.message; + * } + * ); + */ + static authenticateAsThingWithToken(thingID: string, token: string, callbacks?: { success(thingContext: KiiThingContext): any; failure(error: Error): any; }): Promise; } /** @@ -3744,7 +3844,7 @@ declare namespace KiiCloud { *
  • response.username is username to use for connecting to the MQTT broker.
  • *
  • response.password is assword to use for connecting to the MQTT broker.
  • *
  • response.mqttTopic is topic to subscribe in the MQTT broker.
  • - *
  • response.host is URL of the MQTT broker host to connect.
  • + *
  • response.host is hostname of the MQTT broker.
  • *
  • response.X-MQTT-TTL is the amount of time in seconds that specifies how long the mqttTopic will be valid, after that the client needs to request new MQTT endpoint info.
  • *
  • response.portTCP is port to connect using plain TCP.
  • *
  • response.portSSL is port to connect using SSL/TLS.
  • @@ -4986,6 +5086,20 @@ declare namespace KiiCloud { */ getDisabled(): boolean; + /** + * Get online status of the thing. + * + * @return true if the thing is online, false otherwise. The return value will be null initially until the thing is connected for the first time. + */ + isOnline(): boolean; + + /** + * Get online status modified date of the thing. + * + * @return online status modified time of this thing. The date will be null initially until the thing is connected for the first time. + */ + getOnlineStatusModifiedAt(): Date; + /** * Register thing in KiiCloud.
    * This API doesnt require users login Anonymous user can register thing. @@ -5794,6 +5908,156 @@ declare namespace KiiCloud { pushSubscription(): KiiPushSubscription; } + /** + * represents a KiiThingContext object + */ + export class KiiThingContext { + /** + * Creates a reference to a bucket in App scope operated by thing. + * + * @param bucketName The name of the bucket the app should create/access + * + * @return A working KiiBucket object + * + * @example + * Kii.authenticateAsThing("vendorThingID", "password", { + * success: function(thingAuthContext) { + * var bucket = thingAuthContext.bucketWithName("myAppBucket"); + * }, + * failure: function(errorString, errorCode) { + * // auth failed. + * } + * }); + */ + bucketWithName(bucketName: string): KiiBucket; + + /** + * Creates a reference to a encrypted bucket in App scope operated by thing. + *

    The bucket will be created/accessed within this app's scope + * + * @param bucketName The name of the bucket the app should create/access + * + * @return A working KiiBucket object + * + * @example + * Kii.authenticateAsThing("vendorThingID", "password", { + * success: function(thingAuthContext) { + * var bucket = thingAuthContext.encryptedBucketWithName("myAppBucket"); + * }, + * failure: function(errorString, errorCode) { + * // auth failed. + * } + * }); + */ + encryptedBucketWithName(bucketName: string): KiiBucket; + + /** + * Creates a reference to an object operated by thing using object`s URI. + * + * @param object URI. + * + * @return A working KiiObject instance + * + * @throws If the URI is null, empty or does not have correct format. + */ + objectWithURI(object: string): KiiObject; + + /** + * Creates a reference to a topic in App scope operated by thing. + *

    The Topic will be created/accessed within this app's scope + * + * @param topicName name of the topic. Must be a not empty string. + * + * @return topic instance. + */ + topicWithName(topicName: string): KiiTopic; + + /** + * Gets a list of topics in app scope + * + * @param callbacks An object with callback methods defined + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is array of KiiTopic instances.
      • + *
      • params[1] is string of nextPaginationKey.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiAppAdminContext instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // Assume you already have thingAuthContext instance. + * thingAuthContext.listTopics({ + * success: function(topicList, nextPaginationKey) { + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * thingAuthContext.listTopics({ + * success: function(topicList, nextPaginationKey) {...}, + * failure: function(anErrorString) {...} + * }, nextPaginationKey); + * } + * }, + * failure: function(anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * // Assume you already have thingAuthContext instance. + * thingAuthContext.listTopics().then( + * function(params) { + * var topicList = params[0]; + * var nextPaginationKey = params[1]; + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * thingAuthContext.listTopics(null, nextPaginationKey).then( + * function(params) {...}, + * function(error) {...} + * ); + * } + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + + /** + * Gets authenticated KiiThing instance. + *
    Returned thing instance only have thingID, vendorThingID and accessToken. + * (vendorThingID is not included when you used + * {@link Kii.authenticateAsThingWithToken()} to obtain KiiThingContext.) + *
    Please execute {@link KiiThing#refresh()} to obtain other properties. + * + * @return return authenticated KiiThing instance. + */ + getAuthenticatedThing(): KiiThing; + + /** + * Instantiate push installation for this thing. + * + * @return push installation object. + */ + pushInstallation(): KiiPushInstallation; + } + /** * Represents a Topic object. */ @@ -6106,6 +6370,25 @@ declare namespace KiiCloud { */ setCountry(value: string): void; + /** + * Get the locale associated with this user + * + * @return + */ + getLocale(): string; + + /** + * Set the locale associated with this user + * The locale argument must be BCP 47 language tag. + * Examples: + * "en": English + * "de-AT": German as used in Austria. + * "zh-Hans-CN": Chinese written in simplified characters as used in China. + * + * @param value The locale to set. + */ + setLocale(value: string): void; + /** * Get the server's creation date of this user * @@ -6196,7 +6479,7 @@ declare namespace KiiCloud { /** * Sets a key/value pair to a KiiUser * - *

    If the key already exists, its value will be written over. If the object is of invalid type, it will return false and a KiiError will be thrown (quietly). Accepted types are any JSON-encodable objects. + *

    If the key already exists, its value will be written over. If key is empty or starting with '_', it will do nothing. Accepted types are any JSON-encodable objects. * * @param key The key to set. The key must not be a system key (created, metadata, modified, type, uuid) or begin with an underscore (_) * @param value The value to be set. Object must be of a JSON-encodable type (Ex: dictionary, array, string, number, etc) @@ -7826,6 +8109,7 @@ import KiiServerCodeEntry = KiiCloud.KiiServerCodeEntry; import KiiServerCodeExecResult = KiiCloud.KiiServerCodeExecResult; import KiiSocialConnect = KiiCloud.KiiSocialConnect; import KiiThing = KiiCloud.KiiThing; +import KiiThingContext = KiiCloud.KiiThingContext; import KiiTopic = KiiCloud.KiiTopic; import KiiUser = KiiCloud.KiiUser; import KiiUserBuilder = KiiCloud.KiiUserBuilder; diff --git a/knex/knex-tests.ts b/knex/knex-tests.ts index 410139f4b6..c01c54691e 100644 --- a/knex/knex-tests.ts +++ b/knex/knex-tests.ts @@ -162,6 +162,8 @@ knex.select('*').from('users').join('accounts', function() { knex.select('*').from('users').join('accounts', 'accounts.type', knex.raw('?', ['admin'])); +knex.raw('select * from users where id = :user_id', { user_id: 1 }); + knex.from('users').innerJoin('accounts', 'users.id', 'accounts.user_id'); knex.table('users').innerJoin('accounts', 'users.id', '=', 'accounts.user_id'); diff --git a/knex/knex.d.ts b/knex/knex.d.ts index c3ede588e8..e5d796350c 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -31,6 +31,7 @@ declare module "knex" { migrate: Knex.Migrator; seed: any; fn: any; + on(eventName: string, callback: Function): Knex.QueryBuilder; } function Knex(config: Knex.Config) : Knex; @@ -249,6 +250,7 @@ declare module "knex" { (value: Value): Raw; (sql: string, ...bindings: Value[]): Raw; (sql: string, bindings: Value[]): Raw; + (sql: string, bindings: Object): Raw; } // @@ -301,6 +303,7 @@ declare module "knex" { interface SchemaBuilder extends Promise { createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; + createTableIfNotExists(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; renameTable(oldTableName: string, newTableName: string): Promise; dropTable(tableName: string): SchemaBuilder; hasTable(tableName: string): Promise; @@ -312,6 +315,7 @@ declare module "knex" { interface TableBuilder { increments(columnName?: string): ColumnBuilder; + bigIncrements(columnName?: string): ColumnBuilder; dropColumn(columnName: string): TableBuilder; dropColumns(...columnNames: string[]): TableBuilder; renameColumn(from: string, to: string): ColumnBuilder; diff --git a/knockout.kogrid/ko-grid.d.ts b/knockout.kogrid/ko-grid.d.ts index fe9877e038..a8f3984acf 100644 --- a/knockout.kogrid/ko-grid.d.ts +++ b/knockout.kogrid/ko-grid.d.ts @@ -6,192 +6,270 @@ // These are very definitely preliminary. Please feel free to improve. /// +/// declare namespace kg { - interface DomUtilityService { - UpdateGridLayout(grid: Grid): void; - BuildStyles(grid: Grid): void; - } + interface DomUtilityService { + UpdateGridLayout(grid: Grid): void; + BuildStyles(grid: Grid): void; + } - interface Row { - selected: KnockoutObservable; - entity: EntityType; - } + interface Row { + selected: KnockoutObservable; + entity: EntityType; + } - interface RowFactory { - rowCache: Row[]; - } + interface RowFactory { + rowCache: Row[]; + } - interface SelectionService { - setSelection(row: Row, selected: boolean): void; - multi: boolean; - lastClickedRow: Row; - } + interface SelectionService { + setSelection(row: Row, selected: boolean): void; + multi: boolean; + lastClickedRow: Row; + } - interface Grid { - configureColumnWidths(): void; - rowFactory: RowFactory; - config: GridOptions; - $$selectionPhase: boolean; - selectionService: SelectionService; - } + interface Grid { + configureColumnWidths(): void; + rowFactory: RowFactory; + config: GridOptions; + $$selectionPhase: boolean; + selectionService: SelectionService; + } - interface Plugin { - onGridInit(grid: Grid): void; - } + interface Plugin { + onGridInit(grid: Grid): void; + } - interface GridOptions { - /** Callback for when you want to validate something after selection. */ - afterSelectionChange?(row: Row): void; + interface GridOptions { + /** Callback for when you want to validate something after selection. */ + afterSelectionChange?(row: Row): void; - /** Callback if you want to inspect something before selection, - return false if you want to cancel the selection. return true otherwise. - If you need to wait for an async call to proceed with selection you can - use rowItem.changeSelection(event) method after returning false initially. - Note: when shift+ Selecting multiple items in the grid this will only get called - once and the rowItem will be an array of items that are queued to be selected. */ - beforeSelectionChange?: Function; + /** Callback if you want to inspect something before selection, + return false if you want to cancel the selection. return true otherwise. + If you need to wait for an async call to proceed with selection you can + use rowItem.changeSelection(event) method after returning false initially. + Note: when shift+ Selecting multiple items in the grid this will only get called + once and the rowItem will be an array of items that are queued to be selected. */ + beforeSelectionChange?(row: Row): boolean; - /** definitions of columns as an array [], if not defined columns are auto-generated. See github wiki for more details. */ - columnDefs?: ColumnDef[]; + /** To be able to have selectable rows in grid. */ + canSelectRows?:boolean; - /** Column width of columns in grid. */ - columnWidth?: number; + /** definitions of columns as an array [], if not defined columns are auto-generated. See github wiki for more details. */ + columnDefs?: ColumnDef[] | KnockoutObservable; - /** Data being displayed in the grid. Each item in the array is mapped to a row being displayed. */ - data?: KnockoutObservableArray; + /** Column width of columns in grid. */ + columnWidth?: number; - /** Row selection check boxes appear as the first column. */ - displaySelectionCheckbox: boolean; + /** Data being displayed in the grid. Each item in the array is mapped to a row being displayed. */ + data?: KnockoutObservableArray; - /** Enable or disable resizing of columns */ - enableColumnResize?: boolean; + /** Row selection check boxes appear as the first column. */ + displaySelectionCheckbox: boolean; - /** Enables the server-side paging feature */ - enablePaging?: boolean; + /** Enable or disable resizing of columns */ + enableColumnResize?: boolean; - /** Enable column pinning */ - enablePinning?: boolean; + /** Enables the server-side paging feature */ + enablePaging?: boolean; - /** Enable drag and drop row reordering. Only works in HTML5 compliant browsers. */ - enableRowReordering?: boolean; + /** Enable drag and drop row reordering. Only works in HTML5 compliant browsers. */ + enableRowReordering?: boolean; - /** To be able to have selectable rows in grid. */ - enableRowSelection?: boolean; + /** Enables or disables sorting in grid. */ + enableSorting?: boolean; - /** Enables or disables sorting in grid. */ - enableSorting?: boolean; + /** filterOptions - + filterText: The text bound to the built-in search box. + useExternalFilter: Bypass internal filtering if you want to roll your own filtering mechanism but want to use builtin search box. + */ + filterOptions?: FilterOptions; - /** filterOptions - - filterText: The text bound to the built-in search box. - useExternalFilter: Bypass internal filtering if you want to roll your own filtering mechanism but want to use builtin search box. - */ - filterOptions?: FilterOptions; + /** Defining the height of the footer in pixels. */ + footerRowHeight?: number; - /** Defining the height of the footer in pixels. */ - footerRowHeight?: number; + /** Show or hide the footer alltogether the footer is enabled by default */ + footerVisible?: boolean; - /** Show or hide the footer alltogether the footer is enabled by default */ - footerVisible?: boolean; + /** Initial fields to group data by. Array of field names, not displayName. */ + groups?: string[]; - /** Initial fields to group data by. Array of field names, not displayName. */ - groups?: string[]; + /** The height of the header row in pixels. */ + headerRowHeight?: number; - /** The height of the header row in pixels. */ - headerRowHeight?: number; + /** Define a header row template for further customization. See github wiki for more details. */ + headerRowTemplate?: string | JQueryGenericPromise; - /** Define a header row template for further customization. See github wiki for more details. */ - headerRowTemplate?: any; + /** Enables the use of jquery UI reaggable/droppable plugin. requires jqueryUI to work if enabled. + Useful if you want drag + drop but your users insist on crappy browsers. */ + jqueryUIDraggable?: boolean; - /** Enables the use of jquery UI reaggable/droppable plugin. requires jqueryUI to work if enabled. - Useful if you want drag + drop but your users insist on crappy browsers. */ - jqueryUIDraggable?: boolean; + /** Enable the use jqueryUIThemes */ + jqueryUITheme?: boolean; - /** Enable the use jqueryUIThemes */ - jqueryUITheme?: boolean; + /** Prevent unselections when in single selection mode. */ + keepLastSelected?: boolean; - /** Prevent unselections when in single selection mode. */ - keepLastSelected?: boolean; + /** Maintains the column widths while resizing. + Defaults to true when using *'s or undefined widths. Can be ovverriden by setting to false. */ + maintainColumnRatios?: any; - /** Maintains the column widths while resizing. - Defaults to true when using *'s or undefined widths. Can be ovverriden by setting to false. */ - maintainColumnRatios?: any; + /** Set this to false if you only want one item selected at a time */ + multiSelect?: boolean; - /** Set this to false if you only want one item selected at a time */ - multiSelect?: boolean; + /** pagingOptions - */ + pagingOptions?: PagingOptions; - /** pagingOptions - */ - pagingOptions?: PagingOptions; + /** Array of plugin functions to register in ng-grid */ + plugins?: Plugin[]; - /** Array of plugin functions to register in ng-grid */ - plugins?: Plugin[]; + /** Row height of rows in grid. */ + rowHeight?: number; - /** Row height of rows in grid. */ - rowHeight?: number; + /** Define a row template to customize output. See github wiki for more details. */ + rowTemplate?: string | JQueryGenericPromise; - /** Define a row template to customize output. See github wiki for more details. */ - rowTemplate?: any; + /** Defines the binding to select all at once */ + selectAllState?: KnockoutObservable; - /** all of the items selected in the grid. In single select mode there will only be one item in the array. */ - selectedItems?: KnockoutObservableArray; + /** all of the items selected in the grid. In single select mode there will only be one item in the array. */ + selectedItems?: KnockoutObservableArray; - /** Disable row selections by clicking on the row and only when the checkbox is clicked. */ - selectWithCheckboxOnly?: boolean; + /** Disable row selections by clicking on the row and only when the checkbox is clicked. */ + selectWithCheckboxOnly?: boolean; - /** Enables menu to choose which columns to display and group by. - If both showColumnMenu and showFilter are false the menu button will not display.*/ - showColumnMenu?: boolean; + /** Enables menu to choose which columns to display and group by. + If both showColumnMenu and showFilter are false the menu button will not display.*/ + showColumnMenu?: boolean; - /** Enables display of the filterbox in the column menu. - If both showColumnMenu and showFilter are false the menu button will not display.*/ - showFilter?: boolean; + /** Enables display of the filterbox in the column menu. + If both showColumnMenu and showFilter are false the menu button will not display.*/ + showFilter?: boolean; - /** Show the dropzone for drag and drop grouping */ - showGroupPanel?: boolean; + /** Show the dropzone for drag and drop grouping */ + showGroupPanel?: boolean; - /** Define a sortInfo object to specify a default sorting state. - You can also observe this variable to utilize server-side sorting (see useExternalSorting). - Syntax is sortinfo: { fields: ['fieldName1',' fieldName2'], direction: 'ASC'/'asc' || 'desc'/'DESC'}*/ - sortInfo?: any; + /** Define a sortInfo object to specify a default sorting state. + You can also observe this variable to utilize server-side sorting (see useExternalSorting). + Syntax is sortinfo: { fields: ['fieldName1',' fieldName2'], direction: 'ASC'/'asc' || 'desc'/'DESC'}*/ + sortInfo?: SortInfo | KnockoutObservable; - /** Set the tab index of the Vieport. */ - tabIndex?: number; + /** Set the tab index of the Vieport. */ + tabIndex?: number; - /** Prevents the internal sorting from executing. - The sortInfo object will be updated with the sorting information so you can handle sorting (see sortInfo)*/ - useExternalSorting?: boolean; - } + /** Prevents the internal sorting from executing. + The sortInfo object will be updated with the sorting information so you can handle sorting (see sortInfo)*/ + useExternalSorting?: boolean; + } - interface ColumnDef { - /** The string name of the property in your data model you want that column to represent. Can also be a property path on your data model. 'foo.bar.myField', 'Name.First', etc.. */ - field: string; + type Direction = "asc" | "desc"; - /** Sets the pretty display name of the column. default is the field given */ - displayName?: string; + interface SortInfo { + /** Which column to sort */ + column: SortColumn; - /** Sets the width of the column. Can be a fixed width in pixels as an int (42), string px('42px'), percentage string ('42%'), weighted asterisks (width divided by total number of *'s is all column definition widths) See github wiki for more details. */ - width?: string; - } + /** Which direction to sort */ + direction: Direction; + } + + interface SortColumn { + /** The string name of the property in your data model you want that column to represent. Can also be a property path on your data model. 'foo.bar.myField', 'Name.First', etc.. */ + field: string; - interface FilterOptions { - filterText?: string; - useExternalFilter?: boolean; - } + /** Sets the sort function for the column. Useful when you have data that is formatted in an unusal way or if you want to sort on an underlying data type. Example: function(a,b){return a > b} */ + sortingAlgorithm?: ((a:any, b:any) => number); + } - interface PagingOptions { - /** pageSizes: list of available page sizes. */ - pageSizes?: number[]; - /** pageSize: currently selected page size. */ - pageSize?: number; - /** totalServerItems: Total items are on the server. */ - totalServerItems?: number; - /** currentPage: the uhm... current page. */ - currentPage?: number; - } + interface ColumnDef { + /** Appends a css class for the column cells */ + cellClass?:string; + + /** + * A function which takes the value of the cell and returns the display value. Useful when your data model has an underlying value which you need to convert to a human readable format. + * @param val + * @returns the display value + * @example function(unixTimeTicks) { return new Date(unixTimeTicks); } + */ + cellFormatter?(val:any): string; + + /**Sets the cell template for the column. See github wiki for more details.*/ + cellTemplate?: string | JQueryGenericPromise; + + /** Sets the pretty display name of the column. default is the field given */ + displayName?: string; + + /** The string name of the property in your data model you want that column to represent. Can also be a property path on your data model. 'foo.bar.myField', 'Name.First', etc.. */ + field: string; + + /** Sets the template for the column header cell. See github wiki for more details. */ + headerCellTemplate?: string | JQueryGenericPromise; + + /** Appends a css class for the column header. */ + headerClass?: string; + + /**Sets the maximum width of the column.*/ + maxWidth?: number; + + /**Whether or not column is resizable. */ + resizable?: boolean; + + /**Whether or not column is sortable. */ + sortable?: boolean; + + /** Sets the sort function for the column. Useful when you have data that is formatted in an unusal way or if you want to sort on an underlying data type. Example: function(a,b){return a > b} */ + sortFn?: ((a: any, b: any) => number); + + /** Sets the width of the column. Can be a fixed width in pixels as an int (42), string px('42px'), percentage string ('42%'), weighted asterisks (width divided by total number of *'s is all column definition widths) See github wiki for more details. */ + width?: string; + } + + interface FilterOptions { + /** Variable to contain the current search filter */ + filterText?: KnockoutObservable; + + /** Is the filtering internal or does it require a server visit. You should subscribe to filterText to refresh */ + useExternalFilter?: boolean; + + /** Number of seconds to throttle before reapplying search */ + filterThrottle?: number; + } + + interface PagingOptions { + /** pageSizes: list of available page sizes. */ + pageSizes?: KnockoutObservableArray; + + /** pageSize: currently selected page size. */ + pageSize?: KnockoutObservable; + + /** totalServerItems: Total items are on the server. */ + totalServerItems?: KnockoutObservable; + + /** currentPage: the uhm... current page. */ + currentPage?: KnockoutObservable; + } } interface IKg { domUtilityService: kg.DomUtilityService; + + /** Default grid template */ + defaultGridTemplate():string; + + /** Default row template. Can be overriden in GridOptions.rowTemplate */ + defaultRowTemplate(): string; + + /** Default cell template. Can be overriden in GridOptions.cellTemplate */ + defaultCellTemplate(): string; + + /** Default aggregate template */ + aggregateTemplate(): string; + + /** Default headerrow template. Can be overriden in GridOptions.headerRowTemplate */ + defaultHeaderRowTemplate(): string; + + /** Default headercell template. Can be overriden in GridOptions.headerCellTemplate */ + defaultHeaderCellTemplate():string; } declare var kg: IKg; @@ -199,4 +277,3 @@ declare var kg: IKg; declare module "kg" { export = kg; } - diff --git a/koa/koa-tests.ts b/koa/koa-tests.ts index e984364973..71814fe4fc 100644 --- a/koa/koa-tests.ts +++ b/koa/koa-tests.ts @@ -9,6 +9,7 @@ app.use((ctx, next) => { const end: any = new Date(); const ms = end - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); + ctx.assert(true, 404, 'Yep!'); }); }); diff --git a/koa/koa.d.ts b/koa/koa.d.ts index 922b243511..b005067b1f 100644 --- a/koa/koa.d.ts +++ b/koa/koa.d.ts @@ -38,7 +38,7 @@ declare module "koa" { toJSON(): any; inspect(): any; throw(code?: any, message?: any): void; - assert(): void; + assert(test: any, status: number, message: string): void; } export interface Request { diff --git a/leaflet-markercluster/leaflet-markercluster.d.ts b/leaflet-markercluster/leaflet-markercluster.d.ts index c9a3140fda..7d8757be03 100644 --- a/leaflet-markercluster/leaflet-markercluster.d.ts +++ b/leaflet-markercluster/leaflet-markercluster.d.ts @@ -51,9 +51,10 @@ declare namespace L { /* * The maximum radius that a cluster will cover from the central marker (in pixels). Default 80. - * Decreasing will make more, smaller clusters. + * Decreasing will make more, smaller clusters. You can also use a function that accepts + * the current map zoom and returns the maximum cluster radius in pixels */ - maxClusterRadius?: number; + maxClusterRadius?: number | ((zoom: number) => number); /* * Options to pass when creating the L.Polygon(points, options) to show the bounds of a cluster. @@ -82,11 +83,21 @@ declare namespace L { * Function used to create the cluster icon */ iconCreateFunction?: any; + + /* + * Boolean to split the addLayers processing in to small intervals so that the page does not freeze. + */ + chunkedLoading?: boolean; + + /* + * Time delay (in ms) between consecutive periods of processing for addLayers. Default to 50ms. + */ + chunkDelay?: number; } export class MarkerClusterGroup extends FeatureGroup { - initialize(): void; - initialize(options: MarkerClusterGroupOptions): void; + constructor(); + constructor(options: MarkerClusterGroupOptions); /* * Bulk methods for adding and removing markers and should be favoured over the @@ -121,5 +132,11 @@ declare namespace L { * Returns the array of total markers contained within that cluster. */ getAllChildMarkers(): Marker[]; + + /* + * Zooms to show the given marker (spiderfying if required), + * calls the callback when the marker is visible on the map. + */ + zoomToShowLayer(layer: any, callback: () => void): void; } } diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 04e8a44a36..94cbe8499a 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1,11 +1,14 @@ -// Type definitions for Leaflet.js 0.7.3 +// Type definitions for Leaflet.js 1.0.0 // Project: https://github.com/Leaflet/Leaflet // Definitions by: Vladimir Zotov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + declare namespace L { type LatLngExpression = LatLng | number[] | ({ lat: number; lng: number }) type LatLngBoundsExpression = LatLngBounds | LatLngExpression[]; + type PositionString = 'topleft' | 'topright' | 'bottomleft' | 'bottomright'; } declare namespace L { @@ -16,7 +19,7 @@ declare namespace L { * The position of the control (one of the map corners). See control positions. * Default value: 'bottomright'. */ - position?: string; + position?: PositionString; /** * The HTML text shown before the attributions. Pass false to disable. @@ -219,7 +222,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the circle (GeoJSON Point Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; } } @@ -254,11 +257,6 @@ declare namespace L { * Sets the radius of a circle marker. Units are in pixels. */ setRadius(radius: number): CircleMarker; - - /** - * Returns a GeoJSON representation of the circle marker (GeoJSON Point Feature). - */ - toGeoJSON(): any; } } @@ -343,12 +341,12 @@ declare namespace L { /** * Sets the position of the control. See control positions. */ - setPosition(position: string): Control; + setPosition(position: PositionString): Control; /** * Returns the current position of the control. */ - getPosition(): string; + getPosition(): PositionString; /** * Adds the control to the map. @@ -400,7 +398,7 @@ declare namespace L { * * Default value: 'topright'. */ - position?: string; // 'topleft' | 'topright' | 'bottomleft' | 'bottomright' + position?: PositionString; /** * The text set on the zoom in button. @@ -550,7 +548,7 @@ declare namespace L { * positions. * Default value: 'topright'. */ - position?: string; + position?: PositionString; } } @@ -1709,8 +1707,9 @@ declare namespace L { /** * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). + * Note: Descendent classes MultiPolygon & MultiPolyLine return `Feature`s, not `FeatureCollection`s */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.FeatureCollection|GeoJSON.Feature; //////////// //////////// @@ -1739,7 +1738,7 @@ declare namespace L { * * Default value: 'topright'. */ - position?: string; + position?: PositionString; /** * If true, the control will be collapsed into an icon and expanded on mouse hover @@ -2000,7 +1999,7 @@ declare namespace L { export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; /** - * Clips the segment a to b by rectangular bounds. Used by Leaflet to only show + * Clips the segment a to b by rectangular bounds. Used by Leaflet to only show * polyline points that are on the screen or near, increasing performance. Returns * either false or a length-2 array of clipped points. */ @@ -2734,6 +2733,22 @@ declare namespace L.Map { * If true, it will delay moveend event so that it doesn't happen many times in a row. */ debounceMoveend?: boolean; + + /** + * Duration of animated panning, in seconds. + */ + duration?: number; + + /** + * The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). + * 1.0 means linear animation, the less the more bowed the curve. + */ + easeLinearity?: number; + + /** + * If true, panning won't fire movestart event on start (used internally for panning inertia). + */ + noMoveStart?: boolean; } export interface FitBoundsOptions extends ZoomPanOptions { @@ -2921,7 +2936,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; /** * Marker dragging handler (by both mouse and touch). @@ -3081,7 +3096,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; } } @@ -3122,7 +3137,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; } } @@ -3384,7 +3399,7 @@ declare namespace L { className?: string; /** - * Sets the radius of a circle marker. + * Sets the radius of a circle marker. */ radius?: number; @@ -3543,7 +3558,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the polyline (GeoJSON LineString Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; } } @@ -3858,7 +3873,7 @@ declare namespace L { * The position of the control (one of the map corners). See control positions. * Default value: 'bottomleft'. */ - position?: string; + position?: PositionString; /** * Maximum width of the control in pixels. The width is set dynamically to show diff --git a/linq/linq-tests.ts b/linq/linq-tests.ts index fb9c3f3d6e..d30ccc8f8c 100644 --- a/linq/linq-tests.ts +++ b/linq/linq-tests.ts @@ -30,7 +30,7 @@ describe("Linq.js tests", function () { it("Grouping Methods", function () { expect(Enumerable.From(["a","aa","aaa","a","a","aaa"]) .GroupBy((item:string) => item.length) - .Select((g: linq.Grouping) => { return { key: g.Key(), count: g.Count() }; }) + .Select((g: linq.Grouping) => { return { key: g.Key(), count: g.Count() }; }) .OrderBy(g => g.key) .Select(g => g.key+":"+g.count) .ToString(",")).toBe("1:3,2:1,3:2"); diff --git a/linq/linq.d.ts b/linq/linq.d.ts index facd5d5901..f7417fc8da 100644 --- a/linq/linq.d.ts +++ b/linq/linq.d.ts @@ -49,8 +49,10 @@ declare namespace linq { Scan(seed: any, func: string, resultSelector?: string): Enumerable; Select(selector: ($: T, i: number) => TResult): Enumerable; Select(selector: string): Enumerable; - SelectMany(collectionSelector: ($: any, i: number) => any[], resultSelector?: ($: any, item: any) => any): Enumerable; - SelectMany(collectionSelector: ($: any, i: number) => Enumerable, resultSelector?: ($: any, item: any) => any): Enumerable; + SelectMany(collectionSelector: ($: T, i: number) => TResult[]): Enumerable; + SelectMany(collectionSelector: ($: T, i: number) => Enumerable): Enumerable; + SelectMany(collectionSelector: ($: T, i: number) => TCollectionItem[], resultSelector: ($: T, item: TCollectionItem) => TResult): Enumerable; + SelectMany(collectionSelector: ($: T, i: number) => Enumerable, resultSelector: ($: T, item: TCollectionItem) => TResult): Enumerable; SelectMany(collectionSelector: string, resultSelector?: string): Enumerable; Where(predicate: ($ : T, i: number) => boolean): Enumerable; Where(predicate: string): Enumerable; @@ -170,12 +172,12 @@ declare namespace linq { LastIndexOf(item: T): number; // Convert Methods ToArray(): T[]; - ToLookup(keySelector: ($: T) => any, elementSelector?: ($: T) => any, compareSelector?: (key: any) => any): Lookup; - ToLookup(keySelector: string, elementSelector?: string, compareSelector?: string): Lookup; + ToLookup(keySelector: ($: T) => TKey, elementSelector?: ($: T) => TValue, compareSelector?: (key: TKey) => any): Lookup; + ToLookup(keySelector: string, elementSelector?: string, compareSelector?: string): Lookup; ToObject(keySelector: ($: T) => string, elementSelector: ($: T) => any): any; ToObject(keySelector: string, elementSelector: string): any; - ToDictionary(keySelector: ($: T) => any, elementSelector: ($: T) => any, compareSelector?: (key: T) => any): Dictionary; - ToDictionary(keySelector: string, elementSelector: string, compareSelector?: string): Dictionary; + ToDictionary(keySelector: ($: T) => TKey, elementSelector: ($: T) => TValue, compareSelector?: (key: TKey) => any): Dictionary; + ToDictionary(keySelector: string, elementSelector: string, compareSelector?: string): Dictionary; ToJSON(replacer?: (key: any, value: any) => any, space?: number): string; ToJSON(replacer?: string, space?: number): string; ToString(separator?: string, selector?: ($: T) =>any): string; @@ -211,26 +213,26 @@ declare namespace linq { ThenByDescending(keySelector: string): OrderedEnumerable; } - interface Grouping extends Enumerable { - Key(): any; + interface Grouping extends Enumerable { + Key(): TKey; } - interface Lookup { + interface Lookup { Count(): number; - Get(key: any): Enumerable; - Contains(key: any): boolean; - ToEnumerable(): Enumerable; + Get(key: TKey): Enumerable; + Contains(key: TKey): boolean; + ToEnumerable(): Enumerable>; } - interface Dictionary { - Add(key: any, value: TValue): void; - Get(key: any): any; - Set(key: any, value: TValue): boolean; - Contains(key: any): boolean; + interface Dictionary { + Add(key: TKey, value: TValue): void; + Get(key: TKey): TValue; + Set(key: TKey, value: TValue): boolean; + Contains(key: TKey): boolean; Clear(): void; - Remove(key: any): void; + Remove(key: TKey): void; Count(): number; - ToEnumerable(): Enumerable; + ToEnumerable(): Enumerable>; } interface KeyValuePair { diff --git a/lodash/lodash-3.10.d.ts b/lodash/lodash-3.10.d.ts index b92de15c89..3948215468 100644 --- a/lodash/lodash-3.10.d.ts +++ b/lodash/lodash-3.10.d.ts @@ -7732,6 +7732,53 @@ declare module _ { thisArg?: any): TResult; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.reduce + **/ + reduce( + callback: MemoIterator, + accumulator: TResult, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + reduce( + callback: MemoIterator, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + inject( + callback: MemoIterator, + accumulator: TResult, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + inject( + callback: MemoIterator, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + foldl( + callback: MemoIterator, + accumulator: TResult, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + foldl( + callback: MemoIterator, + thisArg?: any): LoDashExplicitObjectWrapper; + } + //_.reduceRight interface LoDashStatic { /** diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 115cc4a1e6..f1772191cd 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -8547,6 +8547,21 @@ declare module _ { callback: MemoIterator): TResult; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.reduce + **/ + reduce( + callback: MemoIterator, + accumulator: TResult): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + reduce( + callback: MemoIterator): LoDashExplicitObjectWrapper; + } + //_.reduceRight interface LoDashStatic { /** diff --git a/mCustomScrollbar/mCustomScrollbar-tests.ts b/mCustomScrollbar/mCustomScrollbar-tests.ts index 7dcf793564..9c5f030679 100644 --- a/mCustomScrollbar/mCustomScrollbar-tests.ts +++ b/mCustomScrollbar/mCustomScrollbar-tests.ts @@ -9,7 +9,8 @@ class SimpleTest { this.element.mCustomScrollbar({ scrollButtons: { - enable: true + enable: true, + scrollAmount: 2 } }); } @@ -22,38 +23,78 @@ class SimpleTestAllParams { this.element = $(".content"); this.element.mCustomScrollbar({ - setWidth: false, - setHeight: false, + setWidth: 22, + setHeight: "40%", + setTop: 0, + setLeft: 22, axis: "y", + scrollbarPosition: "inside", scrollInertia: 950, - mouseWheel: true, - mouseWheelPixels: "auto", autoDraggerLength: true, autoHideScrollbar: false, + autoExpandScrollbar: false, + alwaysShowScrollbar: 0, + snapAmount: [3,3], + snapOffset: 3, + mouseWheel: { + enable: true, + scrollAmount: 1, + axis:"x", + preventDefault: false, + deltaFactor:12, + normalizeDelta:true, + invert: false, + disableOver: ["select","option"] + + }, scrollButtons: { enable: false, - scrollType: "continuous", - scrollSpeed: "auto", - scrollAmount: 40 + scrollType: "stepped", + scrollAmount: 40, + tabindex: 33, + }, + keyboard:{ + enable: true, + scrollAmount:5, + scrollType:"stepless" }, advanced: { updateOnBrowserResize: true, updateOnContentResize: false, + updateOnImageLoad: true, + updateOnSelectorChange: "ul li", + extraDraggableSelectors: ".myClass", + releaseDraggableSelectors: ".myClass", + autoUpdateTimeout:60, autoExpandHorizontalScroll: false, - autoScrollOnFocus: true, - normalizeMouseWheelDelta: false + autoScrollOnFocus: "input", }, contentTouchScroll: true, + documentTouchScroll: false, + callbacks: { + onCreate: () => { }, + onInit: () => { }, onScrollStart: () => { }, onScroll: () => { }, onTotalScroll: () => { }, onTotalScrollBack: () => { }, onTotalScrollOffset: 0, onTotalScrollBackOffset: 0, - whileScrolling: () => { } + whileScrolling: () => { }, + alwaysTriggerOffsets: false, + onOverflowY: () => { }, + onOverflowX: () => { }, + onOverflowYNone: () => {}, + onOverflowXNone: () => {}, + onBeforeUpdate: () => {}, + onUpdate: () => {}, + onImageLoad: () => {}, + onSelectorChange: () => {}, }, - theme: "light" + theme: "light", + live: true, + liveSelector: ".myClass" }); } } diff --git a/mCustomScrollbar/mCustomScrollbar.d.ts b/mCustomScrollbar/mCustomScrollbar.d.ts index 08e532d7bf..aa088d6f5c 100644 --- a/mCustomScrollbar/mCustomScrollbar.d.ts +++ b/mCustomScrollbar/mCustomScrollbar.d.ts @@ -10,16 +10,35 @@ declare namespace MCustomScrollbar { /** * Set the width of your content (overwrites CSS width), value in pixels (integer) or percentage (string) */ - setWidth?: any; + setWidth?: boolean|number|string; /** * Set the height of your content (overwirtes CSS height), value in pixels (integer) or percentage (string) */ - setHeight?: any; + setHeight?: boolean|number|string; + /** + * Set the initial css top property of content, accepts string values (css top position). + * Example: setTop: "-100px". + */ + setTop? : number|string; + /** + * Set the initial css top property of content, accepts string values (css top position). + * Example: setTop: "-100px". + */ + setLeft? : number|string; /** * Define content’s scrolling axis (the type of scrollbars added to the element: vertical and/of horizontal). - * Available values: "y", "x", "yx". y -vertical, x - horizontal + * Available values: "y", "x", "yx". y -vertical, x - horizontal, yx - vertical and horizontal */ - axis?: string; + axis?: "x"|"y"|"yx"; + /** + * Set the position of scrollbar in relation to content. + * Available values: "inside", "outside". + * Setting scrollbarPosition: "inside" (default) makes scrollbar appear inside the element. + * Setting scrollbarPosition: "outside" makes scrollbar appear outside the element. + * Note that setting the value to "outside" requires your element (or parent elements) + * to have CSS position: relative (otherwise the scrollbar will be positioned in relation to document’s root element). + */ + scrollbarPosition?: "inside"|"outside"; /** * Always keep scrollbar(s) visible, even when there’s nothing to scroll. * 0 – disable (default) @@ -28,6 +47,18 @@ declare namespace MCustomScrollbar { */ alwaysShowScrollbar?: number; /** + * Make scrolling snap to a multiple of a fixed number of pixels. Useful in cases like scrolling tabular data, + * image thumbnails or slides and you need to prevent scrolling from stopping half-way your elements. + * Note that your elements must be of equal width or height in order for this to work properly. + * To set different values for vertical and horizontal scrolling, use an array: [y,x] + */ + snapAmount?: number|[number,number]; + /** + * Set an offset (in pixels) for the snapAmount option. Useful when for example you need to offset the + * snap amount of table rows by the table header. + */ + snapOffset?: number; + /** * Enable or disable auto-expanding the scrollbar when cursor is over or dragging the scrollbar. */ autoExpandScrollbar?: boolean; @@ -47,7 +78,7 @@ declare namespace MCustomScrollbar { * Set the mouse-wheel scrolling amount (in pixels). * The default value "auto" adjusts scrolling amount according to scrollable content length. */ - scrollAmount?: number; + scrollAmount?: "auto"|number; /** * Define the mouse-wheel scrolling axis when both vertical and horizontal scrollbars are present. * Set axis: "y" (default) for vertical or axis: "x" for horizontal scrolling. @@ -76,7 +107,27 @@ declare namespace MCustomScrollbar { * Set the tags that disable mouse-wheel when cursor is over them. * Default value: ["select","option","keygen","datalist","textarea"] */ - disableOver?: string[] + disableOver?: string[]; + } + /** + * Keyboard support + */ + keyboard?:{ + /** + * Enable or disable content scrolling via keyboard. + */ + enable?: boolean; + /** + * Set the keyboard arrows scrolling amount (in pixels). + * The default value "auto" adjusts scrolling amount according to scrollable content length. + */ + scrollAmount?: "auto"|number; + /** + * Define the buttons scrolling type/behavior. + * scrollType: "stepless" – continuously scroll content while pressing the button (default) + * scrollType: "stepped" – each button click scrolls content by a certain amount (defined in scrollAmount option above) + */ + scrollType?: "stepless"|"stepped"; } /** * Mouse wheel scrolling pixels amount, value in pixels (integer) or "auto" (script calculates and sets pixels amount according to content length) @@ -96,19 +147,21 @@ declare namespace MCustomScrollbar { */ enable?: boolean; /** - * Scroll buttons scroll type, values: "continuous" (scroll continuously while pressing the button), "pixels" (scrolls by a fixed number of pixels on each click") + * Define the buttons scrolling type/behavior. + * scrollType: "stepless" – continuously scroll content while pressing the button (default) + * scrollType: "stepped" – each button click scrolls content by a certain amount (defined in scrollAmount option above) */ - scrollType?: string; + scrollType?: "stepless"|"stepped"; /** - * Scroll buttons continuous scrolling speed, integer value or "auto" (script calculates and sets the speed according to content length) + * Set a tabindex value for the buttons. */ - scrollSpeed?: number | string; + tabindex?: number; /** * Scroll buttons pixels scrolling amount, value in pixels or "auto" */ - scrollAmount?: number | string; + scrollAmount?: "auto"|number ; } - advanced?: { + advanced?: { /** * Update scrollbars on browser resize (for fluid content blocks and layouts based on percentages), values: true, false. Set to false only when you content has fixed dimensions */ @@ -119,27 +172,75 @@ declare namespace MCustomScrollbar { */ updateOnContentResize?: boolean; /** + * Update scrollbar(s) automatically each time an image inside the element is fully loaded. + * Default value is auto which triggers the function only on "x" and "yx" axis (if needed). + * The value should be true when your content contains images and you need the function to trigger on any axis. + */ + updateOnImageLoad?: "auto"|boolean; + /** + * Add extra selector(s) that’ll release scrollbar dragging upon mouseup, pointerup, touchend etc. + * Example: extraDraggableSelectors: ".myClass, #myID" + */ + extraDraggableSelectors?: string; + /** + * Add extra selector(s) that’ll allow scrollbar dragging upon mousemove/up, pointermove/up, touchend etc. + * Example: releaseDraggableSelectors: ".myClass, #myID" + */ + releaseDraggableSelectors?: string; + /** + * Set the auto-update timeout in milliseconds. + * Default timeout: 60 + */ + autoUpdateTimeout?: number; + /** + * Update scrollbar(s) automatically when the amount and size of specific selectors changes. + * Useful when you need to update the scrollbar(s) automatically, each time a type of element is added, removed or changes its size. + * For example, setting updateOnSelectorChange: "ul li" will update scrollbars each time list-items inside the element are changed. + * Setting the value to true, will update scrollbars each time any element is changed. + * To disable (default) set to false. + */ + updateOnSelectorChange?: string|boolean; + /** * Auto-expanding content's width on horizontal scrollbars, values: true, false. Set to true if you have horizontal scrollbr on content that change on-the-fly. Demo contains * blocks with images and horizontal scrollbars that use this option parameter */ autoExpandHorizontalScroll?: boolean; /** - * Auto-scrolling on elements that have focus (e.g. scrollbar automatically scrolls to form text fields when the TAB key is pressed), values: true, false + * Set the list of elements/selectors that will auto-scroll content to their position when focused. + * For example, when pressing TAB key to focus input fields, if the field is out of the viewable area the content + * will scroll to its top/left position (same bahavior with browser’s native scrollbar). + * To completely disable this functionality, set autoScrollOnFocus: false. + * Default: + * "input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']" */ - autoScrollOnFocus?: boolean; + autoScrollOnFocus?: boolean|string; /** * Normalize mouse wheel delta (-1/1), values: true, false */ normalizeMouseWheelDelta?: boolean; } - /** - * Additional scrolling method by touch-swipe content (for touch enabled devices), value: true, false - */ - contentTouchScroll?: boolean; + /** + * Enable or disable content touch-swipe scrolling for touch-enabled devices. + * To completely disable, set contentTouchScroll: false. + * Integer values define the axis-specific minimum amount required for scrolling momentum (default: 25). + */ + contentTouchScroll?: boolean|number; + /** + * Enable or disable document touch-swipe scrolling for touch-enabled devices. + */ + documentTouchScroll?: boolean; /** * All of the following callbacks option have examples in the callback demo - http://manos.malihu.gr/tuts/custom-scrollbar-plugin/callbacks_example.html */ callbacks?: { + /** + * A function to call when plugin markup is created. + */ + onCreate?: () => void; + /** + * A function to call when scrollbars have initialized + */ + onInit?: () => void; /** * User defined callback function, triggered on scroll start event. You can call your own function(s) each time a scroll event begins */ @@ -176,11 +277,56 @@ declare namespace MCustomScrollbar { * Set alwaysTriggerOffsets: false when you need to trigger onTotalScroll and onTotalScrollBack callbacks once, each time scroll end or beginning is reached. */ alwaysTriggerOffsets?: boolean; + /** + * A function to call when content becomes long enough and vertical scrollbar is added. + */ + onOverflowY?: () => void; + /** + * A function to call when content becomes wide enough and horizontal scrollbar is added. + */ + onOverflowX?: () => void; + /** + * A function to call when content becomes short enough and vertical scrollbar is removed. + */ + onOverflowYNone?: () => void; + /** + * A function to call when content becomes narrow enough and horizontal scrollbar is removed. + */ + onOverflowXNone?: () => void; + /** + * A function to call right before scrollbar(s) are updated. + */ + onBeforeUpdate?: () => void; + /** + * A function to call when scrollbar(s) are updated. + */ + onUpdate?: () => void; + /** + * A function to call each time an image inside the element is fully loaded and scrollbar(s) are updated. + */ + onImageLoad?: () => void; + /** + * A function to call each time a type of element is added, removed or changes its size and scrollbar(s) are updated. + */ + onSelectorChange?: () => void; } - /** - * Set a scrollbar ready-to-use theme. See themes demo for all themes - http://manos.malihu.gr/tuts/custom-scrollbar-plugin/scrollbar_themes_demo.html - */ - theme?: string; + /** + * Set a scrollbar ready-to-use theme. See themes demo for all themes - http://manos.malihu.gr/tuts/custom-scrollbar-plugin/scrollbar_themes_demo.html + */ + theme?: string; + /** + * Enable or disable applying scrollbar(s) on all elements matching the current selector, now and in the future. + * Set live: true when you need to add scrollbar(s) on elements that do not yet exist in the page. + * These could be elements added by other scripts or plugins after some action by the user takes place (e.g. lightbox markup may not exist untill the user clicks a link). + * If you need at any time to disable or enable the live option, set live: "off" and "on" respectively. + * You can also tell the script to disable live option after the first invocation by setting live: "once". + */ + live?: string|boolean; + /** + * Set the matching set of elements (instead of the current selector) to add scrollbar(s), now and in the future. + */ + liveSelector?: string; + } interface ScrollToParameterOptions { diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 198f49f7bc..367aae4e11 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -641,6 +641,7 @@ declare namespace __MaterialUI { touchRippleColor?: string; touchRippleOpacity?: number; type?: string; + containerElement?: React.ReactNode | string; } interface EnhancedButtonProps extends React.HTMLAttributes, SharedEnhancedButtonProps { diff --git a/mdns/mdns.d.ts b/mdns/mdns.d.ts index d159ee7dba..63e1e7b72a 100644 --- a/mdns/mdns.d.ts +++ b/mdns/mdns.d.ts @@ -49,6 +49,9 @@ declare namespace MDNS { interface Browser extends NodeJS.EventEmitter { start():any; stop():any; + on(event:string, listener:Function):this; + on(event:'serviceUp', listener:(info:Service)=>void):this; + on(event:'serviceDown', listener:(info:Service)=>void):this; } interface BrowserStatic { diff --git a/meteor/README.md b/meteor/README.md index d9d7898ffb..7c8aa5cb1d 100644 --- a/meteor/README.md +++ b/meteor/README.md @@ -1,4 +1,13 @@ -# Meteor Type Definitions +# Meteor Type Definitions [DEPRECATED] + +## Deprecated + +These definitions for Meteor are now deprecated. They should still work for versions of Meteor up to 1.2.1. + +The canonical TypeScript definitions for Meteor can now be found using the NPM [Typings definition manager](https://www.npmjs.com/package/typings). If you prefer to view the definitions directly, or contribute to them, they can be found here: . + + +## Description These are the definitions for version 1.3 of Meteor. These definitions were generated from the from the same [Meteor data.js file] (https://github.com/meteor/meteor/blob/devel/docs/client/data.js) that is used to generate the official [Meteor docs] (http://docs.meteor.com/). The code that generates these definitions can be found [here](https://github.com/meteor-typescript/meteor-typescript-libs/). diff --git a/meteor/meteor-tests.ts b/meteor/meteor-tests.ts index bc877bdea0..4b5a154794 100644 --- a/meteor/meteor-tests.ts +++ b/meteor/meteor-tests.ts @@ -650,16 +650,16 @@ Accounts.emailTemplates.siteName = "AwesomeSite"; Accounts.emailTemplates.from = "AwesomeSite Admin "; Accounts.emailTemplates.headers = { asdf: 'asdf', qwer: 'qwer' }; -Accounts.emailTemplates.enrollAccount.subject = function (user) { +Accounts.emailTemplates.enrollAccount.subject = function (user: Meteor.User) { return "Welcome to Awesome Town, " + user.profile.name; }; -Accounts.emailTemplates.enrollAccount.html = function (user, url) { +Accounts.emailTemplates.enrollAccount.html = function (user: Meteor.User, url: string) { return "

    Some html here

    "; }; Accounts.emailTemplates.enrollAccount.from = function() { return "asdf@asdf.com"; }; -Accounts.emailTemplates.enrollAccount.text = function (user, url) { +Accounts.emailTemplates.enrollAccount.text = function (user: Meteor.User, url: string) { return "You have been selected to participate in building a better future!" + " To activate your account, simply click the link below:\n\n" + url; diff --git a/mocha/mocha-tests.ts b/mocha/mocha-tests.ts index d0108263ec..c6185aa32b 100644 --- a/mocha/mocha-tests.ts +++ b/mocha/mocha-tests.ts @@ -66,6 +66,21 @@ function test_test() { }); } +function test_specify() { + + specify('does something', () => { }); + + specify('does something', (done) => { done(); }); + + specify.only('does something', () => { }); + + specify.skip('does something', () => { }); + + specify('does something', function () { + this.timeout(2000); + }); +} + function test_before() { before(() => { }); diff --git a/mocha/mocha.d.ts b/mocha/mocha.d.ts index 56c6cdba82..eb167c83c9 100644 --- a/mocha/mocha.d.ts +++ b/mocha/mocha.d.ts @@ -44,6 +44,7 @@ declare var it: Mocha.ITestDefinition; declare var xit: Mocha.ITestDefinition; // alias for `it` declare var test: Mocha.ITestDefinition; +declare var specify: Mocha.ITestDefinition; declare function before(action: () => void): void; diff --git a/node/node.d.ts b/node/node.d.ts index bffb007c4b..8fbed6bc51 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1399,6 +1399,7 @@ declare module "fs" { export interface ReadStream extends stream.Readable { close(): void; + destroy(): void; } export interface WriteStream extends stream.Writable { close(): void; diff --git a/nw.js/nw.js-tests.ts b/nw.js/nw.js-tests.ts new file mode 100644 index 0000000000..585b7ebe3c --- /dev/null +++ b/nw.js/nw.js-tests.ts @@ -0,0 +1,352 @@ +/// +/* + * nw.App Tests + */ +var argv = nw.App.argv; +var fullArgv = nw.App.fullArgv; +var filteredArgv = nw.App.filteredArgv; +var dataPath = nw.App.dataPath; +var manifest = nw.App.manifest; + +nw.App.clearCache(); +nw.App.closeAllWindows(); +nw.App.crashBrowser(); +nw.App.crashRenderer(); +nw.App.getProxyForURL( 'https://github.com/alirdn' ); +nw.App.setProxyConfig( 'http=foopy:80;ftp=foopy2' ); +nw.App.quit(); +nw.App.addOriginAccessWhitelistEntry( 'http://github.com/', 'chrome-extension', location.host, true ); +nw.App.removeOriginAccessWhitelistEntry( 'http://github.com/', 'chrome-extension', location.host, true ); + +/* + * Note: + * nw.App.registerGlobalHotKey() tested in Shortcut Tests + * nw.App.unregisterGlobalHotKey() tested in Shortcut Tests + * */ + +nw.App.on( 'open', function ( args ) { + console.log( args ); +}); + +nw.App.on( 'reopen', function () { + console.log( 'reopened' ); +}); + +/** + * nw.Clipboard Tests + */ +// get the system clipboard +var clipboard = nw.Clipboard.get(); +// Read from clipboard +var text = clipboard.get( 'text' ); +console.log( text ); + +// Or write something +clipboard.set( 'I love NW.js :)', 'text' ); + +// And clear it! +clipboard.clear(); + +/** + * nw.Menu Tests + */ +// Create an empty context menu +var menu = new nw.Menu(); + +// Add some items +menu.append( new nw.MenuItem( { label: 'Item A' }) ); +menu.append( new nw.MenuItem( { label: 'Item B' }) ); +menu.append( new nw.MenuItem( { type: 'separator' }) ); +menu.append( new nw.MenuItem( { label: 'Item C' }) ); + +// Remove one item +menu.removeAt( 1 ); + +// Popup as context menu +menu.popup( 10, 10 ); + +// Iterate menu's items +for ( var i = 0; i < menu.items.length; ++i ) { + console.log( menu.items[i] ); +} +// Create an empty menubar +var menu = new nw.Menu( { type: 'menubar' }); + +// Create a submenu as the 2nd level menu +var submenu = new nw.Menu(); +submenu.append( new nw.MenuItem( { label: 'Item A' }) ); +submenu.append( new nw.MenuItem( { label: 'Item B' }) ); + +// Create and append the 1st level menu to the menubar +menu.append( new nw.MenuItem( { + label: 'First Menu', + submenu: submenu +}) ); + +// Assign it to `window.menu` to get the menu displayed +nw.Window.get().menu = menu; + +/** + * nw.MenuItem Tests + */ +var item: any; + +// Create a separator +item = new nw.MenuItem( { type: 'separator' }); + +// Create a normal item with label and icon +item = new nw.MenuItem( { + type: "normal", + label: "I'm a menu item", + icon: "img/icon.png" +}); + +// Or you can omit the 'type' field for normal items +item = new nw.MenuItem( { label: 'Simple item' }); + +// Bind a callback to item +item = new nw.MenuItem( { + label: "Click me", + click: function () { + console.log( "I'm clicked" ); + }, + key: "s", + modifiers: "ctrl+alt", +}); + +// You can have submenu! +var submenu = new nw.Menu(); +submenu.append( new nw.MenuItem( { label: 'Item 1' }) ); +submenu.append( new nw.MenuItem( { label: 'Item 2' }) ); +submenu.append( new nw.MenuItem( { label: 'Item 3' }) ); +item.submenu = submenu; + +// And everything can be changed at runtime +item.label = 'New label'; +item.click = function () { + console.log( 'New click callback' ); +}; + +/** + * nw.Screen Tests + */ +//init must be called once during startup, before any function to nw.Screen can be called +nw.Screen.Init(); + +var screenCB = { + onDisplayBoundsChanged: function ( screen: any ) { + console.log( 'displayBoundsChanged', screen ); + }, + + onDisplayAdded: function ( screen: any ) { + console.log( 'displayAdded', screen ); + }, + + onDisplayRemoved: function ( screen: any ) { + console.log( 'displayRemoved', screen ) + } +}; + +// listen to screen events +nw.Screen.on( 'displayBoundsChanged', screenCB.onDisplayBoundsChanged ); +nw.Screen.on( 'displayAdded', screenCB.onDisplayAdded ); +nw.Screen.on( 'displayRemoved', screenCB.onDisplayRemoved ); + +/** + * nw.Screen.chooseDesktopMedia() Tests + */ +nw.Screen.Init(); // you only need to call this once +nw.Screen.chooseDesktopMedia( ["window", "screen"], + function ( streamId ) { + var vid_constraint = { + mandatory: { + chromeMediaSource: 'desktop', + chromeMediaSourceId: streamId, + maxWidth: 1920, + maxHeight: 1080 + }, + optional: [] + }; + //navigator.webkitGetUserMedia( { audio: false, video: constraint }, success_func, fallback_func ); + } +); + +/** + * nw.Screen.DesktopCaptureMonitor Tests + */ +var dcm = nw.Screen.DesktopCaptureMonitor; +nw.Screen.Init(); +dcm.on( "added", function ( id, name, order, type ) { + //select first stream and shutdown + var constraints = { + audio: { + mandatory: { + chromeMediaSource: "system", + chromeMediaSourceId: dcm.registerStream( id ) + } + }, + video: { + mandatory: { + chromeMediaSource: 'desktop', + chromeMediaSourceId: dcm.registerStream( id ) + } + } + }; + + // TODO: call getUserMedia with contraints + + dcm.stop(); +}); + +dcm.on( "removed", function ( id ) { +}); +dcm.on( "orderchanged", function ( id, new_order, old_order ) { +}); +dcm.on( "namechanged", function ( id, name ) { +}); +dcm.on( "thumbnailchanged", function ( id, thumbnail ) { +}); +dcm.start( true, true ); + +/** + * nw.Shell Tests + */ +// Open URL with default browser. +nw.Shell.openExternal( 'https://github.com/nwjs/nw.js' ); + +// Open a text file with default text editor. +nw.Shell.openItem( 'test.txt' ); + +// Show a file in parent folder with file manager. +nw.Shell.showItemInFolder( 'test.txt' ); + +/** + * nw.Shortcut Tests + */ +var option = { + key: "Ctrl+Shift+A", + active: function () { + console.log( "Global desktop keyboard shortcut: " + this.key + " active." ); + }, + failed: function ( msg: any ) { + // :(, fail to register the |key| or couldn't parse the |key|. + console.log( msg ); + } +}; + +// Create a shortcut with |option|. +var shortcut = new nw.Shortcut( option ); + +// Register global desktop shortcut, which can work without focus. +nw.App.registerGlobalHotKey( shortcut ); + +// If register |shortcut| successfully and user struck "Ctrl+Shift+A", |shortcut| +// will get an "active" event. + +// You can also add listener to shortcut's active and failed event. +shortcut.on( 'active', function () { + console.log( "Global desktop keyboard shortcut: " + this.key + " active." ); +}); + +shortcut.on( 'failed', function ( msg: any ) { + console.log( msg ); +}); + +// Unregister the global desktop shortcut. +nw.App.unregisterGlobalHotKey( shortcut ); + +/** + * nw.Tray Tests + */ +// Create a tray icon +var tray = new nw.Tray( { title: 'Tray', icon: 'img/icon.png' }); + +// Give it a menu +var menu = new nw.Menu(); +menu.append( new nw.MenuItem( { type: 'checkbox', label: 'box1' }) ); +tray.menu = menu; + +// Remove the tray +tray.remove(); +tray = null; + +/** + * nw.Window Tests + */ +// Get the current window +var win = nw.Window.get(); + +// Listen to the minimize event +win.on( 'minimize', function () { + console.log( 'Window is minimized' ); +}); + +// Minimize the window +win.minimize(); + +// Unlisten the minimize event +win.removeAllListeners( 'minimize' ); + +// Create a new window and get it +nw.Window.open( 'https://github.com', {}, function ( new_win ) { + // And listen to new window's focus event + new_win.on( 'focus', function () { + console.log( 'New window is focused' ); + }); +}); + +// Get the current window +var win = nw.Window.get(); + +// Create a new window and get it +nw.Window.open( 'https://github.com/nwjs/nw.js', {}, function ( new_win ) { + // do something with the newly created window +}); + +win.on( 'close', function () { + this.hide(); // Pretend to be closed already + console.log( "We're closing..." ); + this.close( true ); // then close it forcely +}); + +win.close(); + +// png as base64string +win.capturePage( function ( base64string ) { + // do something with the base64string +}, { format: 'png', datatype: 'raw' }); + +// png as node buffer +win.capturePage( function ( buffer ) { + // do something with the buffer +}, { format: 'png', datatype: 'buffer' }); + +// Open a new window. +nw.Window.open( 'popup.html', {}, function ( win ) { + + // Release the 'win' object here after the new window is closed. + win.on( 'closed', function () { + win = null; + }); + + // Listen to main window's close event + nw.Window.get().on( 'close', function () { + // Hide the window to give user the feeling of closing immediately + this.hide(); + + // If the new window is still open then close it. + if ( win != null ) + win.close( true ); + + // After closing the new window, close the main window. + this.close( true ); + }); + +}); + +nw.Window.get().on( 'new-win-policy', function ( frame, url, policy ) { + // do not open the window + policy.ignore(); + // and open it in external browser + nw.Shell.openExternal( url ); +}); diff --git a/nw.js/nw.js.d.ts b/nw.js/nw.js.d.ts new file mode 100644 index 0000000000..6ae2582e50 --- /dev/null +++ b/nw.js/nw.js.d.ts @@ -0,0 +1,1883 @@ +// Type definitions for nw.js v0.13.x and later +// Project: http://nwjs.io +// Definitions by: Alireza Dabiri Nejad +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * Helpers class and interfaces defined here, to make `nw` module cleaner. + */ +declare module NWJS_Helpers { + + /** + * Node.js v6.x EventEmitter Class + */ + class EventEmitter implements NodeJS.EventEmitter { + static EventEmitter: EventEmitter; + + static listenerCount( emitter: EventEmitter, event: string ): number; // deprecated + static defaultMaxListeners: number; + + addListener( event: string, listener: Function ): this; + + on( event: string, listener: Function ): this; + + once( event: string, listener: Function ): this; + + removeListener( event: string, listener: Function ): this; + + removeAllListeners( event?: string ): this; + + setMaxListeners( n: number ): this; + + getMaxListeners(): number; + + listeners( event: string ): Function[]; + + emit( event: string, ...args: any[] ): boolean; + + listenerCount( type: string ): number; + } + + /** + * The clipboard object. + */ + interface clip { + + /** + * Write `data` of `type` to the clipboard. + * + * @param data {string} the data to write to the clipboard + * @param type {string} (Optional) the type of the data. Support text, png, jpeg, html and rtf. By default, type is set to "text". + * @param raw {boolean} (Optional) requiring raw image data. This option is only valid if type is png or jpeg. By default, raw is set to false. + */ + set( data: string, type?: string, raw?: boolean ): void; + + /** + * Get the data of `type` from clipboard. + * + * @param type {string} (Optional) the type of the data. Support text, png, jpeg, html and rtf. By default, type is set to "text". + * @param raw {boolean} (Optional) requiring raw image data. This option is only valid if type is png or jpeg. + * @returns {string} the data retrieved from the clipboard. + */ + get( type?: string, raw?: boolean ): string; + + /** + * Get an array contains list of available types of data in clipboard currenly. + * You can use the returned list as a suggestion to get the right data from clipboard. + * + * @returns {string[]} List of available types of data in clipboard currenly. + */ + readAvailableTypes(): string[]; + + /** + * Clear the clipboard. + */ + clear(): void; + } + + /** + * Object that contains options to use while creation of nw.Menu. example: new nw.Menu(MenuOption) + */ + interface MenuOption { + /** + * {string} (Optional) two types are accepted by this method: "menubar" or "contextmenu". The value is set to "contextmenu" by default. + */ + type: string; + } + + /** + * Options to modify default `edit` and `window` MenuItems in Mac. + */ + interface CreateMacBuiltinOption { + + /** + * {Boolean} (Optional) do not populate the Edit menu + */ + hideEdit?: boolean; + + /** + * {Boolean} (Optional) do not populate the Window menu + */ + hideWindow?: boolean; + } + + /** + * Options for MenuItem. + */ + interface MenuItemOption { + + /** + * {string} (Optional) Label for normal item or checkbox + */ + label?: string; + + /** + * {string} (Optional) Icon for normal item or checkbox + */ + icon?: string; + + /** + * {string} (Optional) Tooltip for normal item or checkbox + */ + tooltip?: string; + + /** + * {string} (Optional) The type of the item. Three types are accepted: normal, checkbox, separator + */ + type?: string | "normal" | "checkbox" | "separator"; + + /** + * {Function} (Optional) The callback function when item is triggered by mouse click or keyboard shortcut + */ + click?: Function; + + /** + * {boolean} (Optional) Whether the item is enabled or disabled. It"s set to true by default. + */ + enabled?: boolean; + + /** + * {boolean} (Optional) Whether the checkbox is checked or not. It"s set to false by default. + */ + checked?: boolean; + + /** + * {nw.Menu} (Optional) A submenu + */ + submenu?: nw.Menu; + + /** + * {string} (Optional) The key of the shortcut + */ + key?: string; + + /** + * {string} (Optional) The modifiers of the shortcut + */ + modifiers?: string; + } + + /** + * nw.Screen screen object + */ + interface screen { + + /** + * Unique id for a screen + */ + id: number, + + /** + * Physical screen resolution, can be negative, not necessarily start from 0,depending on screen arrangement + */ + bounds: { + x: number, + y: number, + width: number, + height: number + }, + + /** + * Useable area within the screen bound + */ + work_area: { + x: number, + y: number, + width: number, + height: number + }, + + scaleFactor: number, + + isBuiltIn: boolean, + + rotation: number, + + touchSupport: number + } + + /** + * This API behaves similar functions as Screen.chooseDesktopMedia. But it doesn"t have GUI. + */ + interface DesktopCaptureMonitor extends EventEmitter { + + /** + * Boolean of whether the DesktopCaptureMonitor is started. + */ + started: boolean; + + /** + * The DesktopCaptureMonitor will start monitoring the system and trigger the the events. + * + * @param should_include_screens {boolean} Whether should include screens + * @param should_include_windows {boolean} Whether should include windows + */ + start( should_include_screens: boolean, should_include_windows: boolean ): void; + + /** + * The DesktopCaptureMonitor will stop monitoring the system. + */ + stop(): void; + + /** + * Register and return a valid stream id passed into chromeMediaSourceId in getUserMedia constraints. + * + * @param id {string} valid stream id. + */ + registerStream( id: string ): void; + + on( event: string, listener: Function ): this; + + /** + * Emit when a new source was added. + * + * @param event {string} Event name + * @param listener {Function(id?,name?,order?,type?,primary?)} The callback that handles the `added` event. + * - (optional) id {string} Is the media id. + * - (optional) name {string} Is the title of the window or screen. + * - (optional) order {number} Is the z-order of the windows, if screens are selected they will appear first. + * - (optional) type {string} Type of the stream: "screen", "window", "other" or "unknown". + * - (optional) primary {boolean} This will be true if the source is the primary monitor. (Windows OS only) + */ + on( event: 'added', listener: ( id?: string, name?: string, order?: number, type?: string, primary?: boolean ) => any ): this; + + /** + * Emit when a source was removed. + * + * @param event {string} Event name + * @param listener {Function(order?)} The callback that handles the `remove` event. + * - (optional) order {number} Is the order of the media source that is no longer capturable. + */ + on( event: 'removed', listener: ( order?: number ) => any ): this; + + /** + * Emit when the Z-order of a source changed (this may change for windows as others are focused). + * + * @param event {string} Event name + * @param listener {Function(id?,new_order?,old_order?)} The callback that handles the `orderchanged` event. + * - (optional) id {string} Is the media id of the screen or window that has changed z-order. + * - (optional) new_order {number} Is the new z-order. + * - (optional) old_order {number} Is the old z-order. + */ + on( event: 'orderchanged', listener: ( id?: string, new_order?: number, old_order?: number ) => any ): this; + + /** + * Emit when the name of the source has changed. This can happen when a window changes title. + * + * @param event {string} Event name + * @param listener {Function(id?,new_order?,old_order?)} The callback that handles the `namechanged ` event. + * - (optional) id {string} Is the media id of the screen or window that has a name changed. + * - (optional) name {string} Is the new name of the screen or window. + */ + on( event: 'namechanged', listener: ( id?: string, name?: string ) => any ): this; + + /** + * Emit when the thumbnail of a source changed. + * + * @param event {string} Event name + * @param listener {Function(id?,new_order?,old_order?)} The callback that handles the `thumbnailchanged ` event. + * - (optional) id {string} Is the media id of the screen or window that has an updated thumbnail. + * - (optional) name {string} Is the base64 encoded png of the thumbnail. + */ + on( event: 'thumbnailchanged', listener: ( id?: string, thumbnail?: string ) => any ): this; + } + + /** + * Shortcut option is an object contains initial settings for the Shortcut. + */ + interface ShortcutOption { + + /** + * {Function} (Optional) A callback when the hotkey is triggered. + */ + active: Function; + + /** + * {Function} (Optional) A callback when failed to register the hotkey. + * + * @param msg {string} Failure message + */ + failed: ( msg?: string ) => any; + + /** + * {string} Key combinations of the shortcut, such as "ctrl+shift+a". + */ + key: string; + } + + /** + * Option for tray that contains initial settings for the Tray. + */ + interface TrayOption { + + /** + * {string} title + */ + title?: string; + + /** + * {string} tooltip + */ + tooltip?: string; + + /** + * {string} icon + */ + icon?: string; + + /** + * {string} alternate + */ + alticon?: string; + + /** + * {boolean} whether icons are templates + */ + iconsAreTemplates?: boolean; + + /** + * {Menu} popup menu + */ + menu?: nw.Menu; + } + + /** + * Options for nw.Window.get().print(). + */ + interface PrintOption { + + /** + * The device name of the printer + */ + printer: string; + + /** + * The path of the output PDF when printing to PDF + */ + pdf_path: string; + + /** + * Whether to enable header and footer + */ + headerFooterEnabled: boolean; + + /** + * Whether to use landscape or portrait + */ + landscape: boolean; + + /** + * The paper size spec + * example: 'mediaSize':{'name': 'CUSTOM', 'width_microns': 279400, 'height_microns': 215900, 'custom_display_name':'Letter', 'is_default': true} + */ + mediaSize: JSON; + + /** + * Whether to print CSS backgrounds + */ + shouldPrintBackgrounds: boolean; + } + + /** + * Config for nw.Window.get().capturePage(). + */ + interface CapturePageConfig { + + /** + * (Optional) The image format used to generate the image. It supports two formats: "png" and "jpeg". If ignored, it’s "jpeg" by default. + */ + format?: string + + /** + * (Optional) It supports three types: "raw", "buffer" and "datauri". If ignored, it’s "datauri" by default. + */ + datatype?: string + } + + /** + * This includes multiple functions to manipulate the cookies. + */ + interface Cookies { + + /** + * Retrieves information about a single cookie. + * + * @param details {Objet} Details to identify the cookie being retrieved. + * @param callback {function(cookie?)} The callback when cookie retrieved. + * - (Optional) cookie {Cookie} Contains details about the cookie. This parameter is null if no such cookie was found. + */ + get( details: CookiesGetDetails, callback: ( cookie?: Cookie ) => void ): void; + + /** + * Retrieves all cookies from a single cookie store that match the given information. + * + * @param details {Objet} Information to filter the cookies being retrieved. + * @param callback {function(cookies?)} The callback when cookies retrieved. + * - (Optional) cookies {Cookie[]} All the existing, unexpired cookies that match the given cookie info. + */ + getAll( details: CookiesGetAllDetails, callback: ( cookies?: Cookie[] ) => void ): void; + + /** + * Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. + * + * @param details {Objet} Details about the cookie being set. + * @param callback {function(cookie?)} The callback when cookie has been set. + * - (Optional) cookie {Cookie} Contains details about the cookie that's been set. If setting failed for any reason, this will be "null", and "chrome.runtime.lastError" will be set. + */ + set( details: CookiesSetDetails, callback: ( cookie?: Cookie ) => void ): void; + + /** + * Deletes a cookie by name. + * + * @param details {Objet} Information to identify the cookie to remove. + * @param callback {function(cookie?)} The callback when cookie has been set. + * - (Optional) details {Objet} Contains details about the cookie that's been removed. If removal failed for any reason, this will be "null", and "chrome.runtime.lastError" will be set. + */ + remove( details: CookiesRemoveDetails, callback: ( details?: CookiesRemovedDetails ) => void ): void; + + /** + * Fired when a cookie is set or removed. + */ + onChanged: { + /** + * Add a new listener for onChanged event. + * + * @param callback {function(changeInfo?)} The callback when cookie has been changed. + * - (Optional) changeInfo {Objet} Contains details about the cookie that's been changed. + */ + addListener( callback: ( changeInfo: CookiesOnChangedCallbackChangeInfo ) => void ): void; + } + } + + /** + * Represents information about an HTTP cookie. + */ + interface Cookie { + + /** + * The name of the cookie. + */ + name: string; + + /** + * The value of the cookie. + */ + value: string; + + /** + * The domain of the cookie (e.g. "www.google.com", "example.com"). + */ + domain: string; + + /** + * True if the cookie is a host-only cookie (i.e. a request's host must exactly match the domain of the cookie). + */ + hostOnly: boolean; + + /** + * The path of the cookie. + */ + path: string; + + /** + * True if the cookie is marked as Secure (i.e. its scope is limited to secure channels, typically HTTPS). + */ + secure: boolean; + + /** + * True if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts). + */ + httpOnly: boolean; + + /** + * The cookie's same-site status (i.e. whether the cookie is sent with cross-site requests). + */ + sameSite: string | "no_restriction" | "lax" | "strict"; + + /** + * True if the cookie is a session cookie, as opposed to a persistent cookie with an expiration date. + */ + session: boolean; + + /** + * (Optional) The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies. + */ + expirationDate?: number; + + /** + * The ID of the cookie store containing this cookie. + */ + storeId: string; + } + + /** + * Coockies.get() details argument object + */ + interface CookiesGetDetails { + + /** + * The URL with which the cookie to retrieve is associated. + */ + url: string; + + /** + * The name of the cookie to retrieve. + */ + name: string; + + /** + * The ID of the cookie store in which to look for the cookie. + */ + storeId: string; + } + + /** + * Coockies.getAll() details argument object + */ + interface CookiesGetAllDetails { + + /** + * Restricts the retrieved cookies to those that would match the given URL. + */ + url?: string; + + /** + * Filters the cookies by name. + */ + name?: string; + + /** + * Restricts the retrieved cookies to those whose domains match or are subdomains of this one. + */ + domain?: string; + + /** + * Restricts the retrieved cookies to those whose path exactly matches this string. + */ + path?: string; + + /** + * Filters the cookies by their Secure property. + */ + secure?: boolean; + + /** + * Filters out session vs. persistent cookies. + */ + session: boolean; + + /** + * The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used. + */ + storeId?: string; + } + + /** + * Coockies.set() details argument object + */ + interface CookiesSetDetails { + + /** + * The request-URI to associate with the setting of the cookie. + */ + url: string; + + /** + * The name of the cookie. Empty by default if omitted. + */ + name?: string; + + /** + * The value of the cookie. Empty by default if omitted. + */ + value?: string; + + /** + * The domain of the cookie. If omitted, the cookie becomes a host-only cookie. + */ + domain?: string; + + /** + * The path of the cookie. Defaults to the path portion of the url parameter. + */ + path?: string; + + /** + * Whether the cookie should be marked as Secure. Defaults to false. + */ + secure?: boolean; + + /** + * Whether the cookie should be marked as HttpOnly. Defaults to false. + */ + httpOnly?: boolean; + + /** + * The cookie's same-site status: defaults to 'no_restriction'. + */ + sameSite?: string | "no_restriction" | "lax" | "strict"; + + /** + * The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie. + */ + expirationDate?: number; + + /** + * The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current execution context's cookie store. + */ + storeId?: string; + } + + /** + * Coockies.remove() details argument object + */ + interface CookiesRemoveDetails { + + /** + * The URL associated with the cookie. + */ + url: string; + + /** + * The name of the cookie to remove. + */ + name: string; + + /** + * The ID of the cookie store to look in for the cookie. + */ + storeId: string; + } + + /** + * Coockies.remove() callback details argument object + */ + interface CookiesRemovedDetails { + + /** + * The URL associated with the cookie that's been removed. + */ + url: string; + + /** + * The name of the cookie that's been removed. + */ + name: string; + + /** + * The ID of the cookie store from which the cookie was removed. + */ + storeId: string; + } + + /** + * Coockies.onChanged.addListener() callback details argument object + */ + interface CookiesOnChangedCallbackChangeInfo { + + /** + * True if a cookie was removed. + */ + removed: boolean; + + /** + * Information about the cookie that was set or removed. + */ + cookie: Cookie; + + /** + * The underlying reason behind the cookie's change. + */ + cause: string | "evicted" | "expired" | "explicit" | "expired_overwrite" | "overwrite" + } + + /** + * nw.Window.get().on('new-win-policy') callback policy argument object + */ + interface WinPolicy { + + /** + * Ignore the request, navigation won’t happen. + */ + ignore(): void; + + /** + * Force the link to be opened in the same frame + */ + forceCurrent(): void; + + /** + * Force the link to be a downloadable, or open by external program + */ + forceDownload(): void; + + /** + * Force the link to be opened in a new window + */ + forceNewWindow(): void; + + /** + * Force the link to be opened in a new popup window + */ + forceNewPopup(): void; + + /** + * Control the options for the new popup window. + * + *@param m {Object} The object is in the same format as the Window subfields in manifest format. + */ + setNewWindowManifest( m: WindowOption ): void; + } + + /** + * nw.Window Option that is in the same format as the Window subfields in manifest format. + */ + interface WindowOption { + + /** + * The id used to identify the window. + */ + id?: string; + + /** + * The default title of window created by NW.js + */ + title?: string; + + /** + * The initial width of the main window. + */ + width?: number; + + /** + * The initial height of the main window. + */ + height?: number; + + /** + * Path to window’s icon + */ + icon?: string; + + /** + * Controls where window will be put, be `null` or `center` or `mouse` + */ + position?: string; + + /** + * Minimum width of window + */ + min_width?: number; + + /** + * Minimum height of window + */ + min_height?: number; + + /** + * Maximum width of window + */ + max_width?: number; + + /** + * Maximum height of window + */ + max_height?: number; + + /** + * Show as desktop background window under X11 environment + */ + as_desktop?: boolean; + + /** + * Whether window is resizable + */ + resizable?: boolean; + + /** + * Whether the window should always stay on top of other windows. + */ + always_on_top?: boolean; + + /** + * Whether the window should be visible on all workspaces simultaneously (on platforms that support multiple workspaces, currently Mac OS X and Linux). + */ + visible_on_all_workspaces?: boolean; + + /** + * Whether window is fullscreen + */ + fullscreen?: boolean; + + /** + * Whether the window is shown in taskbar or dock. The default is true. + */ + show_in_taskbar?: boolean; + + /** + * Specify it to false to make the window frameless + */ + frame?: boolean; + + /** + * Specify it to false if you want your app to be hidden on startup + */ + show?: boolean; + + /** + * Whether to use Kiosk mode. + */ + kiosk?: boolean; + + /** + * Whether to turn on transparent window mode. + */ + transparent?: boolean; + } + + interface WindowOpenOption extends WindowOption { + + /** + * (Optional) Whether to open a new window in a separate render process. + */ + new_instance?: boolean; + + /** + * (Optional) The script to be injected before document loaded. + */ + inject_js_start?: string; + + /** + * (Optional) The script to be injected before document unloaded. + */ + inject_js_end?: string; + + /** + * (Optional) The id used to identify the window. + */ + id?: string; + } + + /** + * nw.Window.get().on('navigation') callback policy argument object + */ + interface WinNavigationPolicy { + + /** + * Ignore the request, navigation won’t happen. + */ + ignore(): void; + } + + interface win extends EventEmitter { + + /** + * Get the corresponding DOM window object of the native window. + */ + window: Object; + + /** + * Get or set left offset from window to screen. + */ + x: number; + + /** + * Get or set top offset from window to screen. + */ + y: number; + + /** + * Get or set window's width. + */ + width: number; + + /** + * Get or set window's height. + */ + height: number; + + /** + * Get or set window's title. + */ + title: string; + + /** + * Get or set window's menubar. + */ + menu: nw.Menu; + + /** + * Get whether we're in fullscreen mode. + */ + isFullscreen: boolean; + + /** + * Get whether transparency is turned on + */ + isTransparent: boolean; + + /** + * Get whether we're in kiosk mode. + */ + isKioskMode: boolean; + + /** + * Get or set the page zoom. + */ + zoomLevel: number; + + /** + * This includes multiple functions to manipulate the cookies. + */ + cookies: Cookies; + + /** + * Moves a window's left and top edge to the specified coordinates. + * + * @param x {Integer} Offset to the left of the screen + * @param y {Integer} Offset to the top of the screen + */ + moveTo( x: number, y: number ): void; + + /** + * Moves a window a specified number of pixels relative to its current coordinates. + * + * @param x {Integer} Horizontal offset + * @param y {Integer} Vertical offset + */ + moveBy( x: number, y: number ): void; + + /** + * Resizes a window to the specified width and height. + * + * @param width {Integer} The width of the window + * @param height {Integer} The height of the window + */ + resizeTo( width: number, height: number ): void; + + /** + * Resizes a window by the specified amount. + * + * @param width {Integer} The offset width of the window + * @param height {Integer} The offset height of the window + */ + resizeBy( width: number, height: number ): void; + + /** + * Focus on the window. + */ + focus(): void; + + /** + * Move focus away. + */ + blur(): void; + + /** + * Show the window if it's not shown. + * + * @param is_show {boolean} (Optional) Specify whether the window should be shown or hidden. It's set to true by default. + */ + show( is_show?: boolean ): void; + + /** + * Hide the window. + */ + hide(): void; + + /** + * Close current window. + * + * @param force {boolean} (Optional) Specify whether to close the window forcely and bypass close event. + */ + close( force?: boolean ): void; + + /** + * Reloads the current window. + */ + reload(): void; + + /** + * Reloads the current page by starting a new renderer process from scratch. + */ + reloadDev(): void; + + /** + * Like reload(), but don't use caches (aka 'shift-reload'). + */ + reloadIgnoringCache(): void; + + /** + * Maximize the window on GTK and Windows, and zoom the window on Mac OS X. + */ + maximize(): void; + + /** + * Minimize the window to task bar on Windows, iconify the window on GTK, and miniaturize the window on Mac OS X. + */ + minimize(): void; + + /** + * Restore window to previous state after the window is minimized. + */ + restore(): void; + + /** + * Make the window fullscreen. + */ + enterFullscreen(): void; + + /** + * Leave the fullscreen mode. + */ + leaveFullscreen(): void; + + /** + * Toggle the fullscreen mode. + */ + toggleFullscreen(): void; + + /** + * Enter the Kiosk mode. + */ + enterKioskMode(): void; + + /** + * Leave the Kiosk mode. + */ + leaveKioskMode(): void; + + /** + * Toggle the kiosk mode. + */ + toggleKioskMode(): void; + + /** + * Open the devtools to inspect the window. + * + * @param iframe {Integer} (Optional) the id or the element of the