Merge remote-tracking branch 'upstream/master' into intl-tel-input

This commit is contained in:
Fidan HAKAJ
2016-06-24 00:56:07 +02:00
230 changed files with 28046 additions and 18578 deletions
+2 -2
View File
@@ -24,7 +24,7 @@ Please see the [contribution guide](http://definitelytyped.org/guides/contributi
* Directly from the GitHub repos
* [NuGet packages](http://nuget.org/packages?q=DefinitelyTyped)
* [TypeScript Definition manager](https://github.com/DefinitelyTyped/tsd)
* [Typings - TypeScript Definition Manager](https://github.com/typings/typings)
## List of definitions
@@ -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
+8
View File
@@ -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;
+14 -1
View File
@@ -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;
+1
View File
@@ -95,6 +95,7 @@ declare namespace angular.material {
onComplete?: Function;
onRemoving?: Function;
fullscreen?: boolean;
skipHide?: boolean;
}
interface IDialogService {
+1 -1
View File
@@ -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;
+2 -2
View File
@@ -43,7 +43,7 @@ declare namespace angular.animate {
* @param container the container element that will capture each of the animation events that are fired on itself as well as among its children
* @param callback the callback function that will be fired when the listener is triggered
*/
on(event: string, container: JQuery, callback: Function): void;
on(event: string, container: JQuery, callback: (element?: JQuery, phase?: string) => any): void;
/**
* Deregisters an event listener based on the event which has been associated with the provided element.
@@ -52,7 +52,7 @@ declare namespace angular.animate {
* @param container the container element the event listener was placed on
* @param callback the callback function that was registered as the listener
*/
off(event: string, container?: JQuery, callback?: Function): void;
off(event: string, container?: JQuery, callback?: (element?: JQuery, phase?: string) => any): void;
/**
* Associates the provided element with a host parent element to allow the element to be animated even if it exists outside of the DOM structure of the Angular application.
+1 -1
View File
@@ -869,7 +869,7 @@ angular.module('docsTabsExample', [])
angular.module('componentExample', [])
.component('counter', {
require: ['^ctrl'],
require: {'ctrl': '^ctrl'},
bindings: {
count: '='
},
+2 -2
View File
@@ -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 {
@@ -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 = "<new key>";
// TelementryContext
var context = appInsights.context;
var context: Microsoft.ApplicationInsights.ITelemetryContext = appInsights.context;
context.application.ver = "v0.0.0";
context.application.build = "1.1.1";
@@ -93,4 +112,46 @@ var envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data,
context.track(envelope);
context.addTelemetryInitializer((envelope) => false);
context.addTelemetryInitializer((envelope) => false);
// track event
var eventObj = new Microsoft.ApplicationInsights.Telemetry.Event("test", null, null);
var eventData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Event>(Microsoft.ApplicationInsights.Telemetry.Event.dataType, eventObj);
var eventEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(eventData, Microsoft.ApplicationInsights.Telemetry.Event.envelopeType);
context.track(eventEnvelope);
// track exception
var exceptionObj = new Microsoft.ApplicationInsights.Telemetry.Exception(new Error(), "handledAt", null, null, AI.SeverityLevel.Critical);
var exceptionData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Exception>(Microsoft.ApplicationInsights.Telemetry.Exception.dataType, exceptionObj);
var exceptionEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(exceptionData, Microsoft.ApplicationInsights.Telemetry.Exception.envelopeType);
context.track(exceptionEnvelope);
// track metric
var metricObj = new Microsoft.ApplicationInsights.Telemetry.Metric("name", 1234, 1, 0, 100, null);
var metricData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Metric>(Microsoft.ApplicationInsights.Telemetry.Metric.dataType, metricObj);
var metricEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(metricData, Microsoft.ApplicationInsights.Telemetry.Metric.envelopeType);
context.track(metricEnvelope);
// track page view
var pageViewObj = new Microsoft.ApplicationInsights.Telemetry.PageView("page name", "url", 999, null, null);
var pageViewData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.PageView>(Microsoft.ApplicationInsights.Telemetry.PageView.dataType, pageViewObj);
var pageViewEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewData, Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType);
context.track(pageViewEnvelope);
// track page view performance
var pageViewPerfObj = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("page name", "url", 999, null, null);
var pageViewPerfData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.PageViewPerformance>(Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.dataType, pageViewPerfObj);
var pageViewPerfEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewPerfData, Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.envelopeType);
context.track(pageViewPerfEnvelope);
// track remote dependency
var remoteDepObj = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData("id", "url", "command", 1, true, 1234, "GET");
var remoteDepData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData>(Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.dataType, remoteDepObj);
var remoteDepEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(remoteDepData, Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.envelopeType);
context.track(pageViewPerfEnvelope);
// track trace
var traceObj = new Microsoft.ApplicationInsights.Telemetry.Trace("message", null);
var traceData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Trace>(Microsoft.ApplicationInsights.Telemetry.Trace.dataType, traceObj);
var traceEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(traceData, Microsoft.ApplicationInsights.Telemetry.Trace.envelopeType);
context.track(traceEnvelope);
File diff suppressed because it is too large Load Diff
+5
View File
@@ -797,3 +797,8 @@ declare module "avoscloud-sdk" {
export = AV;
}
declare module 'leanengine' {
import alias = require('avoscloud-sdk');
export = alias;
}
+109 -2
View File
@@ -18,6 +18,10 @@ declare module "aws-sdk" {
accessKeyId: string;
}
export class EnvironmentCredentials extends Credentials {
constructor(profile: string);
}
export interface Logger {
write?: (chunk: any, encoding?: string, callback?: () => void) => void;
log?: (...messages: any[]) => void;
@@ -86,6 +90,8 @@ declare module "aws-sdk" {
export interface ClientConfigPartial extends Services {
credentials?: Credentials;
region?: string;
accessKeyId: string;
secretAccessKey: string;
computeChecksums?: boolean;
convertResponseTypes?: boolean;
logger?: Logger;
@@ -138,9 +144,9 @@ declare module "aws-sdk" {
export class SNS {
constructor(options?: any);
public client: Sns.Client;
publish(request: Sns.PublishRequest, callback: (err: any, data: any) => void): void;
}
export class SimpleWorkflow {
constructor(options?: any);
public client: Swf.Client;
@@ -152,6 +158,51 @@ declare module "aws-sdk" {
getObject(params: s3.GetObjectRequest, callback: (err: any, data: any) => void): void;
}
export class STS{
constructor(options?: any);
/**
* Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that you can use to access AWS resources that you might not normally have access to.
*/
assumeRole(params: sts.AssumeRoleParams, callback: (err: any, data: any) => void): void;
/**
* Returns a set of temporary security credentials for users who have been authenticated via a SAML authentication response.
*/
assumeRoleWithSAML(params: sts.AssumeRoleWithSAMLParams, callback: (err: any, data: any) => void): void;
/**
* Returns a set of temporary security credentials for users who have been authenticated in a mobile or web application with a web identity provider, such as Amazon Cognito, Login with Amazon, Facebook, Google, or any OpenID Connect-compatible identity provider.
*/
assumeRoleWithWebIdentity(params: sts.AssumeRoleWithWebIdentityParams, callback: (err: any, data: any) => void): void;
/**
* Creates a credentials object from STS response data containing credentials information.
*/
credentialsFrom(params: sts.CredentialsFromParams, callback: (err: any, data: any) => void): void;
/**
* Decodes additional information about the authorization status of a request from an encoded message returned in response to an AWS request.
*/
decodeAuthorizationMessage(params: sts.DecodeAuthorizationMessageParams, callback: (err: any, data: any) => void): void;
/**
* Returns details about the IAM identity whose credentials are used to call the API.
*/
getCallerIdentity(params: {}, callback: (err: any, data: any) => void): void;
/**
* Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) for a federated user.
*/
getFederationToken(params: sts.GetFederationTokenParams, callback: (err: any, data: any) => void): void;
/**
* Returns a set of temporary credentials for an AWS account or IAM user.
*/
getSessionToken(params: sts.GetSessionTokenParams, callback: (err: any, data: any) => void): void;
}
export class ECS {
constructor(options?: any);
/**
@@ -1345,4 +1396,60 @@ declare module "aws-sdk" {
taskDefinition: string;
}
}
export module sts {
export interface AssumeRoleParams {
RoleArn: string;
RoleSessionName: string;
DurationSeconds?: number;
ExternalId?: string;
Policy?: string;
SerialNumber?: string;
TokenCode?: string;
}
export interface AssumeRoleWithSAMLParams {
PrincipalArn: string;
RoleArn: string;
SAMLAssertion: string;
DurationSeconds?: number;
Policy?: string;
}
export interface AssumeRoleWithWebIdentityParams {
RoleArn: string;
RoleSessionName: string;
WebIdentityToken: string;
DurationSeconds?: number;
Policy?: string;
ProviderId?: string;
}
export interface CredentialsFromParams {
/**
* Data retrieved from a call to AWS.STS.getFederatedToken, getSessionToken(), assumeRole(), or assumeRoleWithWebIdentity().
*/
Data: any;
/**
* An optional credentials object to fill instead of creating a new object. Useful when modifying an existing credentials object from a refresh call.
*/
Credentials?: Credentials
}
export interface DecodeAuthorizationMessageParams {
EncodedMessage: string;
}
export interface GetFederationTokenParams {
Name: string;
DurationSeconds?: number,
Policy?: string
}
export interface GetSessionTokenParams {
DurationSeconds: number,
SerialNumber: string;
TokenCode: string;
}
}
}
+37 -3
View File
@@ -7,10 +7,11 @@ declare namespace Microsoft.WindowsAzure {
// MobileServiceClient object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554219.aspx
interface MobileServiceClient {
new (applicationUrl: string, applicationKey: string): MobileServiceClient;
new (applicationUrl: string, applicationKey?: string): MobileServiceClient;
applicationUrl: string;
applicationKey: string;
currentUser: User;
push: Push;
//for provider:string use one of ProviderEnum: 'microsoftaccount', 'facebook', 'twitter', 'google'
login(provider: string, token: string, callback: (error: any, user: User) => void ): void;
login(provider: string, token: string): asyncPromise;
@@ -18,8 +19,40 @@ declare namespace Microsoft.WindowsAzure {
login(provider: string): asyncPromise;
logout(): void;
getTable(tableName: string): MobileServiceTable;
withFilter(serviceFilter: (request: any, next: (request: any, callback: (error:any, response: any) => void ) => void, callback: (error: any, response: any) => void ) => void ) : MobileServiceClient;
invokeApi(apiName: string, options?:InvokeApiOptions): asyncPromise;
withFilter(serviceFilter: (request: any, next: (request: any, callback: (error: any, response: any) => void) => void, callback: (error: any, response: any) => void) => void): MobileServiceClient;
/**
* Invokes the specified custom api and returns a response object.
*
* @param apiName The custom api to invoke.
* @param options Contains additional parameter information, valid values are:
* body: The body of the HTTP request.
* method: The HTTP method to use in the request, with the default being POST,
* parameters: Any additional query string parameters,
* headers: HTTP request headers, specified as an object.
* @param callback Optional callback accepting (error, results) parameters.
*/
invokeApi(apiName: string, options?: InvokeApiOptions, callback?: (error: any, results: any) => void): asyncPromise;
}
interface Push
{
/**
* Register a push channel with the Mobile Apps backend to start receiving notifications.
*
* @param platform The device platform being used - wns, gcm or apns.
* @param pushChannel The push channel identifier or URI.
* @param templates An object containing template definitions. Template objects should contain body, headers and tags properties.
* @param secondaryTiles An object containing template definitions to be used with secondary tiles when using WNS.
* @param callback Optional callback accepting (error, results) parameters.
*/
register(platform: string, pushChannel: string, templates?: any, secondaryTiles?: any, callback?: (error: any, results: any) => void): void;
/**
* Invokes the specified custom api and returns a response object.
*
* @param pushChannel The push channel identifier or URI.
* @param callback Optional callback accepting (error, results) parameters.
*/
unregister(pushChannel: string, callback?: (error: any, results: any) => void): void;
}
interface InvokeApiOptions
@@ -36,6 +69,7 @@ declare namespace Microsoft.WindowsAzure {
accessTokens: any; // { [providerName: string]: string; }
level: string; //for level:string use one of LevelEnum: 'admin','anonymous','authenticated'
userId: string;
mobileServiceAuthenticationToken: string;
}
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="babelify.d.ts" />
import babelify = require("babelify");
module BabelifyTest {
export function whatDidTheEs6Say(srcPath: string, opts?: babelify.BabelifyOptions) {
opts.extensions = opts.extensions || undefined;
opts.sourceMapsAbsolute = opts.sourceMapsAbsolute || false;
var dst: NodeJS.ReadWriteStream;
babelify(""); // 'opts' are optional
babelify(srcPath, opts).on("error", function (err: any) {
console.error("babelify error: ", err);
});
babelify.configure(opts)(srcPath).pipe(dst);
}
}
export = BabelifyTest;
+46
View File
@@ -0,0 +1,46 @@
// Type definitions for babelify v7.3.0
// Project: https://github.com/babel/babelify
// Definitions by: TeamworkGuy2 <https://github.com/TeamworkGuy2>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../babel-core/babel-core.d.ts" />
/** Browserify transform for Babel
*/
declare module 'babelify' {
import stream = require("stream");
import babel = require("babel-core");
function Babelify(filename: string, opts?: Babelify.BabelifyOptions): Babelify.BabelifyObject;
module Babelify {
export interface BabelifyConstructor {
(filename: string, opts: Babelify.BabelifyOptions): Babelify.BabelifyObject;
}
/** In addition to the various purposes documented here, all of the babelify options are passed to babel which passes them on to babel.transform() when each file is transformed */
export interface BabelifyOptions extends babel.TransformOptions {
/** These are passed to babel.util.canCompile() for each filename
* default: null
*/
extensions?: string | string[];
/** if true, a 'sourceFileName' property with a value equal to the current file being transformed is included with the options passed to babel.transform()
* default: false
*/
sourceMapsAbsolute?: boolean;
}
export class BabelifyObject extends stream.Transform {
_transform(buf: string | Buffer, encoding: string, callback: () => void): void;
_flush(callback: () => void): void;
}
export function configure(opts: Babelify.BabelifyOptions): (filename: string) => Babelify.BabelifyObject;
}
export = Babelify;
}
+60 -44
View File
@@ -147,7 +147,6 @@ declare namespace Backbone {
/*private*/ set(attributeName: string, value: any, options?: ModelSetOptions): Model;
set(obj: any, options?: ModelSetOptions): Model;
change(): any;
changedAttributes(attributes?: any): any[];
clear(options?: Silenceable): any;
clone(): Model;
@@ -173,8 +172,12 @@ declare namespace Backbone {
invert(): any;
pick(keys: string[]): any;
pick(...keys: string[]): any;
pick(fn: (value: any, key: any, object: any) => any): any;
omit(keys: string[]): any;
omit(...keys: string[]): any;
omit(fn: (value: any, key: any, object: any) => any): any;
chain(): any;
isEmpty(): boolean;
}
class Collection<TModel extends Model> extends ModelBase {
@@ -223,58 +226,72 @@ declare namespace Backbone {
private _removeReference(model: TModel): void;
private _onModelEvent(event: string, model: TModel, collection: Collection<TModel>, options: any): void;
/**
* Return a shallow copy of this collection's models, using the same options as native Array#slice.
*/
slice(min: number, max?: number): TModel[];
// mixins from underscore
all(iterator: (element: TModel, index: number) => boolean, context?: any): boolean;
any(iterator: (element: TModel, index: number) => boolean, context?: any): boolean;
collect(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[];
all(iterator?: _.ListIterator<TModel, boolean>, context?: any): boolean;
any(iterator?: _.ListIterator<TModel, boolean>, context?: any): boolean;
chain(): any;
contains(value: any): boolean;
countBy(iterator: (element: TModel, index: number) => any): _.Dictionary<number>;
countBy(attribute: string): _.Dictionary<number>;
detect(iterator: (item: any) => boolean, context?: any): any; // ???
drop(): TModel;
drop(n: number): TModel[];
each(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any;
every(iterator: (element: TModel, index: number) => boolean, context?: any): boolean;
filter(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[];
find(iterator: (element: TModel, index: number) => boolean, context?: any): TModel;
collect<TResult>(iterator: _.ListIterator<TModel, TResult>, context?: any): TResult[];
contains(value: TModel): boolean;
countBy(iterator?: _.ListIterator<TModel, any>): _.Dictionary<number>;
countBy(iterator: string): _.Dictionary<number>;
detect(iterator: _.ListIterator<TModel, boolean>, context?: any): TModel;
difference(others: TModel[]): TModel[];
drop(n?: number): TModel[];
each(iterator: _.ListIterator<TModel, void>, context?: any): TModel[];
every(iterator: _.ListIterator<TModel, boolean>, context?: any): boolean;
filter(iterator: _.ListIterator<TModel, boolean>, context?: any): TModel[];
find(iterator: _.ListIterator<TModel, boolean>, context?: any): TModel;
findIndex(predicate: _.ListIterator<TModel, boolean>, context?: any): number;
findLastIndex(predicate: _.ListIterator<TModel, boolean>, context?: any): number;
first(): TModel;
first(n: number): TModel[];
foldl(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any;
forEach(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any;
groupBy(iterator: (element: TModel, index: number) => string, context?: any): _.Dictionary<TModel[]>;
groupBy(attribute: string, context?: any): _.Dictionary<TModel[]>;
include(value: any): boolean;
indexOf(element: TModel, isSorted?: boolean): number;
foldl<TResult>(iterator: _.MemoIterator<TModel, TResult>, memo?: TResult, context?: any): TResult;
foldr<TResult>(iterator: _.MemoIterator<TModel, TResult>, memo?: TResult, context?: any): TResult;
forEach(iterator: _.ListIterator<TModel, void>, context?: any): TModel[];
groupBy(iterator: _.ListIterator<TModel, any>, context?: any): _.Dictionary<TModel[]>;
groupBy(iterator: string, context?: any): _.Dictionary<TModel[]>;
head(): TModel;
head(n: number): TModel[];
include(value: TModel): boolean;
includes(value: TModel): boolean;
indexBy(iterator: _.ListIterator<TModel, any>, context?: any): _.Dictionary<TModel>;
indexBy(iterator: string, context?: any): _.Dictionary<TModel>;
indexOf(value: TModel, isSorted?: boolean): number;
initial(): TModel;
initial(n: number): TModel[];
inject(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any;
isEmpty(object: any): boolean;
invoke(methodName: string, args?: any[]): any;
inject<TResult>(iterator: _.MemoIterator<TModel, TResult>, memo?: TResult, context?: any): TResult;
invoke(methodName: string, ...args: any[]): any;
isEmpty(): boolean;
last(): TModel;
last(n: number): TModel[];
lastIndexOf(element: TModel, fromIndex?: number): number;
map(iterator: (element: TModel, index: number, context?: any) => any, context?: any): any[];
max(iterator?: (element: TModel, index: number) => any, context?: any): TModel;
min(iterator?: (element: TModel, index: number) => any, context?: any): TModel;
reduce(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any;
select(iterator: any, context?: any): any[];
lastIndexOf(value: TModel, from?: number): number;
map<TResult>(iterator: _.ListIterator<TModel, TResult>, context?: any): TResult[];
max(iterator?: _.ListIterator<TModel, any>, context?: any): TModel;
min(iterator?: _.ListIterator<TModel, any>, context?: any): TModel;
partition(iterator: _.ListIterator<TModel, boolean>): TModel[][];
reduce<TResult>(iterator: _.MemoIterator<TModel, TResult>, memo?: TResult, context?: any): TResult;
reduceRight<TResult>(iterator: _.MemoIterator<TModel, TResult>, memo?: TResult, context?: any): TResult;
reject(iterator: _.ListIterator<TModel, boolean>, context?: any): TModel[];
rest(n?: number): TModel[];
sample(): TModel;
sample(n: number): TModel[];
select(iterator: _.ListIterator<TModel, boolean>, context?: any): TModel[];
shuffle(): TModel[];
size(): number;
shuffle(): any[];
slice(min: number, max?: number): TModel[];
some(iterator: (element: TModel, index: number) => boolean, context?: any): boolean;
sortBy(iterator: (element: TModel, index: number) => number, context?: any): TModel[];
sortBy(attribute: string, context?: any): TModel[];
sortedIndex(element: TModel, iterator?: (element: TModel, index: number) => number): number;
reduceRight(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any[];
reject(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[];
rest(): TModel;
rest(n: number): TModel[];
tail(): TModel;
tail(n: number): TModel[];
toArray(): any[];
without(...values: any[]): TModel[];
some(iterator?: _.ListIterator<TModel, boolean>, context?: any): boolean;
sortBy<TSort>(iterator?: _.ListIterator<TModel, TSort>, context?: any): TModel[];
sortBy(iterator: string, context?: any): TModel[];
tail(n?: number): TModel[];
take(): TModel;
take(n: number): TModel[];
toArray(): TModel[];
without(...values: TModel[]): TModel[];
}
class Router extends Events {
@@ -370,7 +387,6 @@ declare namespace Backbone {
$(selector: any): JQuery;
render(): View<TModel>;
remove(): View<TModel>;
make(tagName: any, attributes?: any, content?: any): any;
delegateEvents(events?: EventsHash): any;
delegate(eventName: string, selector: string, listener: Function): View<TModel>;
undelegateEvents(): any;
+91
View File
@@ -90,6 +90,25 @@ function test_models() {
note.set({ title: "March 20", content: "In his eyes she eclipses..." });
note.set("title", "A Scandal in Bohemia");
let strings: string[]
let value: any;
let values: any[];
let bool: boolean;
// underscore methods
strings = note.keys();
values = note.values();
values = note.pairs();
values = note.invert();
value = note.pick("foo");
value = note.pick("foo", "bar");
value = note.pick((value: any, key: any, object: any) => true);
value = note.omit("foo");
value = note.omit("foo", "bar");
value = note.omit((value: any, key: any, object: any) => true);
value = note.chain().pick().omit().value();
bool = note.isEmpty();
}
class Employee extends Backbone.Model {
@@ -161,6 +180,78 @@ function test_collection() {
book.get("published") === true);
var alphabetical = books.sortBy((book: Book): number => null);
let one: Book;
let models: Book[];
let bool: boolean;
let numDict: _.Dictionary<number>;
let modelDict: _.Dictionary<Book>;
let modelsDict: _.Dictionary<Book[]>;
let num: number;
models = books.slice(1);
models = books.slice(1, 3);
// underscore methods
bool = books.all((value: Book, index: number, list: Book[]) => true);
bool = books.any((value: Book, index: number, list: Book[]) => true);
bool = books.chain().any((value: Book, index: number, list: Book[]) => true).value();
models = books.collect((value: Book, index: number, list: Book[]) => value);
bool = books.contains(book1);
numDict = books.countBy((value: Book, index: number, list: Book[]) => true);
numDict = books.countBy("foo");
one = books.detect((value: Book, index: number, list: Book[]) => true);
models = books.difference([book1]);
models = books.drop();
models = books.each((value: Book, index: number, list: Book[]) => true);
bool = books.every((value: Book, index: number, list: Book[]) => true);
models = books.filter((value: Book, index: number, list: Book[]) => true);
one = books.find((value: Book, index: number, list: Book[]) => true);
num = books.findIndex((value: Book, index: number, list: Book[]) => true);
num = books.findLastIndex((value: Book, index: number, list: Book[]) => true);
one = books.first();
models = books.first(3);
models = books.foldl((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.foldr((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.forEach((value: Book, index: number, list: Book[]) => true);
modelsDict = books.groupBy((value: Book, index: number, list: Book[]) => true);
modelsDict = books.groupBy("foo");
one = books.head();
models = books.head(3);
bool = books.include(book1);
bool = books.includes(book1);
modelDict = books.indexBy((value: Book, index: number, list: Book[]) => true);
modelDict = books.indexBy("foo");
num = books.indexOf(book1, true);
one = books.initial();
models = books.initial(3);
models = books.inject((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
one = books.invoke("at", 3);
bool = books.isEmpty();
one = books.last();
models = books.last(3);
num = books.lastIndexOf(book1, 3);
models = books.map((value: Book, index: number, list: Book[]) => value);
one = books.max((value: Book, index: number, list: Book[]) => value);
one = books.min((value: Book, index: number, list: Book[]) => value);
[models] = books.partition((value: Book, index: number, list: Book[]) => true);
models = books.reduce((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.reduceRight((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.reject((value: Book, index: number, list: Book[]) => true);
models = books.rest(3);
one = books.sample();
models = books.sample(3);
models = books.select((value: Book, index: number, list: Book[]) => true);
models = books.shuffle();
num = books.size();
bool = books.some((value: Book, index: number, list: Book[]) => true);
models = books.sortBy((value: Book, index: number, list: Book[]) => value);
models = books.sortBy("foo");
models = books.tail(3);
one = books.take();
models = books.take(3);
models = books.toArray();
models = books.without(book1, book1);
}
//////////
+91
View File
@@ -91,6 +91,25 @@ function test_models() {
note.set({ title: "March 20", content: "In his eyes she eclipses..." });
note.set("title", "A Scandal in Bohemia");
let strings: string[]
let value: any;
let values: any[];
let bool: boolean;
// underscore methods
strings = note.keys();
values = note.values();
values = note.pairs();
values = note.invert();
value = note.pick("foo");
value = note.pick("foo", "bar");
value = note.pick((value: any, key: any, object: any) => true);
value = note.omit("foo");
value = note.omit("foo", "bar");
value = note.omit((value: any, key: any, object: any) => true);
value = note.chain().pick().omit().value();
bool = note.isEmpty();
}
class Employee extends Backbone.Model {
@@ -152,6 +171,78 @@ function test_collection() {
book.get("published") === true);
var alphabetical = books.sortBy((book: Book): number => null);
let one: Book;
let models: Book[];
let bool: boolean;
let numDict: _.Dictionary<number>;
let modelDict: _.Dictionary<Book>;
let modelsDict: _.Dictionary<Book[]>;
let num: number;
models = books.slice(1);
models = books.slice(1, 3);
// underscore methods
bool = books.all((value: Book, index: number, list: Book[]) => true);
bool = books.any((value: Book, index: number, list: Book[]) => true);
bool = books.chain().any((value: Book, index: number, list: Book[]) => true).value();
models = books.collect((value: Book, index: number, list: Book[]) => value);
bool = books.contains(book1);
numDict = books.countBy((value: Book, index: number, list: Book[]) => true);
numDict = books.countBy("foo");
one = books.detect((value: Book, index: number, list: Book[]) => true);
models = books.difference([book1]);
models = books.drop();
models = books.each((value: Book, index: number, list: Book[]) => true);
bool = books.every((value: Book, index: number, list: Book[]) => true);
models = books.filter((value: Book, index: number, list: Book[]) => true);
one = books.find((value: Book, index: number, list: Book[]) => true);
num = books.findIndex((value: Book, index: number, list: Book[]) => true);
num = books.findLastIndex((value: Book, index: number, list: Book[]) => true);
one = books.first();
models = books.first(3);
models = books.foldl((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.foldr((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.forEach((value: Book, index: number, list: Book[]) => true);
modelsDict = books.groupBy((value: Book, index: number, list: Book[]) => true);
modelsDict = books.groupBy("foo");
one = books.head();
models = books.head(3);
bool = books.include(book1);
bool = books.includes(book1);
modelDict = books.indexBy((value: Book, index: number, list: Book[]) => true);
modelDict = books.indexBy("foo");
num = books.indexOf(book1, true);
one = books.initial();
models = books.initial(3);
models = books.inject((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
one = books.invoke("at", 3);
bool = books.isEmpty();
one = books.last();
models = books.last(3);
num = books.lastIndexOf(book1, 3);
models = books.map((value: Book, index: number, list: Book[]) => value);
one = books.max((value: Book, index: number, list: Book[]) => value);
one = books.min((value: Book, index: number, list: Book[]) => value);
[models] = books.partition((value: Book, index: number, list: Book[]) => true);
models = books.reduce((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.reduceRight((prev: Book[], curr: Book, index: number, list: Book[]) => prev, []);
models = books.reject((value: Book, index: number, list: Book[]) => true);
models = books.rest(3);
one = books.sample();
models = books.sample(3);
models = books.select((value: Book, index: number, list: Book[]) => true);
models = books.shuffle();
num = books.size();
bool = books.some((value: Book, index: number, list: Book[]) => true);
models = books.sortBy((value: Book, index: number, list: Book[]) => value);
models = books.sortBy("foo");
models = books.tail(3);
one = books.take();
models = books.take(3);
models = books.toArray();
models = books.without(book1, book1);
}
//////////
+6
View File
@@ -0,0 +1,6 @@
/// <reference path="base64-js.d.ts" />
import * as base64js from 'base64-js';
const bytes: Uint8Array = base64js.toByteArray('shemp');
const decoded: string = base64js.fromByteArray(new Uint8Array(0));
+10
View File
@@ -0,0 +1,10 @@
// Type definitions for base64-js v1.1.2
// Project: https://github.com/beatgammit/base64-js
// Definitions by: Peter Safranek <https://github.com/pe8ter>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'base64-js' {
export function toByteArray(encoded: string): Uint8Array;
export function fromByteArray(bytes: Uint8Array): string;
}
+8
View File
@@ -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;
}
+2 -2
View File
@@ -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?: {
File diff suppressed because it is too large Load Diff
+6 -1
View File
@@ -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;
+5
View File
@@ -44,3 +44,8 @@ $('.typeahead').typeahead({
});
$('#navbar').affix();
$('.item').emulateTransitionEnd(2000);
$.support.transition = false;
console.log(($.support.transition as TransitionEventNames).end === "transitionend");
+11 -1
View File
@@ -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" {
+33
View File
@@ -0,0 +1,33 @@
/// <reference path="browser-pack.d.ts" />
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;
+61
View File
@@ -0,0 +1,61 @@
// Type definitions for browser-pack v6.0.1
// Project: https://github.com/substack/browser-pack
// Definitions by: TeamworkGuy2 <https://github.com/TeamworkGuy2>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/** 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;
}
+39
View File
@@ -0,0 +1,39 @@
/// <reference path="./browser-resolve.d.ts" />
import * as browserResolve from 'browser-resolve';
function basic_test_async(callback: (err?: Error, resolved?: string) => void) {
browserResolve('typescript', function(error, resolved) {
if (error) {
return callback(error);
}
callback(null, resolved);
});
}
function basic_test_sync() {
var resolved = browserResolve.sync('typescript');
}
function options_test_async() {
browserResolve('typescript', {
browser: 'jsnext:main',
filename: './browser-resolve/browser-resolve.js',
modules: {
fs: './fs-shim.js'
}
}, function(error, resolved) {
if (error) {
console.error(error);
return;
}
console.log(resolved);
});
}
function options_test_sync() {
var resolved = browserResolve.sync('typescript', {
filename: './browser-resolve/browser-resolve.js',
modules: {}
});
}
+61
View File
@@ -0,0 +1,61 @@
// Type definitions for browser-resolve
// Project: https://github.com/defunctzombie/node-browser-resolve
// Definitions by: Mario Nebl <https://github.com/marionebl/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../resolve/resolve.d.ts" />
declare module 'browser-resolve' {
import * as resolve from 'resolve';
/**
* Callback invoked when resolving asynchronously
*
* @param error
* @param resolved Absolute path to resolved identifier
*/
type resolveCallback = (err?: Error, resolved?: string) => void;
/**
* Resolve a module path and call cb(err, path [, pkg])
*
* @param id Identifier to resolve
* @param callback
*/
function browserResolve(id: string, cb: resolveCallback): void;
/**
* Resolve a module path and call cb(err, path [, pkg])
*
* @param id Identifier to resolve
* @param options Options to use for resolving, optional.
* @param callback
*/
function browserResolve(id: string, opts: browserResolve.AsyncOpts, cb: resolveCallback): void;
/**
* Returns a module path
*
* @param id Identifier to resolve
* @param options Options to use for resolving, optional.
*/
function browserResolveSync(id: string, opts?: browserResolve.SyncOpts): string;
namespace browserResolve {
interface Opts {
// the 'browser' property to use from package.json (defaults to 'browser')
browser?: string;
// the calling filename where the require() call originated (in the source)
filename?: string;
// modules object with id to path mappings to consult before doing manual resolution (use to provide core modules)
modules?: any;
}
export interface AsyncOpts extends resolve.AsyncOpts, Opts {}
export interface SyncOpts extends resolve.SyncOpts, Opts {}
export var sync: typeof browserResolveSync;
}
export = browserResolve
}
+761
View File
@@ -0,0 +1,761 @@
// Type definitions for nodejs-driver v0.8.2
// Project: https://github.com/datastax/nodejs-driver
// Definitions by: Marc Fisher <http://github.com/Svjard>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../long/long.d.ts" />
declare module "cassandra-driver" {
type Callback = Function;
type ResultCallback = (err: Error, result: types.ResultSet) => void;
import * as events from "events";
import * as stream from "stream";
import _Long = require("long");
namespace policies {
namespace addressResolution {
var EC2MultiRegionTranslator: EC2MultiRegionTranslatorStatic;
interface AddressTranslator {
translate(address: string, port: number, callback: Callback): void;
}
interface EC2MultiRegionTranslatorStatic {
new(): EC2MultiRegionTranslator;
}
interface EC2MultiRegionTranslator extends AddressTranslator {
logError(address: string, err: Error): void;
}
}
namespace loadBalancing {
var DCAwareRoundRobinPolicy: DCAwareRoundRobinPolicyStatic;
var RoundRobinPolicy: RoundRobinPolicyStatic;
var TokenAwarePolicy: TokenAwarePolicyStatic;
var WhiteListPolicy: WhiteListPolicyStatic;
interface LoadBalancingPolicy {
init(client: Client, hosts: HostMap, callback: Callback): void;
getDistance(host: Host): types.distance;
newQueryPlan(keyspace: string, queryOptions: any, callback: Callback): void;
}
interface DCAwareRoundRobinPolicyStatic {
new(localDc?: string, usedHostsPerRemoteDc?: number): DCAwareRoundRobinPolicy;
}
interface DCAwareRoundRobinPolicy extends LoadBalancingPolicy {
localHostsArray: Array<Host>;
remoteHostsArray: Array<Host>;
}
interface RoundRobinPolicyStatic {
new(): RoundRobinPolicy;
}
interface RoundRobinPolicy extends LoadBalancingPolicy {}
interface TokenAwarePolicyStatic {
new(childPolicy: LoadBalancingPolicy): TokenAwarePolicy;
}
interface TokenAwarePolicy extends LoadBalancingPolicy {}
interface WhiteListPolicyStatic {
new(childPolicy: LoadBalancingPolicy, whiteList: Array<string>): WhiteListPolicy;
}
interface WhiteListPolicy extends LoadBalancingPolicy {}
}
namespace reconnection {
var ConstantReconnectionPolicy: ConstantReconnectionPolicyStatic;
var ExponentialReconnectionPolicy: ExponentialReconnectionPolicyStatic;
interface ReconnectionPolicy {
newSchedule(): {next: Function};
}
interface ConstantReconnectionPolicyStatic {
new(delay: number): ConstantReconnectionPolicy;
}
interface ConstantReconnectionPolicy extends ReconnectionPolicy {}
interface ExponentialReconnectionPolicyStatic {
new(baseDelay: number, maxDelay: number, startWithNoDelay: boolean): ExponentialReconnectionPolicy;
}
interface ExponentialReconnectionPolicy extends ReconnectionPolicy {}
}
namespace retry {
var RetryPolicy: RetryPolicyStatic;
interface DecisionInfo {
decision: number;
consistency: number;
}
interface RequestInfo {
request: any,
nbRetry: number
}
enum retryDecision {
rethrow = 0,
retry,
ignore
}
interface RetryPolicyStatic {
new (): RetryPolicy;
retryDecision: any;
}
interface RetryPolicy {
onReadTimeout(requestInfo: RequestInfo, consistency: types.consistencies, received: number, blockFor: number, isDataPresent: boolean): DecisionInfo;
onUnavailable(requestInfo: RequestInfo, consistency: types.consistencies, required: number, alive: number): DecisionInfo;
onWriteTimeout(requestInfo: RequestInfo, consistency: types.consistencies, received: number, blockFor: number, writeType: string): DecisionInfo;
rethrowResult(): { decision: retryDecision };
retryResult(): { decision: retryDecision, consistency: types.consistencies, useCurrentHost: boolean };
}
}
}
namespace types {
var BigDecimal: BigDecimalStatic;
var InetAddress: InetAddressStatic;
var Integer: IntegerStatic;
var LocalDate: LocalDateStatic;
var LocalTime: LocalTimeStatic;
var Long: _Long;
var ResultSet: ResultSetStatic;
var ResultStream: ResultStreamStatic;
var Row: RowStatic;
var TimeUuid: TimeUuidStatic;
var Tuple: TupleStatic;
var Uuid: UuidStatic;
enum consistencies {
any = 0,
one,
two,
three,
quorum,
all,
localQuorm,
eachQuorum,
serial,
localSerial,
localOne
}
enum dataTypes {
custom = 0,
ascii,
bigint,
blob,
boolean,
counter,
decimal,
double,
float,
int,
text,
timestamp,
uuid,
varchar,
varint,
timeuuid,
inet,
date,
time,
smallint,
tinyint,
list,
map,
set,
udt,
tuple
}
enum distance {
local = 0,
remote,
ignored
}
interface responseErrorCodes { [key:string]:number; }
interface unset { unset: boolean; }
function generateTimestamp(date?: Date, microseconds?: number): _Long;
function timeuuid(options?: {msecs: number | Date, node: Buffer, clockseq: number, nsecs: number}, buffer?: Buffer, offset?: number): string;
interface BigDecimalStatic {
new (unscaledValue: number, scale: number): BigDecimal;
fromBuffer(buf: Buffer): BigDecimal;
toBuffer(value: BigDecimal): Buffer;
fromString(value: string): BigDecimal;
fromNumber(value: number): BigDecimal;
}
interface BigDecimal {
equals(other: BigDecimal): boolean;
inspect(): string;
notEquals(other: BigDecimal): boolean;
compare(other: BigDecimal): number;
subtract(other: BigDecimal): BigDecimal;
add(other: BigDecimal): BigDecimal;
greaterThan(other: BigDecimal): boolean;
isNegative(): boolean;
isZero(): boolean;
toString(): string;
toNumber(): number;
toJSON(): string;
}
interface InetAddressStatic {
new(buffer: Buffer): InetAddress;
fromString(value: string): InetAddress;
}
interface InetAddress {
equals(other: InetAddress): boolean;
getBuffer(): Buffer;
inspect(): string;
toString(): string;
toJSON(): string;
length: number;
version: number;
}
interface IntegerStatic {
new(bits: Array<number>, sign: number): Integer;
fromInt(value: number): Integer;
fromNumber(value: number): Integer;
fromBits(bits: Array<number>): Integer;
fromString(str: string, opt_radix?: number): Integer;
fromBuffer(bits: Buffer): Integer;
toBuffer(value: Integer): Buffer;
ZERO: Integer;
ONE: Integer;
}
interface Integer {
toInt(): number;
toNumber(): number;
toString(opt_radix?: number): string;
getBits(index: number): number;
getBitsUnsigned(index: number): number;
getSign(): number;
isZero(): boolean;
isNegative(): boolean;
isOdd(): boolean;
equals(other: Integer): boolean;
notEquals(other: Integer): boolean;
greaterThan(other: Integer): boolean;
greaterThanOrEqual(other: Integer): boolean;
lessThan(other: Integer): boolean;
lessThanOrEqual(other: Integer): boolean;
compare(other: Integer): number;
shorten(numBits: number): Integer;
negate(): Integer;
add(other: Integer): Integer;
subtract(other: Integer): Integer;
multiply(other: Integer): Integer;
divide(other: Integer): Integer;
modulo(other: Integer): Integer;
not(): Integer;
and(other: Integer): Integer;
or(other: Integer): Integer;
xor(other: Integer): Integer;
shiftLeft(numBits: number): Integer;
shiftRight(numBits: number): Integer;
inspect(): string;
abs(): Integer;
toJSON(): string;
}
interface LocalDateStatic {
new(year: number, month: number, day: number): LocalDate;
now(): LocalDate;
utcNow(): LocalDate;
fromDate(date: Date): LocalDate;
fromString(value: string): LocalDate;
fromBuffer(buffer: Buffer): LocalDate;
}
interface LocalDate {
_value: number;
year: number;
month: number;
day: number;
equals(other: LocalDate): boolean;
inspect(): string;
toBuffer(): Buffer;
toString(): string;
toJSON(): string;
}
interface LocalTimeStatic {
new (totalNanoseconds: _Long): LocalTime;
fromString(value: string): LocalTime;
now(nanoseconds?: number): LocalTime;
fromDate(date: Date, nanoseconds: number): LocalTime;
fromMilliseconds(milliseconds: number, nanoseconds?: number): LocalTime;
fromBuffer(value: Buffer): LocalTime;
}
interface LocalTime {
hour: number;
minute: number;
second: number;
nanosecond: number;
compare(other: LocalTime): boolean;
equals(other: LocalTime): boolean;
getTotalNanoseconds(): _Long;
inspect(): string;
toBuffer(): Buffer;
toString(): string;
toJSON(): string;
}
interface ResultSetStatic {
new(response: any, host: string, triedHost: { [key:string]: any }, consistency: consistencies): ResultSet;
}
interface ResultSet {
info: {
queriedHost: Host,
triedHosts: { [key:string]:string; },
achievedConsistency: consistencies,
traceId: Uuid,
warnings: Array<string>,
customPayload: any
};
rows: Array<Row>;
rowLength: number;
columns: Array<{ [key:string]:string; }>;
pageState: string;
nextPage: any; // function
first(): Row;
getPageState(): string;
getColumns(): Array<{ [key:string]:string; }>;
}
interface ResultStreamStatic {
new (opt: any): ResultSet;
}
interface ResultStream extends stream.Readable {
buffer: Buffer;
paused: boolean;
_read(): void;
_valve(readNext: Function): void;
add(chunk: Buffer): void;
}
interface RowStatic {
new(columns: Array<{ [key:string]:string; }>): Row;
}
interface Row {
get(columnName: string|number): { [key:string]:any; };
values(): Array<{ [key:string]:any; }>;
keys(): Array<string>;
forEach(callback: Callback): void;
}
interface TimeUuidStatic {
new (value?: Date, ticks?: number, nodeId?: string|Buffer, clockId?: string|Buffer): TimeUuid;
fromDate(date: Date, ticks?: number, nodeId?: string|Buffer, clockId?: string|Buffer): TimeUuid;
fromString(value: string): TimeUuid;
min(date: Date, ticks?: number): TimeUuid;
max(date: Date, ticks?: number): TimeUuid;
now(nodeId?: string|Buffer, clockId?: string|Buffer): TimeUuid;
}
interface TimeUuid extends Uuid {
getDatePrecision(): { date: Date, ticks: number };
getDate(): Date;
getNodeId(): Buffer;
getNodeIdString(): string;
}
interface TupleStatic {
new (...arguments: Array<any>): Tuple;
fromArray(elements: Array<any>): Tuple;
}
interface Tuple {
elements: Array<any>;
length: number;
get(index: number): any;
toString(): string;
toJSON(): string;
values(): Array<any>;
}
interface UuidStatic {
new (buffer: Buffer): Uuid;
fromString(value: string): Uuid;
random(): Uuid;
}
interface Uuid {
buffer: Buffer;
getBuffer(): Buffer;
equals(other: types.Uuid): boolean;
toString(): string;
inspect(): string;
toJSON(): string;
}
}
var Client: ClientStatic;
var Host: HostStatic;
var HostMap: HostMapStatic;
var Encoder: EncoderStatic;
interface ClientOptions {
contactPoints: Array<string>,
keyspace: string,
policies?: {
addressResolution?: policies.addressResolution.AddressTranslator,
loadBalancing?: policies.loadBalancing.LoadBalancingPolicy,
reconnection?: policies.reconnection.ReconnectionPolicy,
retry?: policies.retry.RetryPolicy
},
queryOptions?: QueryOptions,
pooling?: {
heartBeatInterval: number,
coreConnectionsPerHost: { [key:number]:number; },
warmup: boolean;
},
protocolOptions?: {
port: number,
maxSchemaAgreementWaitSeconds: number,
maxVersion: number
},
socketOptions?: {
connectTimeout: number,
defunctReadTimeoutThreshold: number,
keepAlive: boolean,
keepAliveDelay: number,
readTimeout: number,
tcpNoDelay: boolean,
coalescingThreshold: number
},
authProvider?: auth.AuthProvider,
sslOptions?: any,
encoding?: {
map: Function,
set: Function,
copyBuffer: boolean,
useUndefinedAsUnset: boolean
}
}
interface QueryOptions {
autoPage?: boolean;
captureStackTrace?: boolean;
consistency: number;
customPayload?: any;
fetchSize?: number;
hints: Array<string> | Array<Array<string>>;
logged?: boolean;
pageState?: Buffer|string;
prepare?: boolean;
readTimeout?: number;
retry?: policies.retry.RetryPolicy;
retryOnTimeout?: boolean;
routingIndexes?: Array<number>;
routingKey?: Buffer | Array<Buffer>;
routingNames?: Array<string>;
serialConsistency?: number;
timestamp?: number | _Long;
traceQuery?: boolean;
}
interface ClientStatic {
new(options?: ClientOptions): Client;
}
interface Client extends events.EventEmitter {
hosts: HostMap;
keyspace: string;
metadata: metadata.Metadata;
batch(queries: Array<string>|Array<{query: string, params?: any}>, options: QueryOptions, callback: ResultCallback): void;
connect(callback: Callback): void;
eachRow(query: string, params?: any, options?: QueryOptions, rowCallback?: Callback, callback?: Callback): void;
execute(query: string, params?: any, options?: QueryOptions, callback?: ResultCallback): void;
getReplicas(keyspace: string, token: Buffer): Array<any>; // TODO: Should this be a more explicit return?
shutdown(callback?: Callback): void;
stream(query: string, params?: any, options?: QueryOptions, callback?: Callback): void;
}
interface HostStatic {
new(address: string, protocolVersion: number, options: ClientOptions): Host;
}
interface Host extends events.EventEmitter {
address: string;
cassandraVersion: string;
dataCenter: string;
rack: string;
tokens: Array<string>;
canBeConsideredAsUp(): boolean;
getCassandraVersion(): Array<number>;
isUp(): boolean;
}
interface HostMapStatic {
new (): HostMap;
}
interface HostMap extends events.EventEmitter {
length: number;
forEach(callback: Callback): void;
get(key: string): Host;
keys(): Array<string>;
remove(key: string): void;
removeMultiple(keys: Array<string>): void;
set(key: string, value: Host): void;
values(): Array<Host>;
}
interface EncoderStatic {
new(protocolVersion: number, options: ClientOptions) : Encoder;
}
interface Encoder {
decode(buffer: Buffer, type: {code: number, info?: any}): void;
encode(value: any, typeInfo?: string|number|{code: number, info?: any}): Buffer;
}
namespace auth {
var Authenticator: AuthenticatorStatic;
var PlainTextAuthProvider: PlainTextAuthProviderStatic;
interface AuthenticatorStatic {
new (): Authenticator;
}
interface Authenticator {
evaluateChallenge(challenge: Buffer, callback: Callback): void;
initialResponse(callback: Callback): void;
onAuthenticationSuccess(token?: Buffer): void;
}
interface AuthProvider {
newAuthenticator(endpoint: string, name: string): void;
}
interface PlainTextAuthProviderStatic {
new (username: string, password: string): PlainTextAuthProvider;
}
interface PlainTextAuthProvider extends AuthProvider {
newAuthenticator(endpoint: string, name: string): void;
}
}
namespace errors {
abstract class DriverError {
constructor(message: string, constructor?: any);
}
class ArgumentError extends DriverError {
constructor(message: string);
}
class AuthenticationError extends DriverError {
constructor(message: string);
}
class DriverInternalError extends DriverError {
constructor(message: string);
}
class NoHostAvailableError extends DriverError {
constructor(innerErrors: any, message?: string);
}
class NotSupportedError extends DriverError {
constructor(message: string);
}
class OperationTimedOutError extends DriverError {}
class ResponseError extends DriverError {
constructor(code: number, message: string);
}
}
namespace metadata {
var Aggregate: AggregateStatic;
var Index: IndexStatic;
var MaterializedView: MaterializedViewStatic;
var Metadata: MetadataStatic;
var SchemaFunction: SchemaFunctionStatic;
var TableMetadata: TableMetadataStatic;
type caching = "all" | "keys_only" | "rows_only" | "none";
interface AggregateStatic {
new (): Aggregate;
}
interface Aggregate {
argumentTypes: Array<{ code: number, info: any}>;
finalFunction: string;
initCondition: string;
keyspaceName: string,
returnType: string;
signature: Array<string>;
stateFunction: string;
stateType: string;
}
interface DataTypeInfo {
code: number,
info: string | DataTypeInfo | Array<DataTypeInfo>,
options: {
frozen: boolean,
reversed: boolean
}
}
interface ColumnInfo {
name: string,
type: DataTypeInfo
}
interface DataCollection {
bloomFilterFalsePositiveChance: number;
caching: caching;
clusterKeys: Array<{ c: ColumnInfo, index: number, order: string }>;
clusteringOrder: Array<string>;
columns: Array<ColumnInfo>;
columnsByName: { [key: string]: ColumnInfo };
comment: string;
compactionClass: string;
compactionOptions: any;
compression: any;
crcCheckChange?: number;
defaultTtl: number;
extensions: any;
gcGraceSeconds: number;
localReadRepairChance: number;
maxIndexInterval?: number;
minIndexInterval?: number;
name: string;
partitionKeys: Array<{ c: ColumnInfo, index: number }>
populateCacheOnFlush: boolean;
readRepairChance: number;
speculateRetry: string;
}
enum IndexType {
custom = 0,
keys,
composites
}
interface IndexStatic {
new (name: string, target: string, kind: IndexType, options: Object): Index;
fromRows(indexRows: Array<types.Row>): Array<Index>;
fromColumnRows(columnRows: Array<types.Row>, columnsByName: { [key:string]: ColumnInfo }): Array<Index>;
}
interface Index {
kind: IndexType;
name: string;
options: Object;
target: string;
isCompositesKind(): boolean;
isCustomKind(): boolean;
isKeysKind(): boolean;
}
interface MaterializedViewStatic {
new (name: string): MaterializedView;
}
interface MaterializedView extends DataCollection {}
interface MetadataStatic {
new (options: ClientOptions, controlConnection: any): Metadata;
}
interface Metadata {
clearPrepared(): void;
getAggregate(keyspaceName: string, name: string, signature: Array<string> | Array<{ code: number, info: any }>, callback: Callback): void;
getAggregates(keyspaceName: string, name: string, callback: Callback): void;
getFunction(keyspaceName: string, name: string, signature: Array<string> | Array<{ code: number, info: any }>, callback: Callback): void;
getFunctions(keyspaceName: string, name: string, callback: Callback): void;
getMaterializedView(keyspaceName: string, name: string, callback: Callback): void;
getReplicas(keyspaceName: string, tokenBuffer: Buffer): Array<any>;
getTable(keyspaceName: string, name: string, callback: Callback): void;
getTrace(traceId: types.Uuid, callback: Callback): void;
getUdt(keyspaceName: string, name: string, callback: Callback): void;
refreshKeyspace(name: string, callback?: Callback): void;
refreshKeyspaces(callback?: Callback): void;
}
interface SchemaFunctionStatic {
new (): SchemaFunction;
}
interface SchemaFunction {
argumentNames: Array<string>;
argumentTypes: Array<{ code: number, info: any}>;
body: string;
calledOnNullInput: boolean;
keyspaceName: string,
language: string;
name: string;
returnType: string;
signature: Array<string>;
}
interface TableMetadataStatic {
new (name: string): TableMetadata;
}
interface TableMetadata extends DataCollection {
indexes: Array<Index>;
indexInterval?: number;
isCompact: boolean;
memtableFlushPeriod: number;
replicateOnWrite: boolean;
}
}
}
@@ -0,0 +1,11 @@
/// <reference path="cassandra-driver.d.ts" />
import * as cassandra from 'cassandra-driver';
import * as util from 'util';
var client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1'});
var query = 'SELECT email, last_name FROM user_profiles WHERE key=?';
client.execute(query, ['guy'], function(err, result) {
console.log('got user profile with email ' + result.rows[0].email);
});
+18
View File
@@ -1930,6 +1930,24 @@ suite('assert', () => {
}, 'expected 5 to be below 5');
});
test('isAtLeast', () => {
assert.isAtLeast(5, 3);
assert.isAtLeast(5, 5);
err(() => {
assert.isAtLeast(3, 5);
}, 'expected 3 to be greater than or equal to 5');
});
test('isAtMost', () => {
assert.isAtMost(3, 5);
assert.isAtMost(5, 5);
err(() => {
assert.isAtMost(5, 3);
}, 'expected 5 to be less than or equal to 3');
});
test('extensible', () => { assert.extensible({}); });
test('isExtensible', () => { assert.isExtensible({}); });
test('notExtensible', () => { assert.notExtensible(Object.preventExtensions({})); });
+3
View File
@@ -271,6 +271,9 @@ declare namespace Chai {
isAbove(val: number, abv: number, msg?: string): void;
isBelow(val: number, blw: number, msg?: string): void;
isAtMost(val: number, atmst: number, msg?: string): void;
isAtLeast(val: number, atlst: number, msg?: string): void;
isFunction(val: any, msg?: string): void;
isNotFunction(val: any, msg?: string): void;
+13
View File
@@ -378,7 +378,20 @@ declare namespace Chai {
}
export interface Config {
/**
* Default: false
*/
includeStack: boolean;
/**
* Default: true
*/
showDiff: boolean;
/**
* Default: 40
*/
truncateThreshold: number;
}
export class AssertionError {
+1 -1
View File
@@ -105,7 +105,7 @@ declare namespace Chartist {
plugins?: Array<any>; // 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.
+1 -1
View File
@@ -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;
+10 -8
View File
@@ -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;
+156
View File
@@ -0,0 +1,156 @@
/// <reference path="common-tags.d.ts" />
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`
<div class="list">
<ul>
${fruits.map(fruit => `<li>${fruit}</li>`)}
${'<li>kiwi</li>\n<li>guava</li>'}
</ul>
</div>
`;
commonTags.codeBlock`
<div class="list">
<ul>
${fruits.map(fruit => `<li>${fruit}</li>`)}
${'<li>kiwi</li>\n<li>guava</li>'}
</ul>
</div>
`;
commonTags.source`
<div class="list">
<ul>
${fruits.map(fruit => `<li>${fruit}</li>`)}
${'<li>kiwi</li>\n<li>guava</li>'}
</ul>
</div>
`;
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'));
+62
View File
@@ -0,0 +1,62 @@
// Type definitions for common-tags v1.2.1
// Project: https://github.com/declandewet/common-tags
// Definitions by: Viktor Zozuliak <https://github.com/zuzusik>
// 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;
}
@@ -0,0 +1,52 @@
/// <reference path='../node/node.d.ts' /> // only for require
/// <reference path='component-emitter.d.ts' />
// 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);
(<Emitter>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')
+19
View File
@@ -0,0 +1,19 @@
// Type definitions for component-emitter v1.2.1
// Project: https://www.npmjs.com/package/component-emitter
// Definitions by: Peter Snider <https://github.com/psnider/>
// 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;
}
+14 -2
View File
@@ -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 {
Vendored
+9 -8
View File
@@ -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<NewDatum>(value: NewDatum): Update<NewDatum>;
/**
* 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<NewDatum>(value: (datum: Datum, index: number, outerIndex: number) => NewDatum): Update<NewDatum>;
/**
* Set the data item for each node in the selection.
* @param value the constant element to use for each node
*/
datum<NewDatum>(value: NewDatum): Update<NewDatum>;
/**
* 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<T>(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<T>(array: T[], x: T, lo?: number, hi?: number): number;
export var bisect: typeof bisectRight;
@@ -3064,6 +3063,8 @@ declare namespace d3 {
}
export interface Partition<T extends partition.Node> {
(root: T): T[];
nodes(root: T): T[];
links(nodes: T[]): partition.Link<T>[];
+1112
View File
File diff suppressed because it is too large Load Diff
+155
View File
@@ -0,0 +1,155 @@
// Type definitions for d3Kit v1.1.0
// Project: https://www.npmjs.com/package/d3kit
// Definitions by: Morgan Benton <https://github.com/morphatic/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../d3/d3.d.ts" />
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<string>);
// Getters
getCustomEventNames(): Array<string>;
getDispatcher(): any; // should be d3.Dispatch but this throws error for user-created events
getInnerWidth(): number;
getInnerHeight(): number;
getLayerOrganizer(): LayerOrganizer;
getRootG(): d3.Selection<any>;
getSvg(): d3.Selection<any>;
// 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<number>, 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<any>) => 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<any>, done?: string): (sel: d3.Selection<any>) => void;
}
export class Chartlet {
constructor(
enterFunction?: ChartletEventFunction,
updateFunction?: ChartletEventFunction,
exitFunction?: ChartletEventFunction,
customEventName?: Array<string>);
// Getter functions
getDispatcher(): d3.Dispatch;
getCustomEventNames(): Array<string>;
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<any>, done?: string): (sel: d3.Selection<any>) => void;
update(sel?: d3.Selection<any>, done?: string): (sel: d3.Selection<any>) => void;
exit( sel?: d3.Selection<any>, done?: string): (sel: d3.Selection<any>) => void;
// Inheritance functions
inheritPropertyFrom(parent_chartlet: Chartlet, parent_property_name: string, child_property_name?: string): void;
inheritPropertiesFrom(parent_chartlet: Chartlet, parent_property_names: Array<string>, child_property_names?: Array<string>): void;
publishEventsTo(dispatcher: d3.Dispatch): Chartlet;
// Events
on(eventName: string, handlerFunction: ChartletEventFunction): void;
}
interface LayerConfig {
name?: string,
names?: Array<string>,
sublayers?: LayerConfig
}
export class LayerOrganizer {
constructor(container: d3.Selection<any>, tag?: string);
create(config: string|Array<string>|LayerConfig|Array<LayerConfig>): d3.Selection<any>|Array<d3.Selection<any>>;
get(name: string): d3.Selection<any>;
has(name: string): boolean;
}
export namespace factory {
export function createChart(
defaultOptions: ChartOptions,
customEvents: Array<string>,
constructor: (skeleton: Skeleton) => void
): (selector: string|Element, options?: ChartOptions, customEvents?: Array<string>) => Skeleton;
}
export namespace helper {
export function debounce(fn: (...args: Array<any>) => void, wait: number, immediate: boolean): (...args: Array<any>) => void;
export function extend(target: Object, ...args: Object[]): Object;
export function deepExtend(target: Object, ...args: Object[]): Object;
export function bindMouseEventsToDispatcher(selection: d3.Selection<any>, dispatch: d3.Dispatch, prefix: string): void;
export function removeAllChildren(selection: d3.Selection<any>, noTransition: boolean): d3.Selection<any>;
export function on(element: Element, type: string, listener: (...args: Array<any>) => void): void;
export function off(element: Element, type: string, listener: (...args: Array<any>) => 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<Node>|NodeList): Array<Element>;
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;
}
+146
View File
@@ -0,0 +1,146 @@
/// <reference path='d3pie.d.ts' />
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
}
})
+146
View File
@@ -0,0 +1,146 @@
// Type definitions for d3pie 0.1.9
// Project: https://github.com/benkeen/d3pie
// Definitions by: Petryshyn Sergii <https://github.com/mc-petry>
// 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
+3
View File
@@ -11,6 +11,9 @@ namespace DagreD3Tests {
predecessors["a"] = graph.predecessors("a");
successors["a"] = graph.successors("a");
graph.transition = (selection: d3.Selection<any>) => {
return d3.transition();
};
const render = new dagreD3.render();
const svg = d3.select("svg");
+2
View File
@@ -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<any>): d3.Transition<any>;
width: number;
}
@@ -1,4 +1,4 @@
/// <reference path="DataStream.js.d.ts" />
/// <reference path="datastream.js.d.ts" />
var buf = new ArrayBuffer(100);
var ds = new DataStream(buf);
+133
View File
@@ -0,0 +1,133 @@
// Type definitions for echarts
// Project: http://echarts.baidu.com/
// Definitions by: Xie Jingyang <https://github.com/xieisabug>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace ECharts {
function init(dom:HTMLDivElement|HTMLCanvasElement, theme?:Object|string, opts?:{
devicePixelRatio?: number
renderer?: string
}):ECharts;
function connect(group:string|Array<string>):void;
function disConnect(group:string):void;
function dispose(target:ECharts|HTMLDivElement|HTMLCanvasElement):void;
function getInstanceByDom(target:HTMLDivElement|HTMLCanvasElement):void;
function registerMap(mapName:string, geoJson:Object, specialAreas?:Object):void;
function registerTheme(themeName:string, theme:Object):void;
class ECharts {
group:string;
setOption(option:EChartOption, notMerge?:boolean, notRefreshImmediately?:boolean):void
getWidth():number
getHeight():number
getDom():HTMLCanvasElement|HTMLDivElement
getOption():Object
resize():void
dispatchAction(payload:Object):void
on(eventName:string, handler:Function, context?:Object):void
off(eventName:string, handler?:Function):void
showLoading(type?:string, opts?:Object):void
hideLoading():void
getDataURL(opts:{
// 导出的格式,可选 png, jpeg
type?: string,
// 导出的图片分辨率比例,默认为 1。
pixelRatio?: number,
// 导出的图片背景色,默认使用 option 里的 backgroundColor
backgroundColor?: string
}):string
getConnectedDataURL(opts:{
// 导出的格式,可选 png, jpeg
type: string,
// 导出的图片分辨率比例,默认为 1。
pixelRatio: number,
// 导出的图片背景色,默认使用 option 里的 backgroundColor
backgroundColor: string
}):string
clear():void
isDisposed():boolean
dispose():void
}
interface EChartOption {
title?: EChartTitleOption
legend?: Object,
grid?: Object,
xAxis?: Object,
yAxis?: Object,
polar?: Object,
radiusAxis?: Object,
angleAxis?: Object,
radar?: Object,
dataZoom?: Array<Object>,
visualMap?: Array<Object>,
tooltip?: Object,
toolbox?: Object,
geo?: Object,
parallel?: Object,
parallelAxis?: Object,
timeline?: Object,
series?: Array<Object>,
color?: Array<Object>,
backgroundColor?: string,
textStyle?: Object,
animation?: boolean,
animationDuration?: number,
animationEasing?: string,
animationDurationUpdate?: number,
animationEasingUpdate?: string
}
interface EChartTitleOption {
show?: boolean;
text?: string;
link?: string,
target?: string,
textStyle?: Object,
subtext?: string,
sublink?: string,
subtarget?: string,
subtextStyle?: Object,
padding?: number,
itemGap?: number,
zlevel?: number,
z?: number,
left?: string,
top?: string,
right?: string,
bottom?: string,
backgroundColor?: string,
borderColor?: string,
borderWidth?: number,
shadowBlur?: number,
shadowColor?: number,
shadowOffsetX?: number,
shadowOffsetY?: number,
}
}
declare module "echarts" {
export = ECharts;
}
+1
View File
@@ -71,6 +71,7 @@ declare namespace esprima {
LabeledStatement: string,
LogicalExpression: string,
MemberExpression: string,
MetaProperty: string,
MethodDefinition: string,
NewExpression: string,
ObjectExpression: string,
+15
View File
@@ -0,0 +1,15 @@
/// <reference path="exorcist.d.ts" />
import exorcist = require("exorcist");
module ExorcistTest {
function pullSourceMaps(srcPath: string, projRoot: string) {
exorcist(srcPath, undefined, projRoot);
exorcist(srcPath, null, projRoot, null, true);
exorcist(srcPath, null, projRoot, "./");
}
}
export = ExorcistTest;
+21
View File
@@ -0,0 +1,21 @@
// Type definitions for exorcist v0.4.0
// Project: https://github.com/thlorenz/exorcist
// Definitions by: TeamworkGuy2 <https://github.com/TeamworkGuy2>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../through/through.d.ts" />
declare module 'exorcist' {
import through = require("through");
/** Externalizes the source map found inside a stream to an external .map file.
* Works with both JavaScript and CSS input streams
* @param file full path to the map file to which to write the extracted source map
* @param [url] full URL to the map file, set as sourceMappingURL in the streaming output (default: file)
* @param [root] root URL for loading relative source paths, set as sourceRoot in the source map (default: "")
* @param [base] base path for calculating relative source paths (default: use absolute paths)
* @param [errorOnMissing] when truthy, causes 'error' to be emitted instead of 'missing-map' if no map was found in the stream (default: falsey)
*/
function exorcist(file: string, url?: string, root?: string, base?: string, errorOnMissing?: boolean): through.ThroughStream;
export = exorcist;
}
+18 -16
View File
@@ -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<T> {
(name: string | RegExp, ...handlers: RequestHandler[]): T;
(name: string | RegExp, ...handlers: RequestHandlerParams[]): T;
}
interface IRouter<T> 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;
};
/**
+6 -2
View File
@@ -3,7 +3,7 @@
// Definitions by: kmxz <https://github.com/kmxz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'fbemitter' {
declare namespace FBEmitter {
export class EventSubscription {
@@ -64,4 +64,8 @@ declare module 'fbemitter' {
}
}
}
declare module 'fbemitter' {
export = FBEmitter;
}
+1
View File
@@ -150,6 +150,7 @@ interface FBSDKCanvas{
}
interface FBResponseObject {
data: any;
error: any;
}
+2 -2
View File
@@ -30,7 +30,7 @@
percentPosition: false,
prevNextButtons: false,
selectedAttraction: 0.050,
useSetGallerySize: true,
setGallerySize: true,
watchCSS: true,
wrapAround: true,
resize: true,
@@ -64,7 +64,7 @@
percentPosition: false,
prevNextButtons: false,
selectedAttraction: 0.050,
useSetGallerySize: true,
setGallerySize: true,
watchCSS: true,
wrapAround: true,
resize: true,
+1 -1
View File
@@ -269,7 +269,7 @@ interface FlickityOptions {
*
* default: true
*/
useSetGallerySize?: boolean;
setGallerySize?: boolean;
/**
* Adjusts sizes and positions when window is resized.
+3 -3
View File
@@ -1,5 +1,5 @@
/// <reference path="flux.d.ts" />
/// <reference path="../react/react.d.ts" />
/// <reference path="../react/react.d.ts" />
import flux = require('flux')
import FluxUtils = require('flux/utils')
@@ -88,7 +88,7 @@ export = customDispatcher
// Sample Reduce Store
class CounterStore extends FluxUtils.ReduceStore<number> {
class CounterStore extends FluxUtils.ReduceStore<number, Action> {
getInitialState(): number {
return 0;
}
@@ -126,4 +126,4 @@ class CounterContainer extends Component<any, any> {
}
}
const container = Container.create(CounterContainer);
const container = Container.create<CounterContainer>(CounterContainer);
+35 -13
View File
@@ -4,6 +4,8 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../react/react.d.ts" />
/// <reference path="../fbemitter/fbemitter.d.ts" />
/// <reference path="../immutable/immutable.d.ts" />
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<any>, options?: any): React.ComponentClass<any>;
static create<TComponent>(base: React.ComponentClass<TComponent>, options?: RealOptions): React.ComponentClass<TComponent>;
}
/**
* This class extends ReduceStore and defines the state as an immutable map.
*/
// TODO: Change <any> to <Immutable.Map<K, V>>
export class MapStore<K extends string | number, V> extends ReduceStore<any> {
export class MapStore<K extends string | number, V, TPayload> extends ReduceStore<immutable.Map<K, V>, 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<K>, prev?: Immutable.Map<K, V>): Immutable.Map<K, V>;
getAll(keys: any, prev?: any): any;
getAll(keys: immutable.Iterable.Indexed<K>, prev?: immutable.Map<K, V>): immutable.Map<K, V>;
}
export class ReduceStore<T> extends Store {
export class ReduceStore<T, TPayload> extends Store<TPayload> {
/**
* 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<TPayload> {
/**
* Constructs and registers an instance of this store with the given dispatcher.
*/
constructor(dispatcher: Flux.Dispatcher<any>);
constructor(dispatcher: Flux.Dispatcher<TPayload>);
/**
* 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<any>;
getDispatcher(): Flux.Dispatcher<TPayload>;
/**
* 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;
}
}
-179
View File
@@ -2,50 +2,16 @@
/// <reference path="../node/node.d.ts" />
import fs = require('fs-extra');
import stream = require('stream');
var stats: fs.Stats;
var str: string;
var strArr: string[];
var bool: boolean;
var num: number;
var src: string;
var dest: string;
var file: string;
var filename: string;
var dir: string;
var path: string;
var data: any;
var object: Object;
var buffer: NodeBuffer;
var modeNum: number;
var modeStr: string;
var encoding: string;
var type: string;
var flags: string;
var srcpath: string;
var dstpath: string;
var oldPath: string;
var newPath: string;
var cache: string;
var offset: number;
var length: number;
var position: number;
var cacheBool: boolean;
var cacheStr: string;
var fd: number;
var len: number;
var uid: number;
var gid: number;
var atime: number;
var mtime: number;
var statsCallback: (err: Error, stats: fs.Stats) => void;
var errorCallback: (err: Error) => void;
var openOpts: fs.OpenOptions;
var watcher: fs.FSWatcher;
var readStreeam: stream.Readable;
var writeStream: stream.Writable;
var outputStream: stream.Writable;
fs.copy(src, dest, errorCallback);
fs.copy(src, dest, (src: string) => {
@@ -125,130 +91,6 @@ fs.writeJSON(file, object, openOpts, errorCallback);
fs.writeJsonSync(file, object, openOpts);
fs.writeJSONSync(file, object, openOpts);
fs.rename(oldPath, newPath, errorCallback);
fs.renameSync(oldPath, newPath);
fs.truncate(fd, len, errorCallback);
fs.truncateSync(fd, len);
fs.chown(path, uid, gid, errorCallback);
fs.chownSync(path, uid, gid);
fs.fchown(fd, uid, gid, errorCallback);
fs.fchownSync(fd, uid, gid);
fs.lchown(path, uid, gid, errorCallback);
fs.lchownSync(path, uid, gid);
fs.chmod(path, modeNum, errorCallback);
fs.chmod(path, modeStr, errorCallback);
fs.chmodSync(path, modeNum);
fs.chmodSync(path, modeStr);
fs.fchmod(fd, modeNum, errorCallback);
fs.fchmod(fd, modeStr, errorCallback);
fs.fchmodSync(fd, modeNum);
fs.fchmodSync(fd, modeStr);
fs.lchmod(path, modeStr, errorCallback);
fs.lchmod(path, modeNum, errorCallback);
fs.lchmodSync(path, modeNum);
fs.lchmodSync(path, modeStr);
fs.stat(path, statsCallback);
fs.lstat(path, statsCallback);
fs.fstat(fd, statsCallback);
stats = fs.statSync(path);
stats = fs.lstatSync(path);
stats = fs.fstatSync(fd);
fs.link(srcpath, dstpath, errorCallback);
fs.linkSync(srcpath, dstpath);
fs.symlink(srcpath, dstpath, type, errorCallback);
fs.symlinkSync(srcpath, dstpath, type);
fs.readlink(path, (err: Error, linkString: string) => {
});
fs.realpath(path, (err: Error, resolvedPath: string) => {
});
fs.realpath(path, cache, (err: Error, resolvedPath: string) => {
});
str = fs.realpathSync(path, cacheBool);
fs.unlink(path, errorCallback);
fs.unlinkSync(path);
fs.rmdir(path, errorCallback);
fs.rmdirSync(path);
fs.mkdir(path, modeNum, errorCallback);
fs.mkdir(path, modeStr, errorCallback);
fs.mkdirSync(path, modeNum);
fs.mkdirSync(path, modeStr);
fs.readdir(path, (err: Error, files: string[]) => {
});
strArr = fs.readdirSync(path);
fs.close(fd, errorCallback);
fs.closeSync(fd);
fs.open(path, flags, modeStr, (err: Error, fd: number) => {
});
num = fs.openSync(path, flags, modeStr);
fs.utimes(path, atime, mtime, errorCallback);
fs.utimesSync(path, atime, mtime);
fs.futimes(fd, atime, mtime, errorCallback);
fs.futimesSync(fd, atime, mtime);
fs.fsync(fd, errorCallback);
fs.fsyncSync(fd);
fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: NodeBuffer) => {
});
num = fs.writeSync(fd, buffer, offset, length, position);
fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: NodeBuffer) => {
});
num = fs.readSync(fd, buffer, offset, length, position);
fs.readFile(filename, (err: Error, data: NodeBuffer) => {
});
fs.readFile(filename, encoding, (err: Error, data: string) => {
});
fs.readFile(filename, openOpts, (err: Error, data: string) => {
});
fs.readFile(filename, (err: Error, data: NodeBuffer) => {
});
buffer = fs.readFileSync(filename);
str = fs.readFileSync(filename, encoding);
str = fs.readFileSync(filename, openOpts);
fs.writeFile(filename, data, errorCallback);
fs.writeFile(filename, data, encoding, errorCallback);
fs.writeFile(filename, data, openOpts, errorCallback);
fs.writeFileSync(filename, data);
fs.writeFileSync(filename, data, encoding);
fs.writeFileSync(filename, data, openOpts);
fs.appendFile(filename, data, errorCallback);
fs.appendFile(filename, data, encoding, errorCallback);
fs.appendFile(filename, data, openOpts, errorCallback);
fs.appendFileSync(filename, data);
fs.appendFileSync(filename, data, encoding);
fs.appendFileSync(filename, data, openOpts);
fs.watchFile(filename, {
curr: stats,
prev: stats
});
fs.watchFile(filename, {
persistent: bool,
interval: num
}, {
curr: stats,
prev: stats
});
fs.unwatchFile(filename);
watcher = fs.watch(filename, { persistent: bool }, (event: string, filename: string) => {
});
fs.exists(path, (exists: boolean) => {
});
bool = fs.existsSync(path);
fs.ensureDir(path, errorCallback);
fs.ensureDirSync(path);
fs.ensureFile(path, errorCallback);
@@ -259,24 +101,3 @@ fs.ensureSymlink(path, errorCallback);
fs.ensureSymlinkSync(path);
fs.emptyDir(path, errorCallback);
fs.emptyDirSync(path);
readStreeam = fs.createReadStream(path);
readStreeam = fs.createReadStream(path, {
flags: str,
encoding: str,
fd: num,
mode: num,
bufferSize: num
});
writeStream = fs.createWriteStream(path);
writeStream = fs.createWriteStream(path, {
flags: str,
encoding: str,
string: str
});
outputStream = fs.createOutputStream(path);
outputStream = fs.createOutputStream(path, {
flags: str,
encoding: str,
string: str
});
+7 -131
View File
@@ -8,39 +8,8 @@
///<reference path="../node/node.d.ts"/>
declare module "fs-extra" {
import stream = require("stream");
export * from "fs";
export interface Stats {
isFile(): boolean;
isDirectory(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
dev: number;
ino: number;
mode: number;
nlink: number;
uid: number;
gid: number;
rdev: number;
size: number;
blksize: number;
blocks: number;
atime: Date;
mtime: Date;
ctime: Date;
}
export interface FSWatcher {
close(): void;
}
export class ReadStream extends stream.Readable { }
export class WriteStream extends stream.Writable { }
//extended methods
export function copy(src: string, dest: string, callback?: (err: Error) => void): void;
export function copy(src: string, dest: string, filter: CopyFilter, callback?: (err: Error) => void): void;
export function copy(src: string, dest: string, options: CopyOptions, callback?: (err: Error) => void): void;
@@ -77,8 +46,6 @@ declare module "fs-extra" {
export function remove(dir: string, callback?: (err: Error) => void): void;
export function removeSync(dir: string): void;
// export function delete(dir: string, callback?: (err: Error) => void): void;
// export function deleteSync(dir: string): void;
export function writeJson(file: string, object: any, callback?: (err: Error) => void): void;
export function writeJson(file: string, object: any, options?: OpenOptions, callback?: (err: Error) => void): void;
@@ -88,98 +55,22 @@ declare module "fs-extra" {
export function writeJsonSync(file: string, object: any, options?: OpenOptions): void;
export function writeJSONSync(file: string, object: any, options?: OpenOptions): void;
export function rename(oldPath: string, newPath: string, callback?: (err: Error) => void): void;
export function renameSync(oldPath: string, newPath: string): void;
export function truncate(fd: number, len: number, callback?: (err: Error) => void): void;
export function truncateSync(fd: number, len: number): void;
export function chown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void;
export function chownSync(path: string, uid: number, gid: number): void;
export function fchown(fd: number, uid: number, gid: number, callback?: (err: Error) => void): void;
export function fchownSync(fd: number, uid: number, gid: number): void;
export function lchown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void;
export function lchownSync(path: string, uid: number, gid: number): void;
export function chmod(path: string, mode: number, callback?: (err: Error) => void): void;
export function chmod(path: string, mode: string, callback?: (err: Error) => void): void;
export function chmodSync(path: string, mode: number): void;
export function chmodSync(path: string, mode: string): void;
export function fchmod(fd: number, mode: number, callback?: (err: Error) => void): void;
export function fchmod(fd: number, mode: string, callback?: (err: Error) => void): void;
export function fchmodSync(fd: number, mode: number): void;
export function fchmodSync(fd: number, mode: string): void;
export function lchmod(path: string, mode: string, callback?: (err: Error) => void): void;
export function lchmod(path: string, mode: number, callback?: (err: Error) => void): void;
export function lchmodSync(path: string, mode: number): void;
export function lchmodSync(path: string, mode: string): void;
export function stat(path: string, callback?: (err: Error, stats: Stats) => void): void;
export function lstat(path: string, callback?: (err: Error, stats: Stats) => void): void;
export function fstat(fd: number, callback?: (err: Error, stats: Stats) => void): void;
export function statSync(path: string): Stats;
export function lstatSync(path: string): Stats;
export function fstatSync(fd: number): Stats;
export function link(srcpath: string, dstpath: string, callback?: (err: Error) => void): void;
export function linkSync(srcpath: string, dstpath: string): void;
export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err: Error) => void): void;
export function symlinkSync(srcpath: string, dstpath: string, type?: string): void;
export function readlink(path: string, callback?: (err: Error, linkString: string) => void): void;
export function realpath(path: string, callback?: (err: Error, resolvedPath: string) => void): void;
export function realpath(path: string, cache: string, callback: (err: Error, resolvedPath: string) => void): void;
export function realpathSync(path: string, cache?: boolean): string;
export function unlink(path: string, callback?: (err: Error) => void): void;
export function unlinkSync(path: string): void;
export function rmdir(path: string, callback?: (err: Error) => void): void;
export function rmdirSync(path: string): void;
export function mkdir(path: string, mode?: number, callback?: (err: Error) => void): void;
export function mkdir(path: string, mode?: string, callback?: (err: Error) => void): void;
export function mkdirSync(path: string, mode?: number): void;
export function mkdirSync(path: string, mode?: string): void;
export function readdir(path: string, callback?: (err: Error, files: string[]) => void ): void;
export function readdirSync(path: string): string[];
export function close(fd: number, callback?: (err: Error) => void): void;
export function closeSync(fd: number): void;
export function open(path: string, flags: string, mode?: string, callback?: (err: Error, fs: number) => void): void;
export function openSync(path: string, flags: string, mode?: string): number;
export function utimes(path: string, atime: number, mtime: number, callback?: (err: Error) => void): void;
export function utimesSync(path: string, atime: number, mtime: number): void;
export function futimes(fd: number, atime: number, mtime: number, callback?: (err: Error) => void): void;
export function futimesSync(fd: number, atime: number, mtime: number): void;
export function fsync(fd: number, callback?: (err: Error) => void): void;
export function fsyncSync(fd: number): void;
export function write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: NodeBuffer) => void): void;
export function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number;
export function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: NodeBuffer) => void ): void;
export function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number;
export function readFile(filename: string, encoding: string, callback: (err: Error, data: string) => void ): void;
export function readFile(filename: string, options: OpenOptions, callback: (err: Error, data: string) => void ): void;
export function readFile(filename: string, callback: (err: Error, data: NodeBuffer) => void ): void;
export function readFileSync(filename: string): NodeBuffer;
export function readFileSync(filename: string, encoding: string): string;
export function readFileSync(filename: string, options: OpenOptions): string;
export function writeFile(filename: string, data: any, encoding?: string, callback?: (err: Error) => void): void;
export function writeFile(filename: string, data: any, options?: OpenOptions, callback?: (err: Error) => void): void;
export function writeFileSync(filename: string, data: any, encoding?: string): void;
export function writeFileSync(filename: string, data: any, option?: OpenOptions): void;
export function appendFile(filename: string, data: any, encoding?: string, callback?: (err: Error) => void): void;
export function appendFile(filename: string, data: any,option?: OpenOptions, callback?: (err: Error) => void): void;
export function appendFileSync(filename: string, data: any, encoding?: string): void;
export function appendFileSync(filename: string, data: any, option?: OpenOptions): void;
export function watchFile(filename: string, listener: { curr: Stats; prev: Stats; }): void;
export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: { curr: Stats; prev: Stats; }): void;
export function unwatchFile(filename: string, listener?: Stats): void;
export function watch(filename: string, options?: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher;
export function exists(path: string, callback?: (exists: boolean) => void ): void;
export function existsSync(path: string): boolean;
export function ensureDir(path: string, cb: (err: Error) => void): void;
export function ensureDirSync(path: string): void;
export function ensureFile(path: string, cb: (err: Error) => void): void;
export function ensureFileSync(path: string): void;
export function ensureLink(path: string, cb: (err: Error) => void): void;
export function ensureLinkSync(path: string): void;
export function ensureSymlink(path: string, cb: (err: Error) => void): void;
export function ensureSymlinkSync(path: string): void;
export function emptyDir(path: string, callback?: (err: Error) => void): void;
export function emptyDirSync(path: string): boolean;
export interface CopyFilterFunction {
export interface CopyFilterFunction {
(src: string): boolean
}
@@ -188,6 +79,7 @@ declare module "fs-extra" {
export interface CopyOptions {
clobber?: boolean
preserveTimestamps?: boolean
dereference?: boolean
filter?: CopyFilter
}
@@ -200,20 +92,4 @@ declare module "fs-extra" {
fs?: any;
mode?: number;
}
export interface ReadStreamOptions {
flags?: string;
encoding?: string;
fd?: number;
mode?: number;
bufferSize?: number;
}
export interface WriteStreamOptions {
flags?: string;
encoding?: string;
string?: string;
}
export function createReadStream(path: string, options?: ReadStreamOptions): ReadStream;
export function createWriteStream(path: string, options?: WriteStreamOptions): WriteStream;
export function createOutputStream(path: string, options?: WriteStreamOptions): WriteStream;
}
+6 -1
View File
@@ -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] ]
}
]
}
}
+1 -4
View File
@@ -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
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="gijgo.d.ts" />
// Grid
$(() => {
this.grid = $('#grid').grid({
primaryKey: 'ID',
columns: [
{ field: 'ID', width: 50, sortable: true },
{ field: 'Name', sortable: true },
],
pager: { limit: 5, sizes: [2, 5, 10, 20] }
});
});
// Dialog
$(() => {
this.dialog = $('#playerModal').dialog({
autoOpen: false,
title: 'Player',
width: 400
});
});
+167
View File
@@ -0,0 +1,167 @@
// Type definitions for Gijgo v0.6.2
// Project: http://gijgo.com
// Definitions by: Atanas Atanasov <https://github.com/atatanasov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module Gijgo {
//Grid
interface GridPager {
limit?: number;
sizes?: Array<number>;
leftControls?: any;
rightControls?: any;
}
interface GridColumn {
align?: string;
cssClass?: string;
decimalDigits?: number;
editor?: any;
events?: any;
field?: string;
format?: string;
headerCssClass?: string;
hidden?: boolean;
icon?: string;
minWidth?: number;
priority?: number;
sortable?: boolean;
stopPropagation?: boolean;
title?: string;
tmpl?: string;
tooltip?: string;
type?: string;
width?: number;
}
interface GridDefaultParams {
direction?: string;
limit?: string;
page?: string;
sortBy?: string;
}
interface GridMapping {
dataField?: string;
totalRecordsField?: string;
}
interface GridSettings<Entity> {
//Configuration options
autoGenerateColumns?: boolean;
autoLoad?: boolean;
columns?: Array<GridColumn>;
dataSource?: any;
defaultColumnSettings?: GridColumn;
defaultParams?: GridDefaultParams;
detailTemplate?: string;
fontSize?: string;
mapping?: string;
minWidth?: number;
notFoundText?: string;
pager?: GridPager;
primaryKey?: string;
resizableColumns?: boolean;
resizeCheckInterval?: number;
responsive?: boolean;
selectionMethod?: string;
selectionType?: string;
showHiddenColumnsAsDetails?: boolean;
title?: string;
toolbarTemplate?: string;
uiLibrary?: string;
width?: number;
params?: any;
//Events
beforeEmptyRowInsert?: (e: any, $row: JQuery) => any;
cellDataBound?: (e: any, $wrapper: JQuery, id: string, column: GridColumn, record: Entity) => any;
cellDataChanged?: (e: any, $cell: JQuery, column: GridColumn, record: Entity, oldValue: any, newValue: any) => any;
columnHide?: (e: any, column: GridColumn) => any;
columnShow?: (e: any, column: GridColumn) => any;
dataBinding?: (e: any, records: Array<Entity>) => any;
dataBound?: (e: any, records: Array<Entity>, totalRecords: number) => any;
destroying?: (e: any) => any;
detailCollapse?: (e: any, detailWrapper: JQuery, record: Entity) => any;
detailExpand?: (e: any, detailWrapper: JQuery, record: Entity) => any;
initialized?: (e: any) => any;
pageChanging?: (e: any, newPage: number) => any;
pageSizeChange?: (e: any, newPage: number) => any;
resize?: (e: any, newWidth: number, oldWidth: number) => any;
rowDataBound?: (e: any, $row: JQuery, id: string, record: Entity) => any;
rowRemoving?: (e: any, $row: JQuery, id: string, record: Entity) => any;
rowSelect?: (e: any, $row: JQuery, id: string, record: Entity) => any;
rowUnselect?: (e: any, $row: JQuery, id: string, record: Entity) => any;
}
interface Grid<Entity, Params> extends JQuery {
addRow(record: Entity): Grid<Entity, Params>;
clear(showNotFoundText?: boolean): Grid<Entity, Params>;
count(): number;
destroy(keepTableTag?: boolean, keepWrapperTag?: boolean): void;
//get(position: number): Entity; //TODO: rename to getByPosition to avoid conflicts with jquery.get
getAll(): Array<Entity>;
getById(id: string): Entity;
getChanges(): Array<Entity>;
getSelected(): string;
getSelections(): Array<string>;
hideColumn(field: string): Grid<Entity, Params>;
makeResponsive(): void;
reload(params?: Params): Grid<Entity, Params>;
removeRow(id: string): Grid<Entity, Params>;
render(response: any): Grid<Entity, Params>;
selectAll(): Grid<Entity, Params>;
setSelected(id: string | number): Grid<Entity, Params>;
showColumn(field: string): Grid<Entity, Params>;
title(text: any): any;
unSelectAll(): Grid<Entity, Params>;
updateRow(id: string, record: Entity): Grid<Entity, Params>;
}
//Dialog
interface DialogSettings {
//Configuration options
autoOpen?: boolean;
closeOnEscape?: boolean;
draggable?: boolean;
height?: number | string;
maxHeight?: number;
maxWidth?: number;
minHeight?: number;
minWidth?: number;
modal?: boolean;
resizable?: boolean;
title?: string;
uiLibrary?: string;
width?: number;
//Events
closed?: (e: any) => any;
closing?: (e: any) => any;
drag?: (e: any) => any;
dragStart?: (e: any) => any;
dragStop?: (e: any) => any;
initialized?: (e: any) => any;
opened?: (e: any) => any;
opening?: (e: any) => any;
resize?: (e: any) => any;
resizeStart?: (e: any) => any;
resizeStop?: (e: any) => any;
}
interface Dialog extends JQuery {
close(): Dialog;
isOpen(): boolean;
open(): Dialog;
}
}
interface JQuery {
grid(settings: Gijgo.GridSettings<any>): Gijgo.Grid<any, any>;
grid<Entity>(settings: Gijgo.GridSettings<Entity>): Gijgo.Grid<Entity, any>;
grid<Entity, Params>(settings: Gijgo.GridSettings<Entity>): Gijgo.Grid<Entity, Params>;
dialog(settings: Gijgo.DialogSettings): Gijgo.Dialog;
}
+32 -3
View File
@@ -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');
}
})
});
+200 -93
View File
@@ -1,4 +1,4 @@
// Type definitions for Electron v1.2.2
// Type definitions for Electron v1.2.4
// Project: http://electron.atom.io/
// Definitions by: jedmao <https://github.com/jedmao/>, rhysd <https://rhysd.github.io>, Milan Burda <https://github.com/miniak/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -34,7 +34,7 @@ declare namespace Electron {
/**
* Emitted when the application has finished basic startup.
* On Windows and Linux, the will-finish-launching event
* is the same as the ready event; on OS X, this event represents
* is the same as the ready event; on macOS, this event represents
* the applicationWillFinishLaunching notification of NSApplication.
* You would usually set up listeners for the open-file and open-url events here,
* and start the crash reporter and auto updater.
@@ -81,7 +81,7 @@ declare namespace Electron {
*
* You should call event.preventDefault() if you want to handle this event.
*
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
on(event: 'open-file', listener: (event: Event, url: string) => void): this;
/**
@@ -90,12 +90,12 @@ declare namespace Electron {
*
* You should call event.preventDefault() if you want to handle this event.
*
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
on(event: 'open-url', listener: (event: Event, url: string) => void): this;
/**
* Emitted when the application is activated, which usually happens when clicks on the applications’s dock icon.
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
on(event: 'activate', listener: Function): this;
/**
@@ -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).
@@ -193,18 +197,18 @@ declare namespace Electron {
}): void;
/**
* On Linux, focuses on the first visible window.
* On OS X, makes the application the active app.
* On macOS, makes the application the active app.
* On Windows, focuses on the application’s first window.
*/
focus(): void;
/**
* Hides all application windows without minimizing them.
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
hide(): void;
/**
* Shows application windows after they were hidden. Does not automatically focus them.
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
show(): void;
/**
@@ -253,36 +257,36 @@ declare namespace Electron {
* Adds path to recent documents list.
*
* This list is managed by the system, on Windows you can visit the list from
* task bar, and on Mac you can visit it from dock menu.
* task bar, and on macOS you can visit it from dock menu.
*
* Note: This is only implemented on OS X and Windows.
* Note: This is only implemented on macOS and Windows.
*/
addRecentDocument(path: string): void;
/**
* Clears the recent documents list.
*
* Note: This is only implemented on OS X and Windows.
* Note: This is only implemented on macOS and Windows.
*/
clearRecentDocuments(): void;
/**
* Sets the current executable as the default handler for a protocol (aka URI scheme).
* Once registered, all links with your-protocol:// will be openend with the current executable.
* Once registered, all links with your-protocol:// will be opened with the current executable.
* The whole link, including protocol, will be passed to your application as a parameter.
*
* Note: This is only implemented on OS X and Windows.
* On OS X, you can only register protocols that have been added to your app's info.plist.
* Note: This is only implemented on macOS and Windows.
* On macOS, you can only register protocols that have been added to your app's info.plist.
*/
setAsDefaultProtocolClient(protocol: string): void;
/**
* Removes the current executable as the default handler for a protocol (aka URI scheme).
*
* Note: This is only implemented on OS X and Windows.
* Note: This is only implemented on macOS and Windows.
*/
removeAsDefaultProtocolClient(protocol: string): void;
/**
* @returns Whether the current executable is the default handler for a protocol (aka URI scheme).
*
* Note: This is only implemented on OS X and Windows.
* Note: This is only implemented on macOS and Windows.
*/
isDefaultProtocolClient(protocol: string): boolean;
/**
@@ -311,13 +315,13 @@ declare namespace Electron {
* @param webpageURL The webpage to load in a browser if no suitable app is
* installed on the resuming device. The scheme must be http or https.
*
* Note: This API is only available on Mac.
* Note: This API is only available on macOS.
*/
setUserActivity(type: string, userInfo: Object, webpageURL?: string): void;
/**
* @returns The type of the currently running activity.
*
* Note: This API is only available on Mac.
* Note: This API is only available on macOS.
*/
getCurrentActivityType(): string;
/**
@@ -339,12 +343,12 @@ declare namespace Electron {
disableHardwareAcceleration(): void;
commandLine: CommandLine;
/**
* Note: This API is only available on Mac.
* Note: This API is only available on macOS.
*/
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 {
/**
@@ -389,49 +393,49 @@ declare namespace Electron {
/**
* Cancel the bounce of id.
*
* Note: This API is only available on Mac.
* Note: This API is only available on macOS.
*/
cancelBounce(id: number): void;
/**
* Bounces the Downloads stack if the filePath is inside the Downloads folder.
*
* Note: This API is only available on Mac.
* Note: This API is only available on macOS.
*/
downloadFinished(filePath: string): void;
/**
* Sets the string to be displayed in the dock’s badging area.
*
* Note: This API is only available on Mac.
* Note: This API is only available on macOS.
*/
setBadge(text: string): void;
/**
* Returns the badge string of the dock.
*
* Note: This API is only available on Mac.
* Note: This API is only available on macOS.
*/
getBadge(): string;
/**
* Hides the dock icon.
*
* Note: This API is only available on Mac.
* Note: This API is only available on macOS.
*/
hide(): void;
/**
* Shows the dock icon.
*
* Note: This API is only available on Mac.
* Note: This API is only available on macOS.
*/
show(): void;
/**
* Sets the application dock menu.
*
* Note: This API is only available on Mac.
* Note: This API is only available on macOS.
*/
setMenu(menu: Menu): void;
/**
* Sets the image associated with this dock icon.
*
* Note: This API is only available on Mac.
* Note: This API is only available on macOS.
*/
setIcon(icon: NativeImage | string): void;
}
@@ -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.
*/
@@ -608,17 +615,17 @@ declare namespace Electron {
on(event: 'app-command', listener: (event: Event, command: string) => void): this;
/**
* Emitted when scroll wheel event phase has begun.
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
on(event: 'scroll-touch-begin', listener: Function): this;
/**
* Emitted when scroll wheel event phase has ended.
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
on(event: 'scroll-touch-end', listener: Function): this;
/**
* Emitted on 3-finger swipe.
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
on(event: 'swipe', listener: (event: Event, direction: SwipeDirection) => void): this;
on(event: string, listener: Function): this;
@@ -643,13 +650,23 @@ declare namespace Electron {
* Adds devtools extension located at path. The extension will be remembered
* so you only need to call this API once, this API is not for programming use.
* @returns The extension's name.
*
* Note: This API cannot be called before the ready event of the app module is emitted.
*/
static addDevToolsExtension(path: string): string;
/**
* Remove a devtools extension.
* @param name The name of the devtools extension to remove.
*
* Note: This API cannot be called before the ready event of the app module is emitted.
*/
static removeDevToolsExtension(name: string): void;
/**
* @returns devtools extensions.
*
* Note: This API cannot be called before the ready event of the app module is emitted.
*/
static getDevToolsExtensions(): DevToolsExtensions;
/**
* The WebContents object this window owns, all web page related events and
* operations would be done via it.
@@ -702,6 +719,10 @@ declare namespace Electron {
* @returns Whether the window is visible to the user.
*/
isVisible(): boolean;
/**
* @returns Whether the window is a modal window.
*/
isModal(): boolean;
/**
* Maximizes the window.
*/
@@ -741,7 +762,7 @@ declare namespace Electron {
* not included within the aspect ratio calculations.
* This API already takes into account the difference between a window’s size and its content size.
*
* Note: This API is available only on OS X.
* Note: This API is available only on macOS.
*/
setAspectRatio(aspectRatio: number, extraSize?: Dimension): void;
/**
@@ -794,31 +815,31 @@ declare namespace Electron {
isResizable(): boolean;
/**
* Sets whether the window can be moved by user. On Linux does nothing.
* Note: This API is available only on OS X and Windows.
* Note: This API is available only on macOS and Windows.
*/
setMovable(movable: boolean): void;
/**
* Note: This API is available only on OS X and Windows.
* Note: This API is available only on macOS and Windows.
* @returns Whether the window can be moved by user. On Linux always returns true.
*/
isMovable(): boolean;
/**
* Sets whether the window can be manually minimized by user. On Linux does nothing.
* Note: This API is available only on OS X and Windows.
* Note: This API is available only on macOS and Windows.
*/
setMinimizable(minimizable: boolean): void;
/**
* Note: This API is available only on OS X and Windows.
* Note: This API is available only on macOS and Windows.
* @returns Whether the window can be manually minimized by user. On Linux always returns true.
*/
isMinimizable(): boolean;
/**
* Sets whether the window can be manually maximized by user. On Linux does nothing.
* Note: This API is available only on OS X and Windows.
* Note: This API is available only on macOS and Windows.
*/
setMaximizable(maximizable: boolean): void;
/**
* Note: This API is available only on OS X and Windows.
* Note: This API is available only on macOS and Windows.
* @returns Whether the window can be manually maximized by user. On Linux always returns true.
*/
isMaximizable(): boolean;
@@ -832,11 +853,11 @@ declare namespace Electron {
isFullScreenable(): boolean;
/**
* Sets whether the window can be manually closed by user. On Linux does nothing.
* Note: This API is available only on OS X and Windows.
* Note: This API is available only on macOS and Windows.
*/
setClosable(closable: boolean): void;
/**
* Note: This API is available only on OS X and Windows.
* Note: This API is available only on macOS and Windows.
* @returns Whether the window can be manually closed by user. On Linux always returns true.
*/
isClosable(): boolean;
@@ -872,8 +893,8 @@ declare namespace Electron {
*/
getTitle(): string;
/**
* Changes the attachment point for sheets on Mac OS X.
* Note: This API is available only on OS X.
* Changes the attachment point for sheets on macOS.
* Note: This API is available only on macOS.
*/
setSheetOffset(offsetY: number, offsetX?: number): void;
/**
@@ -893,7 +914,7 @@ declare namespace Electron {
*/
isKiosk(): boolean;
/**
* The native type of the handle is HWND on Windows, NSView* on OS X,
* The native type of the handle is HWND on Windows, NSView* on macOS,
* and Window (unsigned long) on Linux.
* @returns The platform-specific handle of the window as Buffer.
*/
@@ -918,22 +939,22 @@ declare namespace Electron {
/**
* Sets the pathname of the file the window represents, and the icon of the
* file will show in window's title bar.
* Note: This API is available only on OS X.
* Note: This API is available only on macOS.
*/
setRepresentedFilename(filename: string): void;
/**
* Note: This API is available only on OS X.
* Note: This API is available only on macOS.
* @returns The pathname of the file the window represents.
*/
getRepresentedFilename(): string;
/**
* Specifies whether the window’s document has been edited, and the icon in
* title bar will become grey when set to true.
* Note: This API is available only on OS X.
* Note: This API is available only on macOS.
*/
setDocumentEdited(edited: boolean): void;
/**
* Note: This API is available only on OS X.
* Note: This API is available only on macOS.
* @returns Whether the window's document has been edited.
*/
isDocumentEdited(): boolean;
@@ -958,7 +979,7 @@ declare namespace Electron {
reload(): void;
/**
* Sets the menu as the window top menu.
* Note: This API is not available on OS X.
* Note: This API is not available on macOS.
*/
setMenu(menu: Menu): void;
/**
@@ -981,11 +1002,11 @@ declare namespace Electron {
setOverlayIcon(overlay: NativeImage, description: string): void;
/**
* Sets whether the window should have a shadow. On Windows and Linux does nothing.
* Note: This API is available only on OS X.
* Note: This API is available only on macOS.
*/
setHasShadow(hasShadow: boolean): void;
/**
* Note: This API is available only on OS X.
* Note: This API is available only on macOS.
* @returns whether the window has a shadow. On Windows and Linux always returns true.
*/
hasShadow(): boolean;
@@ -996,13 +1017,13 @@ declare namespace Electron {
*/
setThumbarButtons(buttons: ThumbarButton[]): boolean;
/**
* Shows pop-up dictionary that searches the selected word on the page.
* Note: This API is available only on OS X.
* Same as webContents.showDefinitionForSelection().
* Note: This API is available only on macOS.
*/
showDefinitionForSelection(): void;
/**
* Changes window icon.
* Note: This API is not available on OS X.
* Note: This API is not available on macOS.
*/
setIcon(icon: NativeImage): void;
/**
@@ -1042,6 +1063,25 @@ 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;
/**
* Sets parent as current window's parent window,
* passing null will turn current window into a top-level window.
* Note: This API is not available on Windows.
*/
setParentWindow(parent: BrowserWindow): void;
/**
* @returns The parent window.
*/
getParentWindow(): BrowserWindow;
/**
* @returns All child windows.
*/
getChildWindows(): BrowserWindow[];
}
type SwipeDirection = 'up' | 'right' | 'down' | 'left';
@@ -1055,6 +1095,13 @@ declare namespace Electron {
flags?: ThumbarButtonFlags[];
}
interface DevToolsExtensions {
[name: string]: {
name: string;
value: string;
}
}
interface WebPreferences {
/**
* Whether node integration is enabled.
@@ -1153,7 +1200,7 @@ declare namespace Electron {
*/
directWrite?: boolean;
/**
* Enables scroll bounce (rubber banding) effect on OS X.
* Enables scroll bounce (rubber banding) effect on macOS.
* Default: false.
*/
scrollBounce?: boolean;
@@ -1290,6 +1337,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.
@@ -1297,13 +1352,13 @@ declare namespace Electron {
alwaysOnTop?: boolean;
/**
* Whether the window should show in fullscreen.
* When explicitly set to false the fullscreen button will be hidden or disabled on OS X.
* When explicitly set to false the fullscreen button will be hidden or disabled on macOS.
* Default: false.
*/
fullscreen?: boolean;
/**
* Whether the window can be put into fullscreen mode.
* On OS X, also whether the maximize/zoom button should toggle full screen mode or maximize window.
* On macOS, also whether the maximize/zoom button should toggle full screen mode or maximize window.
* Default: true.
*/
fullscreenable?: boolean;
@@ -1336,6 +1391,16 @@ declare namespace Electron {
* Default: true.
*/
frame?: boolean;
/**
* Specify parent window.
* Default: null.
*/
parent?: BrowserWindow;
/**
* Whether this is a modal window. This only works when the window is a child window.
* Default: false.
*/
modal?: boolean;
/**
* Whether the web view accepts a single mouse-down event that simultaneously activates the window.
* Default: false.
@@ -1363,7 +1428,7 @@ declare namespace Electron {
backgroundColor?: string;
/**
* Whether window should have a shadow.
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
* Default: true.
*/
hasShadow?: boolean;
@@ -1589,7 +1654,7 @@ declare namespace Electron {
/**
* You are required to call this method before using other crashReporter APIs.
*
* Note: On OS X, Electron uses a new crashpad client, which is different from breakpad
* Note: On macOS, Electron uses a new crashpad client, which is different from breakpad
* on Windows and Linux. To enable the crash collection feature, you are required to call
* the crashReporter.start API to initialize crashpad in the main process and in each
* renderer process from which you wish to collect crash reports.
@@ -1812,7 +1877,7 @@ declare namespace Electron {
/**
* The value will be returned when user cancels the dialog instead of clicking the buttons of the dialog.
* By default it is the index of the buttons that have "cancel" or "no" as label,
* or 0 if there is no such buttons. On OS X and Windows the index of "Cancel" button
* or 0 if there is no such buttons. On macOS and Windows the index of "Cancel" button
* will always be used as cancelId, not matter whether it is already specified.
*/
cancelId?: number;
@@ -1832,9 +1897,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 +1917,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 +1964,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
@@ -2041,8 +2118,8 @@ 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 MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteandmatchstyle' | 'selectall' | 'delete' | 'minimize' | 'close' | 'quit' | 'togglefullscreen';
type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'front' | 'zoom' | 'window' | 'help' | 'services';
interface MenuItemOptions {
/**
@@ -2065,13 +2142,13 @@ declare namespace Electron {
*
* Platform notice:
* On Linux and Windows, the Command key would not have any effect,
* you can use CommandOrControl which represents Command on OS X and Control on
* you can use CommandOrControl which represents Command on macOS and Control on
* Linux and Windows to define some accelerators.
*
* Use Alt instead of Option. The Option key only exists on OS X, whereas
* Use Alt instead of Option. The Option key only exists on macOS, whereas
* the Alt key is available on all platforms.
*
* The Super key is mapped to the Windows key on Windows and Linux and Cmd on OS X.
* The Super key is mapped to the Windows key on Windows and Linux and Cmd on macOS.
*
* Available modifiers:
* Command (or Cmd for short)
@@ -2157,16 +2234,20 @@ declare namespace Electron {
*/
constructor();
/**
* Sets menu as the application menu on OS X. On Windows and Linux, the menu
* Sets menu as the application menu on macOS. On Windows and Linux, the menu
* will be set as each window's top menu.
*/
static setApplicationMenu(menu: Menu): void;
/**
* @returns The application menu if set, or null if not set.
*/
static getApplicationMenu(): Menu;
/**
* Sends the action to the first responder of application.
* This is used for emulating default Cocoa menu behaviors,
* usually you would just use the role property of MenuItem.
*
* Note: This method is OS X only.
* Note: This method is macOS only.
*/
static sendActionToFirstResponder(action: string): void;
/**
@@ -2176,7 +2257,7 @@ declare namespace Electron {
*/
static buildFromTemplate(template: MenuItemOptions[]): Menu;
/**
* Popups this menu as a context menu in the browserWindow. You can optionally
* Pops up this menu as a context menu in the browserWindow. You can optionally
* provide a (x,y) coordinate to place the menu at, otherwise it will be placed
* at the current mouse cursor position.
* @param x Horizontal coordinate where the menu will be placed.
@@ -2233,8 +2314,8 @@ declare namespace Electron {
*/
toDataURL(): string;
/**
* The native type of the handle is NSImage* on OS X.
* Note: This is only implemented on OS X.
* The native type of the handle is NSImage* on macOS.
* Note: This is only implemented on macOS.
* @returns The platform-specific handle of the image as Buffer.
*/
getNativeHandle(): Buffer;
@@ -2635,6 +2716,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';
@@ -3025,26 +3110,34 @@ declare namespace Electron {
/**
* @returns If the system is in Dark Mode.
*
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
isDarkMode(): boolean;
/**
* Subscribes to native notifications of OS X, callback will be called when the corresponding event happens.
* Subscribes to native notifications of macOS, callback will be called when the corresponding event happens.
* The id of the subscriber is returned, which can be used to unsubscribe the event.
*
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
subscribeNotification(event: string, callback: (event: Event, userInfo: Object) => void): number;
/**
* Removes the subscriber with id.
*
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
unsubscribeNotification(id: number): void;
/**
* Same as subscribeNotification, but uses NSNotificationCenter for local defaults.
*/
subscribeLocalNotification(event: string, callback: (event: Event, userInfo: Object) => void): number;
/**
* Same as unsubscribeNotification, but removes the subscriber from NSNotificationCenter.
*/
unsubscribeLocalNotification(id: number): void;
/**
* Get the value of key in system preferences.
*
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
getUserDefault(key: string, type: 'string' | 'boolean' | 'integer' | 'float' | 'double' | 'url' | 'array' | 'dictionary'): any;
/**
@@ -3065,17 +3158,17 @@ declare namespace Electron {
interface Tray extends NodeJS.EventEmitter {
/**
* Emitted when the tray icon is clicked.
* Note: The bounds payload is only implemented on OS X and Windows.
* Note: The bounds payload is only implemented on macOS and Windows.
*/
on(event: 'click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this;
/**
* Emitted when the tray icon is right clicked.
* Note: This is only implemented on OS X and Windows.
* Note: This is only implemented on macOS and Windows.
*/
on(event: 'right-click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this;
/**
* Emitted when the tray icon is double clicked.
* Note: This is only implemented on OS X and Windows.
* Note: This is only implemented on macOS and Windows.
*/
on(event: 'double-click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this;
/**
@@ -3095,27 +3188,27 @@ declare namespace Electron {
on(event: 'balloon-closed', listener: Function): this;
/**
* Emitted when any dragged items are dropped on the tray icon.
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
on(event: 'drop', listener: Function): this;
/**
* Emitted when dragged files are dropped in the tray icon.
* Note: This is only implemented on OS X
* Note: This is only implemented on macOS
*/
on(event: 'drop-files', listener: (event: Event, files: string[]) => void): this;
/**
* Emitted when a drag operation enters the tray icon.
* Note: This is only implemented on OS X
* Note: This is only implemented on macOS
*/
on(event: 'drag-enter', listener: Function): this;
/**
* Emitted when a drag operation exits the tray icon.
* Note: This is only implemented on OS X
* Note: This is only implemented on macOS
*/
on(event: 'drag-leave', listener: Function): this;
/**
* Emitted when a drag operation ends on the tray or ends at another location.
* Note: This is only implemented on OS X
* Note: This is only implemented on macOS
*/
on(event: 'drag-end', listener: Function): this;
on(event: string, listener: Function): this;
@@ -3141,12 +3234,12 @@ declare namespace Electron {
setToolTip(toolTip: string): void;
/**
* Sets the title displayed aside of the tray icon in the status bar.
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
setTitle(title: string): void;
/**
* Sets whether the tray icon is highlighted when it is clicked.
* Note: This is only implemented on OS X.
* Note: This is only implemented on macOS.
*/
setHighlightMode(highlight: boolean): void;
/**
@@ -3159,16 +3252,20 @@ declare namespace Electron {
content?: string;
}): void;
/**
* Popups the context menu of tray icon. When menu is passed,
* Pops up the context menu of tray icon. When menu is passed,
* the menu will showed instead of the tray's context menu.
* The position is only available on Windows, and it is (0, 0) by default.
* Note: This is only implemented on OS X and Windows.
* Note: This is only implemented on macOS and Windows.
*/
popUpContextMenu(menu?: Menu, position?: Point): void;
/**
* Sets the context menu for this icon.
*/
setContextMenu(menu: Menu): void;
/**
* @returns The bounds of this tray icon.
*/
getBounds(): Bounds;
}
interface Modifiers {
@@ -3643,6 +3740,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 macOS.
*/
showDefinitionForSelection(): void;
/**
* @returns The unique ID of this WebContents.
*/
@@ -3669,11 +3771,11 @@ declare namespace Electron {
interface ContextMenuParams {
/**
* x coodinate
* x coordinate
*/
x: number;
/**
* y coodinate
* y coordinate
*/
y: number;
/**
@@ -4428,6 +4530,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 macOS.
*/
showDefinitionForSelection(): void;
/**
* @returns The WebContents associated with this webview.
*/
@@ -4816,7 +4923,7 @@ declare namespace NodeJS {
* Sets the file descriptor soft limit to maxDescriptors or the OS hard limit,
* whichever is lower for the current process.
*
* Note: This API is only available on Mac and Linux.
* Note: This API is only available on macOS and Linux.
*/
setFdLimit(maxDescriptors: number): void;
/**
+319 -17
View File
@@ -1,28 +1,330 @@
// Type definitions for Globalize
// Type definitions for Globalize
// Project: https://github.com/jquery/globalize
// Definitions by: Aram Taieb <https://github.com/afromogli/>
// Definitions: https://github.com/afromogli/DefinitelyTyped
// Definitions by: Grégoire Castre <https://github.com/gcastre/>, Aram Taieb <https://github.com/afromogli/>
// 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;
/// <reference path="../cldr.js/cldr.js.d.ts" />
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;
+7
View File
@@ -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;
+5 -3
View File
@@ -39,7 +39,7 @@ interface HammerStatic
DIRECTION_VERTICAL: number;
DIRECTION_ALL: number;
Manager: HammerManager;
Manager: HammerManagerConstructor;
Input: HammerInput;
TouchAction: TouchAction;
@@ -95,10 +95,12 @@ interface HammerOptions extends HammerDefaults
}
interface HammerManagerConstructor {
new( element:HTMLElement, options?:any ):HammerManager;
}
interface HammerManager
{
new( element:HTMLElement, options?:any ):HammerManager;
add( recogniser:Recognizer ):Recognizer;
add( recogniser:Recognizer ):HammerManager;
add( recogniser:Recognizer[] ):Recognizer;
+2 -1
View File
@@ -77,8 +77,9 @@ interface HeatmapConfiguration {
/*
* The property name of the value/weight in a datapoint
* Default value: 'value'
*/
valueField: string;
valueField?: string;
}
/*
+2 -2
View File
@@ -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
+88
View File
@@ -0,0 +1,88 @@
///<reference path="./imagemapster.d.ts" />
///<reference path="../jquery/jquery.d.ts" />
const areaOptions: ImageMapster.AreaRenderingOptions = {
key: "foo",
includeKeys: "foo",
isMask: true,
toolTip: "tooltip",
};
const onClickData: ImageMapster.OnClickData = {
listTarget: $(),
key: "foo",
e: $.Event("click"),
selected: true,
}
const onMouseData: ImageMapster.OnMouseData = {
key: "foo",
selected: true,
e: $.Event("click"),
options: areaOptions,
};
const onGetListData: ImageMapster.OnGetListData = {
key: "foo",
value: "foo",
area: [{}],
options: areaOptions,
};
const onStateChangeData: ImageMapster.OnStateChangeData = {
key: "foo",
state: "highlight",
selected: true,
};
const onShowToolTipData: ImageMapster.OnShowToolTipData = {
toolTip: $(),
key: "foo",
selected: true,
areaOptions,
};
const bool = true;
const options: ImageMapster.Options = {
mapKey: "foo",
mapValue: "foo",
clickNavigate: true,
listKey: "foo",
listSelectedAttribute: "foo",
listSelectedClass: "foo",
wrapClass: "foo",
wrapCss: "foo",
mouseoutDelay: 123,
sortList: "asc",
configTimeout: 123,
scaleMap: true,
noHrefIsMask: true,
boundList: $(),
showToolTip: true,
toolTipContainer: $(),
toolTipClose: ["area-mouseout", "area-click", "tooltip-click", "image-mouseout"],
onClick: onClickData => {},
onMouseover: onMouseData => {},
onMouseout: onMouseData => {},
onGetList: onGetListData => $(),
onConfigured: bool => {},
onStateChange: onStateChangeData => {},
onShowToolTip: onShowToolTipData => {},
};
$("img").mapster(options)
$("img").mapster("select")
$("img").mapster("deselect")
$("img").mapster("set", true, options)
$("img").mapster("get", "foo")
$("img").mapster("highlight", true)
$("img").mapster("unbind", true)
$("img").mapster("snapshot")
$("img").mapster("rebind", options)
$("img").mapster("resize", 123, 123, 123)
$("img").mapster("keys", "foo", true)
$("img").mapster("keys", true)
$("img").mapster("set_options", options)
$("img").mapster("get_options", "foo", true)
$("img").mapster("tooltip", "foo");
+996
View File
@@ -0,0 +1,996 @@
// Type definitions for imagemapster 1.2.10
// Project: http://www.outsharked.com/imagemapster/
// Definitions by: delphinus <https://github.com/delphinus35/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
///<reference path="../jquery/jquery.d.ts" />
declare namespace ImageMapster {
type Select = "select";
type Deselect = "deselect";
type Set = "set";
type Get = "get";
type Highlight = "highlight";
type Unbind = "unbind";
type Resize = "resize";
type Snapshot = "snapshot";
type Rebind = "rebind";
type Keys = "keys";
type SetOptions = "set_options";
type GetOptions = "get_options";
type Tooltip = "tooltip";
type ToolTipCloseEvent = "area-mouseout" | "area-click" | "tooltip-click" | "image-mouseout";
type State = "highlight" | "select";
interface RenderingOptions {
/**
* fade effect - can only be applied to "render_highlight".
*
* Use a fade effect when highlighting areas on mouseover.
*/
fade?: boolean;
/**
* The duration of the fade-in effect, in milliseconds.
*/
fadeDuration?: number;
/**
* highlight areas on mouseover. When null (default), the behavior is
* disabled for mobile browsers. You can explicitly enable or disable
* it by setting this option to a boolean value.
*/
highlight?: boolean;
/**
* the map or an area on the map can be selected (or deselected).
*
* When true, the image map will function like a multiple-select menu.
* Users can click any area to select or deselect it. When applied to
* the entire map, it determines whether or not the click-selection
* functionality is enabled. When applied to an area, it determines
* whether that individual area (or group) can be selected. By default,
* the map and all areas are selectable.
*/
isSelectable?: boolean;
/**
* the map or area on the map can be deselected.
*
* Normally true, this option can be used to prevent users from
* unselecting items once they have been selected. When combined with
* singleSelect, the effect is that one and only one option can be
* selected at any given time. Users cannot deselect the active option.
* This provides a menu-like functionality. It is possible for zero
* items to be selected if this is the default state (or the only
* selected item is deselected programatically).
*/
isDeselectable?: boolean;
/**
* only one area can be selected at a time
*
* When true, only one or zero areas can be selected at any given time.
* If an area is selected and the user selects another area, the
* previously selected area will become deselected. Unlike
* "staticState", this property cannot be overridden by setting areas
* programatically, only one (or zero) areas can ever be selected when
* this option is true.
*/
singleSelect?: boolean;
/**
* the map or area is permanently in a selected or deselected state.
*
* When true or false, the map or area to which this option applies
* will be permanently selected or deselected. Typically this is more
* useful applied to individual areas that you want to exclude from the
* interactive part of the map.
*
* staticState forces an area to be always selected or deselected. If
* set, this will supercede isSelectable. Something with a staticState
* will always be in that state and it cannot be changed by the user.
* Note that when setting states programatically, this option will not
* be honored; it only affects user interaction.
*/
staticState?: boolean;
/**
* initial selection state of an area.
*
* The area in question is selected. To set default selections when
* creating a new mapster, use this option for a specific area (see
* above).
*/
selected?: boolean;
/**
* Use an alternate image of the same size as the imagemap as the
* source for highlight or select effects.
*
* When specified, the mapster will highlight areas using the image
* data obtained from the same area in an alternate image, instead of
* using a fill effect to highlight or select the area. This feature is
* currently available in browsers with HTML5 canvas support. In
* practical terms, this means it will work in all commonly used
* browsers except IE 8 or lower.
*
* If this feature is enabled when an unsupported browser is used, it
* will fall back to the normal highlight method.
*
* The fill, stroke and opacity effects can be specified independently
* from those used for the normal higlight effect. This ensures that
* when your page is viewed with a non-supported browser, you can still
* control the rendering as would be appropriate for a normal
* fill/stroke effect, which may be different from when you're using an
* alternate image.
*/
altImage?: string;
altImageFill?: boolean;
altImageStroke?: boolean;
altImageOpacity?: number;
/**
* Areas should be flood-filled when moused over or highlighted.
*/
fill?: boolean;
/**
* The color used for flood fill.
*/
fillColor?: string;
fillColorMask?: string;
/**
* The opacity of the fill. This is a number from 0 to 1.
*/
fillOpacity?: number;
/**
* Areas should be outlined when moused over or highlighted.
*/
stroke?: boolean;
/**
* The color of the outline.
*/
strokeColor?: string;
/**
* The opacity of the outline.
*/
strokeOpacity?: number;
/**
* The width of the outline.
*/
strokeWidth?: number;
/**
* The options below control the way highlighted areas are rendered.
* Each can be applied globally to the map, or to each element, using
* the areas option to pass area-specific options. These options apply
* to either highlighted or selected areas. Highlighting occurs when
* the mouse enters an area on the image map. Selection occurs when an
* area is clicked, and selection is enabled. These options will be
* applied to both situations if present in the root of the options
* object. They can also be applied to one or the other situations
* specifically using the render_highlight and render_select options.
*/
render_highlight?: string | RenderingOptions;
render_select?: string | RenderingOptions;
}
interface AreaRenderingOptions extends RenderingOptions {
key: string;
/**
* when rendering an area or area group, also render the areas in the
* other group (or groups) specified
*
* This is an area-specific option that allows you to create
* supergroups. A supergroup is a collection of groups that will all be
* highlighted simultaneously, but only when the area that defines the
* supergroup is moused over or activated through code.
*
* When the area for which this option has been set is activated, all
* the areas specified in the includeKeys list will also be rendered.
* This is a one-way relationship. Defining a supergroup in an area
* causes all the other groups to be highlighted, but not the other way
* around.
*
* A typical use of this is to define areas that you want to be
* highlighted when the mouse enters some specific area, but that you
* do not want to be highlighted on their own if the target area is
* moused over. This could be a hidden menu, for example: you want the
* menu to display when the hotspot is moused over, but when it's
* hidden, mousing over the menu area itself should have no effect.
*/
includeKeys?: string;
/**
* the area is a mask rather than a highlighted area.
*
* Normally, every area in an imagemap is an active area, and would be
* highlighted when moused over (unless its behavior was otherwise
* specified with staticState). The isMask option allows you to
* identify an area as being a mask. When a mask is part of an area
* group, the masked area will be specifically excluded from the
* rendering of a highlight or selected state.
*
* This is usually used in conjunction, or instead of, the nohref
* attribute of the area tag. When nohref is specified on an area tag,
* that area is specifically excluded from the hotspot of any area that
* encompasses it. It will not respond to mouse events, and will not be
* highlighted. This can be used to create "holes" in hotspots. By
* default, ImageMapster will treat any area with nohref or no href tag
* as masks, the same as if this option had been applied.
*
* Sometimes you won't be able to use nohref to identify something as a
* mask, for example, if you intend to re-use an area has both a mask,
* and an independent hotspot. This would be typical if you wanted to a
* selectable area that was completely included within another
* selectable area, but functioned independently, such as concentric
* circles. In this case, you would need to identify the inner circle
* as both a mask, and a hotspot. The nohref attribute would make it
* not act as a hotspot, and only function as a mask. You couldn't also
* select the inner area. You can solve this problem by including the
* inner circle in two different groups - one group which is a mask for
* the main area, and another which is an independent selectable area.
* You can specify different options for each group, so even though
* it's just one area, it can function as two completely independent
* ones.
*
* There may also be situations where you do not want an area marked
* with nohref to be treated as a mask. For example, given "area1" and
* "area2," you may want to create a configuration where mousing over
* "area1" causes both "area1" and "area2" to be highlighted, but
* "area2" should not be highlighted on its own when it is moused over.
* In this situation, you'll need to use "nohref" to prevent the hover
* behavior for the area, but you still want it to be treated normally
* when it's rendered as a result of mousing over "area1." You can
* accomplish this using the noHrefIsMask global option, below.
*
* Generally, masked areas will appear as a window to the underlying
* image. If stroke is in effect, the stroke will be rendered for the
* mask as well as the areas, to create both inner and outer borders.
* You can always specifically enable or disable this, or any other
* effect, for any area as desired.
*
*/
isMask?: boolean;
/**
* tool tip data for an area
*
* When this area-specific option is present and showToolTips = true, a
* toolTipContainer will be created this will be inserted into it,
* either as inner text (if only text as passed) or as HTML if a jQuery
* object is passed. In order to pass anything other than plain text
* using this option you must use a jQuery object. Any string will be
* treated as plain text (and special characters rendered correctly).
*/
toolTip?: string;
}
interface OnClickData {
/**
* $(item) from boundList
*/
listTarget?: JQuery;
/**
* mapKey for this area
*/
key: string;
e: JQueryEventObject;
selected: boolean;
}
interface OnStateChangeData {
/**
* map key
*/
key: string;
state: "highlight" | "select";
/**
* indicating the current state (following the event)
*/
selected: boolean;
}
interface OnMouseData {
/**
* area key
*/
key: string;
/**
* true if area is currently selected
*/
selected: boolean;
e: JQueryEventObject;
options: AreaRenderingOptions;
}
interface OnGetListData {
/**
* primary mapKey for this area or area group
*/
key: string;
/**
* mapValue for this area or group
*/
value: string;
/**
* array of areas that make up this group
*/
area: any[];
options: AreaRenderingOptions;
}
interface OnShowToolTipData {
/**
* jQuery object of the tooltip container
*/
toolTip: JQuery;
/**
* map key for this area
*/
key: string;
/**
* current state of the area
*/
selected: boolean;
areaOptions: AreaRenderingOptions;
}
interface Options extends RenderingOptions {
/**
* an attribute identifying each imagemap area.
*
* If specified, this refers to an attribute on the area tags that will
* be used to group them logically. Any areas containing the same
* mapKey will be considered part of a group, and rendered together
* when any of these areas is activated. If you don't want this
* functionality, ensure each key is unique. When mapKey is omitted,
* then each area is considered to be independent from the other and no
* grouping is applied.
*
* When mapKey is present, any area tags that are missing this
* attribute will be excluded from the image map e ntirely. This is
* functionally identical to setting staticState=false for these areas,
* except they will be inaccessible through the API.
*
* ImageMapster will work with any attribute you identify as a key. If
* you wish to maintain HTML compliance, it's recommeded that you use
* attribute names starting with "data-", for example, data-mapkey. Any
* such names are legal for the HTML5 document type. If you are using
* older document types, the class attribute is part of the HTML spec
* for area and will not cause any visual effects, so this is also a
* good choice. It is not recommended to use id, since the values of
* this attribute must be unique. title and alt also will cause
* possibly undesired side effects.
*
* You can specify more than one value in the mapKey attribute,
* separated by commas. This will cause an area to be a member of more
* than one group. The area may have different options in the context
* of each group. When the area is physically moused over, the first
* key listed will identify the group that's effective for that action.
*/
mapKey?: string;
/**
* an attribute on each area tag containing additional descriptive
* information about an area.
*
* This option is applicable only when using onGetList. When set, the
* data provided to the callback function will include the value of
* this attribute for each group. This can be used to simplify building
* a list with associated information, without having to match against
* another resource. It also ties this information to the image map
* itself. It is not required to use this option when using onGetList.
*
* For example, you could set mapValue: 'data-statename' to an imagemap
* of the united states, and add an attribute to your areas that
* provided the full name of each state, e.g. data-statename="Alaska".
* This text would be included in the onGetList callback, and so you
* could use it to construct an external list of states.
*
* If there are grouped areas (areas with the same key), then the value
* from the first area found with data in this attribute will be used.
*/
mapValue?: string;
/**
* Clicking on a link should cause the browser to navigate to the href
* whenever it's not a hash sign (#). Version 1.2.4.050 and later
*
* By default, ImageMapster will prevent the default browser behavior
* in image maps, and "select" areas when they are clicked. If you want
* to navigate to the url for an area, use this option. When enabled,
* all areas that have an href attribute, and its value is not empty or
* "#" (just a hashtag).
*
* When area grouping is used, if an href is present for any area in
* the primary group, this will be used as the navigation target. This
* way you don't need to copy the url for every area in groups, rather,
* you can include it on just one, and clicking any area will cause the
* appropraite navigation.
*/
clickNavigate?: boolean;
/**
* an attribute on items in a boundList that corresponds to the value
* of the mapKey attributes.
*
* This is used to synchronize the actions on the imagemap with the
* actions on a boundList. Each value should match a value from the
* imageMap mapKey tag. Any item in the boundList with missing or
* mismatched data will be ignored.
*/
listKey?: string;
/**
* attribute to set or remove when an area is selected or deselected
*
* If boundList is present, when a map area is selected, set or remove
* this attribute on the list element that matches that area based on
* their respective keys.
*/
listSelectedAttribute?: string;
/**
* a class to add or remove when an area is selected or deselected
*
* If a boundList is present, when a map area is selected, this class
* is added or removed from the corresponding list element. This can be
* used to easily create any kind of associated action when areas on
* the map are changed.
*/
listSelectedClass?: string;
/**
*
* define area-specific options; each object in the array must contain
* a "key" property identifying a valid mapKey, and additional
* rendering options specific to that area or group
*/
areas?: AreaRenderingOptions[],
/**
* add "classname" class to the wrapper created around the image, or
* copy classes from the image if "true"
*/
wrapClass?: string | boolean;
/**
* add CSS to the wrapper created around the image
*/
wrapCss?: string | boolean;
/**
* delay removing highlight when mouse exits an area (1.2.5b36)
*
* Normally, when the user's mouse pointer exits an area, the highlight
* effect is removed immediately. This behavior can be changed with
* this option. Setting it to a positive number causes a delay of n
* milliseconds before the effect is removed. Setting to -1 causes the
* effect to remain active until another hotspot is entered (e.g., it
* will only be removed when superceded by a different area being
* highlighted).
*
* When using mouseoutDelay, the onMouseover event will still be fired
* at the time the user's mouse pointer leaves the area. However, the
* onStateChange event will be delayed until the highlight is actually
* removed.
*
* Whether or not you are using mouseoutDelay, only one area can be
* highlighted at a time. That is, whenever the mouse pointer moves
* onto a new active area, any previously highlighted area will become
* un-highlighted, regardless of any delay in effect. Hovering over a
* new area will always supercede any delay and cause the new area (and
* only the new area) to be highlighted at that time. So, for dense
* imagemaps where most areas adjoin one another, this option may not
* have much effect within the boundaries of the imagemap. Rather, it
* is intended to help keep the higlights active for imagemaps that are
* sparse, or have very small areas.
*/
mouseoutDelay?: number;
/**
* sort the values before calling onGetList
*
* If a non-false value or "asc" is passed, the list will be sorted in
* ascending order by the area value from mapValue. If "desc" is
* passed, the list will be sorted in descending order.
*/
sortList?: boolean | "asc" | "desc";
/**
* time (in milliseconds) to wait for images to load before giving up
*
* When first bound, ImageMapster has to wait for the source image,and
* any altImage images to load before it can finish binding. This is
* necessary because otherwise it's not alwasy possible to know the
* native size of the images. After this period of time, ImageMapster
* will give up. If you have particularly large pages or images, you
* may want to increase this to account for long load times.
*/
configTimeout?: number;
/**
* Automatically scale imagemaps to match the size of a
* dynamically-scaled image.
*
* When you render an image, you can optionally define a size through
* CSS or using the "height" and "width" attributes. If omitted, the
* image will be displayed in its native size. If included, browsers
* will automatically resize the image to display in the dimensions you
* have provided.
*
* Starting with 1.1.3, ImageMapster will automatically recalculate all
* area data to match the effective size of the image. This means that
* you can set the size of your image to anything you want and
* ImageMapster will work with no changes at all needed to the "area"
* data.
*
* If this behavior is not desired for some reason, this can be
* disabled by setting this option to false.
*/
scaleMap?: boolean;
/**
* Treat areas containing the onhref attribute (or missing the href
* attribute) as masks. This is true by default.
*
* Set this to "false" to disable automatic masking of these areas. You
* can control them explicitly by creating independent groups for areas
* you wish to mask and assigning the isMask area-specific option when
* using this option.
*
* There are some things to be aware of when using nohref and masking:
*
* * You must put the area that include the nohref attribute before
* other areas that overlap it, or it will be ignored.
*
* * You should also explicitly omit the href tag when using nohref.
*
* * Due to limitations in rendering with VML (e.g. Internet Explorer
* 6-8), it is not possible to create a true mask, which would allow
* the underlying image to show through the masked area. Instead, the
* "masked" areas are rendered on top of the highlighted area in a
* different color. This can be specified for each area (see the
* fillColorMask option below) to create the best possible effect.
*/
noHrefIsMask?: boolean;
/**
* a jQuery object whose elements are bound to the map.
*
* boundList can be any list of objects. To be bound to the map, they
* must contain an attribute whose name is identified by the option
* listKey, and whose value matches the value in an area tag's mapKey
* attribute. If more than one element in the list has the same value,
* the action will affect all matching elements.
*/
boundList?: JQuery;
/**
* enable tooltips
*
* When showToolTip is true, mapster will look for a property called
* toolTip in the areas option for a an area. If present, a tool tip
* dialog will be shown on mouseover for that area. It will
* automatically be closed according to the behavior specified by
* toolTipClose. This option does not apply at the item level, but
* rather enables tooltips for the entire map. At the item level, only
* the presence of tooltip data is necessary for a tooltip to appear.
*/
showToolTip?: boolean;
/**
* HTML describing the popup that will be created for tooltips.
*
* A div with some simple styling is included as the default tooltip
* container. This can be replaced with anything using this option.
*
* When tooltips are rendered, the code attempts to determine the best
* place for it. It will try to position it in near the top-left part
* of the area, and continue to try other corners in order to render it
* within the confines of the container where the image map resides. If
* it can't be placed within the image, it will be placed in the
* lower-right corner and extend outside the image.
*/
toolTipContainer?: string | JQuery;
/**
* specify the behavior that causes a toolTip to close.
*
* This option should be passed an array of strings that define the
* events that cause active tooltips to close. The array can include
* one or more of the following stings:
*
* 'area-mouseout' - tooltips close when the mouse pointer leaves the
* area that activated it. This is the default.
*
* 'area-click' - tooltips close when another area (or the same one) is
* clicked
*
* 'tooltip-click' - tooltips close when the tooltip itself is clicked
* anywhere
*
* 'image-mouseout' - tooltips close when the mouse pointer leaves the
* image itself.
*
* Under any circumstances, active tooltip will disappear when a new
* one is created. You don't have to define an automatic closing
* behavior; setting this option to an empty array will result in
* tooltips never closing, leaving it to you to close them manually
* though the tooltip method.
*/
toolTipClose?: ToolTipCloseEvent[];
/**
* callback when a hotspot area is clicked. Return false to cancel
* default select action, or true to navigate to the 'href'
*/
/**
* a callback when an area is clicked.:silent doautocmd FocusLost %
*
* This event occurs when the usual click event happens, but includes
* data from the mapster about the area:
*
* This can be used to perform additional actions on a click without
* binding another event and having to obtain information manually.
*/
onClick?: (data: OnClickData) => void;
/**
* callback when mouse enters a bound area.
*
* This function is called when the mouse enters a bound area.
*/
onMouseover?: (data: OnMouseData) => void;
/**
* callback when mouse leavesd a bound area.
*
* Callback when the mouse leaves a bound area. The data structure
* passed to the callback is the same as onMouseover.
*/
onMouseout?: (data: OnMouseData) => void;
/**
* a callback on mapster initialization that provides summary data
* about the image map, and expects a jQuery list to be returned.
*
* This callback allows you to dynamically provide a boundList based on
* summary data from the imagemap itself, rather than providing the
* list up front. The event passes an array of AreaData objects
*
* The client should return a jQuery object containing all the elements
* that make up the bound list, the same as if it was assigned
* manually.
*/
onGetList?: (data: OnGetListData) => JQuery;
/**
* a callback when the mapster has finished initial configuration
*
* This event is fired when the mapster configuration completes. When
* control execution continues after a first-time bind operation, the
* mapster is not guaranteed to be configured, because images are
* loaded asynchronously by web browsers. If a mapster is bound to an
* image that is not yet loaded, it will attempt to rebind every 200
* milliseconds. This event will be fired when it is eventually
* successful, or the length of time specified by configTimeout is
* exceeded (default of ten seconds).
*
* The altImage option will also increase the time needed to configure,
* because the alternate image is loaded by the client at configure
* time to ensure it is available immediately when needed.
*/
onConfigured?: (success: boolean) => void;
/**
* callback when area state is changed (either highlight or select).
*
* onStateChange can be used to get more specific information than the
* mouseover or click events.
*/
onStateChange?: (data: OnStateChangeData) => void;
/**
* callback when a toolTip is created
*
* This can be used to control tooltip closing behavior directly, if
* desired.
*/
onShowToolTip?: (data: OnShowToolTipData) => void;
}
}
interface JQuery {
/**
*
* All images in the jQuery object will be bound. The specific example
* above will attempt to bind to all images present on the page. Each image
* must be bound to an image map identified with the usemap attribute. If
* there is no usemap attribute, or it does not refer to a valid map, then
* the image will be ignored. Therefore you can use this syntax to activate
* all imagemaps on a page. Because pages often contain many images,
* though, it will be faster to select just the image you are targeting
* using a more specific selector.
*
* Images are often not completely loaded when script execution begins.
* ImageMapster will ensure that all images are loaded before it permits
* interaction from the client. If an alternate image is specified, this
* will also be preloaded.
*
* Because images are loaded asynchronously, code execution will often
* return to your script before the ImageMapster is available. If you apply
* other methods to it (such as selecting or deselecting areas), these
* commands will be queued until the image has been loaded, and then
* executed automatically. So you don't need to worry about using callbacks
* for initial configuration. You can assign a function to a callback when
* configuration is complete if needed to perform other setup activities on
* the page.
*/
mapster(options?: ImageMapster.Options): JQuery;
/**
* select: Cause an area to become selected. This is similar to a user
* click, but will not cause a click event to be fired.
*
* Programatically select elements from the image map. The programmatic
* selection/deselection methods will not honor the staticState property.
*/
mapster(method: ImageMapster.Select): void;
/**
* deselect: Cause an area to become deselected
*
* The opposite of select, this causes an area to become deselected. If it
* was not previously selected, nothing changes.
*/
mapster(method: ImageMapster.Deselect): void;
/**
* set: select or deselect an area
*
* Select or deselect elements from jQuery objects wrapping "area" tags on
* the map based on truthiness of selected. If the area represents a bound
* area on the imagemap, it will be selected or deselected. The method can
* be called from an AREA, or from a bound image, passing a specific key as
* a 2nd parameter
*
* If the selected parameter is omitted (or anything other than "true" or
* "false") then the state of each area will be toggled.
*
* You can include an object containing rendering options as the last
* parameter. When present, these will supercede the default and
* area-specific rendering options.
*/
mapster(method: ImageMapster.Set, selected: boolean, options: ImageMapster.RenderingOptions): JQuery;
mapster(method: ImageMapster.Set, options: ImageMapster.RenderingOptions): JQuery;
/**
* get: get keys for all selected areas
*
* When no "key" parameter is included, returns a comma-separated list of
* keys representing the areas currently selected. If specified, returns
* true or false indicating whether the area specified is selected.
*/
mapster(method: ImageMapster.Get, key?: string): string | boolean;
/**
* highlight: highlight, clear, or return highlight state
*
* This method is used to control or obtain the current highlight state.
* Setting the highlight does not mimic a mouseover, rather, it only sets
* the highlight. Events and tooltips will not be activated. Even using
* these methods, it is not possible to highlight more than one area at a
* time. If another area is highlighted programatically, any existing
* highlight will be removed.
*
* Once set this way, the highlight will be removed when any user-event
* that would normally cause a highlight to be removed occurs (e.g. moving
* the mouse into any area), or it is removed programatically.
*/
mapster(method: ImageMapster.Highlight, flag?: string | boolean): void;
/**
* unbind: unbind ImageMapster from an image
*
* Removes the ImageMapster binding from an image and restores it to its
* original state. All visible elements (selections, tooltips) will be
* removed.
*
* If the optional "preserveState" parameter is true, the selection overlay
* and any active tooltips will be preserved. Tooltips can still be
* dismissed by a user click, but once unbound, the selection states can no
* longer be controlled either by the user or programatically. To remove
* them, the actual DOM elements must be removed.
*
* Notes: When a mapster is first bound, several things happen. A div
* element is created which wraps the image. A copy is made of the original
* image, and the original image is set be transparent. This allows
* creating visible elements for the selections & highlights without
* interfering with the image map. Additionally, canvas elements are
* created (for HTML5 browsers), or a VML elements are created for Internet
* Explorer, to render the effects. Profile information about each bound
* image map is stored in memory, and finally, event handlers are bound to
* the image map.
*
* The "unbind" method cleans up these resources: it removes the wrapper,
* restores the image to its original visibility state, and releases
* internal resources. When using 'preserveState', the internal resources
* are cleaned up and event handling is disabled, but HTML elements are not
* removed. Each element created by ImageMapster is assigned a class of
* "mapster_el", which can be used to target them for later removal, though
* it is not easy to complete this process manually because of the wrapper
* and styles applied during configuration, which will be left intact when
* using "preserveState."
*/
mapster(method: ImageMapster.Unbind, preserveState?: boolean): JQuery;
/**
* snapshot: take a "snapshot" of the current selection state, and reset
* ImageMapster
*
* This option is similar to unbind with preserveState. After a snapshot,
* any active selections will still appear as they did at the time of the
* snapshot, but they are no longer part of the ImageMapster. This is
* useful for configuring an initial state, or creating complex
* representations that may not be easily accomplished with area
* configuration options.
*
* For example, you could bind in image with a specific set of options;
* programatically select some areas; and take a snapshot; then set new
* options that cause a different rendering mode. This way you could have
* certain areas appear differently from the selection highlight, but be
* "highlighted again" using the new rendering options. Any effects in
* place at the time of the snapshot essentially become part of the image
* and are not affected by future operations.
*/
mapster(method: ImageMapster.Snapshot): JQuery;
/**
* rebind: rebind ImageMapster with new options
*
* This method is similar to set_options, in that its purpose is to change
* options for an existing bound map. However, unlike set_options rebind
* will immediately apply all the new options to the existing map. This
* means that rendering options will change areas that are already selected
* to be rendered with the new options. If you pass area-specific options,
* these will also be applied, e.g. you could cause new areas to be
* selected by passing selected: true in an area specific options.
*
* set_options, in contrast only changes the options, and does not apply
* them to any existing data. When using set_options the new options only
* apply to future actions.
*/
mapster(method: ImageMapster.Rebind, options: ImageMapster.Options): JQuery;
/**
* resize: change the size of the image and map
*
* This will resize the image map to the dimensions specified. Note that
* either width or height should be passed, and the other will be
* calculated in the same aspect ratio as the original image. If you pass
* both, only the width will be used to calculate the new dimensions: the
* proportions must remain the same as the original image. (Though I intend
* to allow scaling without constraining proportions, it will be difficult
* to make work for certain shapes -- e.g. circles, which would have to
* become ovals).
*
* This method will recalculate and re-render the entire imagemap, so it
* will work exactly the same under the new sizing scheme. When the image
* is unbound, the imagemap will be restored to its original condition.
*
* When using HTML5 canvases, any existing selections, etc. will be
* preserved during the animation. VML data cannot be resized dynamically,
* however, so in IE<9 the selections will be erased, then redrawn when the
* animation is complete.
*/
mapster(method: ImageMapster.Resize, width: number, height: number, duration?: number): JQuery;
/**
* keys: get the primary mapKey (or comma-separated list of keys) for an
* area, set of areas, or key group. Version 1.2.4.050
*
* This method allows you to obtain the primary mapKey (or keys) associated
* with another key, or one or more areas. If the all parameter is true,
* the method returns all keys or groups that include the area.
*
* When using area groups, it is possible for more than one key to be
* associated with a map area. It's also possible for an area to be
* highlighted from code as part of a group, but be inaccessible to the
* end-user. This is because area groups are separate physical entities
* from the areas defined by their primary key. They can have different
* options, and are highlighted independently. Note: the way area groups
* work is not well documented here yet. I am working on a more
* comprehensive tutorial for the site. In the meantime please see this
* example which describes area groups in detail, and shows how they work
* through an active demonstration.
*
* There are reasons you may want to be able to access the primary keys
* that make up an area group directly. Perhaps you want to select a group
* of areas using the options from a group - but not as a separate group.
* Perhaps you want to be able to compare the area clicked against a group
* you have defined to take some action if the area is a member of a
* certain group. This method provides access to that information.
*
* This method allows working with groups in a variety of ways by providing
* access to a complete list of primary keys in any group, or all keys
* which contain a given primary key.
*/
mapster(method: ImageMapster.Keys, key: string, all?: boolean): string | string[];
mapster(method: ImageMapster.Keys, all: boolean): string | string[];
/**
* set_options: set active options
*
* When called without the "options" parameter, returns an object with all
* active options. When the parameter is included, the active options are
* updated for the imagemap, and any area options are merged with existing
* area options. Unlike "rebind", this will not rebind or reapply any
* options, but only update the state. This may affect future actions, but
* it will not change any existing state information.
*/
mapster(method: ImageMapster.SetOptions, options?: ImageMapster.Options): JQuery;
/**
* get_options: get active options
*
* When called with no parameters, returns the options that the mapster was
* configured using. When called with a single key it returns the
* area-specific options assigned to that area. The final parameter
* effective determines whether the actual options in effect for this area,
* or the specific options assigned are returned.
*
* Areas inherit the global options assigned, but can be overridden by
* area-specific options. The "effective" options contain all options
* including those that are inherited, as well as any specifically assigned
* to the area.
*/
mapster(method: ImageMapster.GetOptions, key?: string, effective?: boolean): ImageMapster.Options | ImageMapster.AreaRenderingOptions;
/**
* tooltip: show/hide tooltips from code
*
* See the tooltip options section below for options to control how
* tooltips appear and are dismissed.
*
* This method can be used to manipulate tooltips from code. If the global
* showToolTip option is false, these methods will still work, so you have
* the ability to control tooltips bound to areas completely using your own
* logic, if desired. These methods can also be used to have better control
* over events needed to close the tooltip, e.g. you could have no tooltip
* closing event, but add a "close" button to your contianer that will
* cause the tooltip to close when clicked.
*/
mapster(method: ImageMapster.Tooltip, key?: string): JQuery;
}
@@ -0,0 +1,159 @@
/// <reference path="./inversify-binding-decorators.d.ts" />
import { inject, Kernel } from "inversify";
import { autoProvide, makeProvideDecorator, makeFluentProvideDecorator } from "inversify-binding-decorators";
module decorator {
let kernel = new Kernel();
let provide = makeProvideDecorator(kernel);
interface INinja {
fight(): string;
sneak(): string;
}
interface IKatana {
hit(): string;
}
interface IShuriken {
throw(): string;
}
let TYPE = {
IKatana: "IKatana",
INinja: "INinja",
IShuriken: "IShuriken"
};
@provide(TYPE.IKatana)
class Katana implements IKatana {
public hit() {
return "cut!";
}
}
@provide(TYPE.IShuriken)
class Shuriken implements IShuriken {
public throw() {
return "hit!";
}
}
@provide(TYPE.INinja)
class Ninja implements INinja {
private _katana: IKatana;
private _shuriken: IShuriken;
public constructor(
@inject("IKatana") katana: IKatana,
@inject("IShuriken") shuriken: IShuriken
) {
this._katana = katana;
this._shuriken = shuriken;
}
public fight() { return this._katana.hit(); };
public sneak() { return this._shuriken.throw(); };
}
let ninja = kernel.get<INinja>(TYPE.INinja);
console.log(ninja);
}
module fluent_decorator {
let kernel = new Kernel();
let provide = makeFluentProvideDecorator(kernel);
let provideSingleton = function(identifier: string) {
return provide(identifier).inSingletonScope().done();
};
let provideTransient = function(identifier: string) {
return provide(identifier).done();
};
interface INinja {
fight(): string;
sneak(): string;
}
interface IKatana {
hit(): string;
}
interface IShuriken {
throw(): string;
}
let TYPE = {
IKatana: "IKatana",
INinja: "INinja",
IShuriken: "IShuriken"
};
@provideSingleton(TYPE.IKatana)
class Katana implements IKatana {
private _mark: any;
public constructor() {
this._mark = Math.random();
}
public hit() {
return "cut! " + this._mark;
}
}
@provideTransient(TYPE.IShuriken)
class Shuriken implements IShuriken {
private _mark: any;
public constructor() {
this._mark = Math.random();
}
public throw() {
return "hit! " + this._mark;
}
}
@provideTransient(TYPE.INinja)
class Ninja implements INinja {
private _katana: IKatana;
private _shuriken: IShuriken;
public constructor(
@inject("IKatana") katana: IKatana,
@inject("IShuriken") shuriken: IShuriken
) {
this._katana = katana;
this._shuriken = shuriken;
}
public fight() { return this._katana.hit(); };
public sneak() { return this._shuriken.throw(); };
}
let ninja = kernel.get<INinja>(TYPE.INinja);
console.log(ninja);
}
module auto_provide {
let warriors = {
Ninja: class Ninja {},
Samurai: class Samurai {}
};
let weapons = {
Katana: class Katana {},
Shuriken: class Shuriken {},
};
let kernel = new Kernel();
autoProvide(kernel, warriors, weapons);
}
@@ -0,0 +1,55 @@
// Type definitions for inversify 1.0.0-beta.5
// Project: https://github.com/inversify/inversify-binding-decorators
// Definitions by: inversify <https://github.com/inversify/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../inversify/inversify.d.ts" />
declare namespace inversifyBindingDecorators {
interface IProvideInSyntax<T> extends IProvideDoneSyntax<T> {
inSingletonScope(): IProvideWhenOnSyntax<T>;
}
interface IProvideDoneSyntax<T> {
done(): (target: any) => any;
}
interface IProvideOnSyntax<T> extends IProvideDoneSyntax<T> {
onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): IProvideWhenSyntax<T>;
}
interface IProvideInWhenOnSyntax<T> extends IProvideInSyntax<T>, IProvideWhenSyntax<T>, IProvideOnSyntax<T> {}
interface IProvideWhenOnSyntax<T> extends IProvideWhenSyntax<T>, IProvideOnSyntax<T> {}
interface IProvideWhenSyntax<T> extends IProvideDoneSyntax<T> {
when(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax<T>;
whenTargetNamed(name: string): IProvideOnSyntax<T>;
whenTargetTagged(tag: string, value: any): IProvideOnSyntax<T>;
whenInjectedInto(parent: (Function|string)): IProvideOnSyntax<T>;
whenParentNamed(name: string): IProvideOnSyntax<T>;
whenParentTagged(tag: string, value: any): IProvideOnSyntax<T>;
whenAnyAncestorIs(ancestor: (Function|string)): IProvideOnSyntax<T>;
whenNoAncestorIs(ancestor: (Function|string)): IProvideOnSyntax<T>;
whenAnyAncestorNamed(name: string): IProvideOnSyntax<T>;
whenAnyAncestorTagged(tag: string, value: any): IProvideOnSyntax<T>;
whenNoAncestorNamed(name: string): IProvideOnSyntax<T>;
whenNoAncestorTagged(tag: string, value: any): IProvideOnSyntax<T>;
whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax<T>;
whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax<T>;
}
export function autoProvide(kernel: inversify.interfaces.Kernel, ...modules: any[]): void;
export function makeProvideDecorator(kernel: inversify.interfaces.Kernel):
(serviceIdentifier: (string|Symbol|inversify.interfaces.Newable<any>)) => (target: any) => any;
export function makeFluentProvideDecorator(kernel: inversify.interfaces.Kernel):
(serviceIdentifier: (string|Symbol|inversify.interfaces.Newable<any>)) => IProvideInWhenOnSyntax<any>;
}
declare module "inversify-binding-decorators" {
export = inversifyBindingDecorators;
}
@@ -0,0 +1,89 @@
/// <reference path="./inversify-express-utils.d.ts" />
import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method } from "inversify-express-utils";
import * as express from "express";
import { Kernel } from "inversify";
module server {
let kernel = new Kernel();
let server = new InversifyExpressServer(kernel);
server
.setConfig((app) => {
app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
console.log("hello world");
next();
});
})
.setErrorConfig((app) => {
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
console.error(err.stack);
res.status(500).send("Something broke!");
});
})
.build()
.listen(3000, "localhost");
}
module decorators {
@Controller("/")
class TestController {
@Get("/")
public testGet() { return "GET"; }
@All("/")
public testAll() { return "ALL"; }
@Delete("/")
public testDelete() { return "DELETE"; }
@Head("/")
public testHead() { return "HEAD"; }
@Put("/")
public testPut() { return "PUT"; }
@Patch("/")
public testPatch() { return "PATCH"; }
@Post("/")
public testPost() { return "POST"; }
@Method("foo", "/")
public testMethod() { return "METHOD:FOO"; }
}
function m1(req: express.Request, res: express.Response, next: express.NextFunction) { next(); }
function m2(req: express.Request, res: express.Response, next: express.NextFunction) { next(); }
function m3(req: express.Request, res: express.Response, next: express.NextFunction) { next(); }
@Controller("/", m1, m2, m3)
class TestMiddlewareController {
@Get("/", m1, m2, m3)
public testGet() { return "GET"; }
@All("/", m1, m2, m3)
public testAll() { return "ALL"; }
@Delete("/", m1, m2, m3)
public testDelete() { return "DELETE"; }
@Head("/", m1, m2, m3)
public testHead() { return "HEAD"; }
@Put("/", m1, m2, m3)
public testPut() { return "PUT"; }
@Patch("/", m1, m2, m3)
public testPatch() { return "PATCH"; }
@Post("/", m1, m2, m3)
public testPost() { return "POST"; }
@Method("foo", "/", m1, m2, m3)
public testMethod() { return "METHOD:FOO"; }
}
}
+50
View File
@@ -0,0 +1,50 @@
// Type definitions for inversify 1.0.0-alpha.4
// Project: https://github.com/inversify/inversify-express-utils
// Definitions by: inversify <https://github.com/inversify/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../inversify/inversify.d.ts" />
/// <reference path="../express/express.d.ts" />
declare module "inversify-express-utils" {
import * as express from "express";
import * as inversify from "inversify";
interface IInversifyExpressServerConstructor {
new(kernel: inversify.interfaces.Kernel): IInversifyExpressServer;
}
interface IInversifyExpressServer {
setConfig(fn: IConfigFunction): IInversifyExpressServer;
setErrorConfig(fn: IConfigFunction): IInversifyExpressServer;
build(): express.Application;
}
interface IConfigFunction {
(app: express.Application): void;
}
interface IHandlerDecoratorFactory {
(path: string, ...middleware: express.RequestHandler[]): IHandlerDecorator;
}
interface IHandlerDecorator {
(target: any, key: string, value: any): void;
}
export interface IController {}
export var InversifyExpressServer: IInversifyExpressServerConstructor;
export var Controller: (path: string, ...middleware: express.RequestHandler[]) => (target: any) => void;
export var All: IHandlerDecoratorFactory;
export var Get: IHandlerDecoratorFactory;
export var Post: IHandlerDecoratorFactory;
export var Put: IHandlerDecoratorFactory;
export var Patch: IHandlerDecoratorFactory;
export var Head: IHandlerDecoratorFactory;
export var Delete: IHandlerDecoratorFactory;
export var Method: (method: string, path: string, ...middleware: express.RequestHandler[]) => IHandlerDecorator;
}
@@ -0,0 +1,59 @@
/// <reference path="./inversify-logger-middleware.d.ts" />
declare var kernel: inversify.interfaces.Kernel;
import { makeLoggerMiddleware, textSerializer } from "inversify-logger-middleware";
interface ILoggerOutput<T> {
entry: T;
}
let makeStringRenderer = function (loggerOutput: ILoggerOutput<string>) {
return function (entry: inversifyLoggerMiddleware.ILogEntry) {
loggerOutput.entry = textSerializer(entry);
};
};
let makeObjRenderer = function (loggerOutput: ILoggerOutput<any>) {
return function (entry: inversifyLoggerMiddleware.ILogEntry) {
loggerOutput.entry = entry;
};
};
let options: inversifyLoggerMiddleware.ILoggerSettings = {
request: {
bindings: {
activated: true,
cache: true,
constraint: true,
dynamicValue: true,
factory: true,
implementationType: true,
onActivation: true,
provider: true,
scope: true,
serviceIdentifier: true,
type: true
},
serviceIdentifier: true,
target: {
metadata: true,
name: true,
serviceIdentifier: true
}
},
time: true
};
let logger = makeLoggerMiddleware();
kernel.applyMiddleware(logger);
let loggerOutput1: ILoggerOutput<string> = { entry: null };
let stringRenderer1 = makeStringRenderer(loggerOutput1);
let logger1 = makeLoggerMiddleware(options, stringRenderer1);
kernel.applyMiddleware(logger1);
let loggerOutput2: ILoggerOutput<inversifyLoggerMiddleware.ILogEntry> = { entry: null };
let objRenderer2 = makeObjRenderer(loggerOutput2);
let logger2 = makeLoggerMiddleware(options, objRenderer2);
kernel.applyMiddleware(logger2);
@@ -0,0 +1,59 @@
// Type definitions for inversify 1.0.0-beta.6
// Project: https://github.com/inversify/inversify-logger-middleware
// Definitions by: inversify <https://github.com/inversify/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../inversify/inversify.d.ts"/>
declare namespace inversifyLoggerMiddleware {
export interface ILoggerSettings {
request?: IRequestLoggerSettings;
time?: boolean;
}
export interface IRequestLoggerSettings {
serviceIdentifier?: boolean;
bindings?: IBindingLoggerSettings;
target?: ITargetLoggerSettings;
}
export interface IBindingLoggerSettings {
activated?: boolean;
serviceIdentifier?: boolean;
implementationType?: boolean;
factory?: boolean;
provider?: boolean;
constraint?: boolean;
onActivation?: boolean;
cache?: boolean;
dynamicValue?: boolean;
scope?: boolean;
type?: boolean;
}
export interface ITargetLoggerSettings {
serviceIdentifier?: boolean;
name?: boolean;
metadata?: boolean;
}
export interface ILogEntry {
error: boolean;
exception: any;
multiInject: boolean;
results: any[];
rootRequest: inversify.interfaces.Request;
serviceIdentifier: any;
target: any;
time: string;
}
export function makeLoggerMiddleware(settings?: ILoggerSettings, renderer?: (out: ILogEntry) => void): inversify.interfaces.Middleware;
export function textSerializer(entry: ILogEntry): string;
}
declare module "inversify-logger-middleware" {
export = inversifyLoggerMiddleware;
}
+335 -85
View File
@@ -1,39 +1,65 @@
/// <reference path="inversify.d.ts" />
/// <reference path="./inversify.d.ts" />
/// <reference path="../harmony-proxy/harmony-proxy.d.ts" />
namespace global_module_test {
let injectable = inversify.injectable;
let inject = inversify.inject;
let tagged = inversify.tagged;
let named = inversify.named;
let Kernel = inversify.Kernel;
let KernelModule = inversify.KernelModule;
let targetName = inversify.targetName;
let multiInject = inversify.multiInject;
let traverseAncerstors = inversify.traverseAncerstors;
let taggedConstraint = inversify.taggedConstraint;
let namedConstraint = inversify.namedConstraint;
let typeConstraint = inversify.typeConstraint;
let makePropertyMultiInjectDecorator = inversify.makePropertyMultiInjectDecorator;
let makePropertyInjectTaggedDecorator = inversify.makePropertyInjectTaggedDecorator;
let makePropertyInjectNamedDecorator = inversify.makePropertyInjectNamedDecorator;
let makePropertyInjectDecorator = inversify.makePropertyInjectDecorator;
interface INinja {
module external_module_test {
interface Warrior {
fight(): string;
sneak(): string;
}
interface IKatana {
interface Weapon {
hit(): string;
}
interface IShuriken {
interface ThrowableWeapon extends Weapon {
throw(): string;
}
class Katana implements IKatana {
@injectable()
class Katana implements Weapon {
public hit() {
return "cut!";
}
}
class Shuriken implements IShuriken {
@injectable()
class Shuriken implements ThrowableWeapon {
public throw() {
return "hit!";
}
public hit() {
return "hit!";
}
}
@inversify.inject("IKatana", "IShuriken")
class Ninja implements INinja {
@injectable()
class Ninja implements Warrior {
private _katana: IKatana;
private _shuriken: IShuriken;
private _katana: Weapon;
private _shuriken: ThrowableWeapon;
public constructor(katana: IKatana, shuriken: IShuriken) {
public constructor(
@inject("Weapon") katana: Weapon,
@inject("ThrowableWeapon") shuriken: ThrowableWeapon
) {
this._katana = katana;
this._shuriken = shuriken;
}
@@ -43,62 +69,73 @@ namespace global_module_test {
}
let kernel = new inversify.Kernel();
kernel.bind<INinja>("INinja").to(Ninja);
kernel.bind<IKatana>("IKatana").to(Katana);
kernel.bind<IShuriken>("IShuriken").to(Shuriken).inSingletonScope();
let kernel: inversify.interfaces.Kernel = new Kernel();
kernel.bind<Warrior>("Warrior").to(Ninja);
kernel.bind<Weapon>("Weapon").to(Katana);
kernel.bind<ThrowableWeapon>("ThrowableWeapon").to(Shuriken).inSingletonScope();
let ninja = kernel.get<INinja>("INinja");
let ninja = kernel.get<Warrior>("Warrior");
console.log(ninja);
// Unbind
kernel.unbind("INinja");
kernel.unbind("Warrior");
kernel.unbindAll();
// Kernel modules
let module: inversify.IKernelModule = (k: inversify.IKernel) => {
k.bind<INinja>("INinja").to(Ninja);
k.bind<IKatana>("IKatana").to(Katana).inTransientScope();
k.bind<IShuriken>("IShuriken").to(Shuriken).inSingletonScope();
};
let warriors: inversify.interfaces.KernelModule = new KernelModule((bind: inversify.interfaces.Bind) => {
bind<Warrior>("Warrior").to(Ninja);
});
let options: inversify.IKernelOptions = {
middleware: [],
modules: [module]
};
let weapons: inversify.interfaces.KernelModule = new KernelModule((bind: inversify.interfaces.Bind) => {
bind<Weapon>("Weapon").to(Katana);
bind<ThrowableWeapon>("ThrowableWeapon").to(Shuriken);
});
kernel = new inversify.Kernel(options);
let ninja2 = kernel.get<INinja>("INinja");
kernel = new Kernel();
kernel.load(warriors, weapons);
let ninja2 = kernel.get<Warrior>("Warrior");
console.log(ninja2);
// middleware
function logger(planAndResolve: inversify.interfaces.PlanAndResolve<any>): inversify.interfaces.PlanAndResolve<any> {
return (args: inversify.interfaces.PlanAndResolveArgs) => {
let start = new Date().getTime();
let result = planAndResolve(args);
let end = new Date().getTime();
console.log(end - start);
return result;
};
}
kernel.applyMiddleware(logger, logger);
// binding types
kernel.bind<IKatana>("IKatana").to(Katana);
kernel.bind<IKatana>("IKatana").toValue(new Katana());
kernel.bind<Weapon>("Weapon").to(Katana);
kernel.bind<Weapon>("Weapon").toConstantValue(new Katana());
kernel.bind<Weapon>("Weapon").toDynamicValue(() => { return new Katana(); });
kernel.bind<inversify.INewable<IKatana>>("IKatana").toConstructor<IKatana>(Katana);
kernel.bind<inversify.interfaces.Newable<Weapon>>("Weapon").toConstructor<Weapon>(Katana);
kernel.bind<inversify.IFactory<IKatana>>("IKatana").toFactory<IKatana>((context) => {
kernel.bind<inversify.interfaces.Factory<Weapon>>("Weapon").toFactory<Weapon>((context) => {
return () => {
return kernel.get<IKatana>("IKatana");
return kernel.get<Weapon>("Weapon");
};
});
kernel.bind<inversify.IFactory<IKatana>>("IKatana").toAutoFactory<IKatana>();
kernel.bind<inversify.interfaces.Factory<Weapon>>("Weapon").toAutoFactory<Weapon>("Weapon");
kernel.bind<inversify.IProvider<IKatana>>("IKatana").toProvider<IKatana>((context) => {
kernel.bind<inversify.interfaces.Provider<Weapon>>("Weapon").toProvider<Weapon>((context) => {
return () => {
return new Promise<IKatana>((resolve) => {
let katana = kernel.get<IKatana>("IKatana");
return new Promise<Weapon>((resolve) => {
let katana = kernel.get<Weapon>("Weapon");
resolve(katana);
});
};
});
kernel.bind<IKatana>("IKatana").to(Katana).proxy((katanaToBeInjected: IKatana) => {
// BLOCK http://stackoverflow.com/questions/35906938/how-to-enable-harmony-proxies-in-gulp-mocha
/*
kernel.bind<Weapon>("Weapon").to(Katana).onActivation((context: inversify.interfaces.Context, katanaToBeInjected: Weapon) => {
let handler = {
apply: function(target, thisArgument, argumentsList) {
apply: function(target: any, thisArgument: any, argumentsList: any[]) {
console.log(`Starting: ${performance.now()}`);
let result = target.apply(thisArgument, argumentsList);
console.log(`Finished: ${performance.now()}`);
@@ -106,88 +143,301 @@ namespace global_module_test {
}
};
return new Proxy(katanaToBeInjected, handler);
*/
return katanaToBeInjected;
});
interface IWeapon {}
interface ISamurai {
katana: IWeapon;
shuriken: IWeapon;
}
@inversify.inject("IWeapon", "IWeapon")
class Samurai implements ISamurai {
public katana: IWeapon;
public shuriken: IWeapon;
@injectable()
class Samurai implements Warrior {
public katana: Weapon;
public shuriken: ThrowableWeapon;
public constructor(
@inversify.tagged("canThrow", false) katana: IWeapon,
@inversify.tagged("canThrow", true) shuriken: IWeapon
@inject("Weapon") @tagged("canThrow", false) katana: Weapon,
@inject("ThrowableWeapon") @tagged("canThrow", true) shuriken: ThrowableWeapon
) {
this.katana = katana;
this.shuriken = shuriken;
}
public fight() { return this.katana.hit(); };
public sneak() { return this.shuriken.throw(); };
}
kernel.bind<Samurai>("Samurai").to(Samurai);
kernel.bind<IWeapon>("IWeapon").to(Katana).whenTargetTagged("canThrow", false);
kernel.bind<IWeapon>("IWeapon").to(Shuriken).whenTargetTagged("canThrow", true);
kernel.bind<Weapon>("IWeapon").to(Katana).whenTargetTagged("canThrow", false);
kernel.bind<ThrowableWeapon>("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true);
let throwable = inversify.tagged("canThrow", true);
let notThrowable = inversify.tagged("canThrow", false);
let throwable = tagged("canThrow", true);
let notThrowable = tagged("canThrow", false);
@inversify.inject("IWeapon", "IWeapon")
class Samurai2 implements ISamurai {
public katana: IWeapon;
public shuriken: IWeapon;
@injectable()
class Samurai2 implements Samurai {
public katana: Weapon;
public shuriken: ThrowableWeapon;
public constructor(
@throwable("canThrow", false) katana: IWeapon,
@notThrowable("canThrow", true) shuriken: IWeapon
@inject("Weapon") @throwable katana: Weapon,
@inject("ThrowableWeapon") @notThrowable shuriken: ThrowableWeapon
) {
this.katana = katana;
this.shuriken = shuriken;
}
public fight() { return this.katana.hit(); };
public sneak() { return this.shuriken.throw(); };
}
@inversify.inject("IWeapon", "IWeapon")
class Samurai3 implements ISamurai {
public katana: IWeapon;
public shuriken: IWeapon;
@injectable()
class Samurai3 implements Samurai {
public katana: Weapon;
public shuriken: ThrowableWeapon;
public constructor(
@inversify.named("strong") katana: IWeapon,
@inversify.named("weak") shuriken: IWeapon
@inject("Weapon") @named("strong") katana: Weapon,
@inject("ThrowableWeapon") @named("weak") shuriken: ThrowableWeapon
) {
this.katana = katana;
this.shuriken = shuriken;
}
public fight() { return this.katana.hit(); };
public sneak() { return this.shuriken.throw(); };
}
kernel.bind<ISamurai>("ISamurai").to(Samurai3);
kernel.bind<IWeapon>("IWeapon").to(Katana).whenTargetNamed("strong");
kernel.bind<IWeapon>("IWeapon").to(Shuriken).whenTargetNamed("weak");
kernel.bind<Warrior>("Warrior").to(Samurai3);
kernel.bind<Weapon>("Weapon").to(Katana).whenTargetNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenTargetNamed("weak");
@inversify.inject("IWeapon", "IWeapon")
@inversify.paramNames("katana", "shuriken")
class Samurai4 implements ISamurai {
public katana: IWeapon;
public shuriken: IWeapon;
@injectable()
class Samurai4 implements Samurai {
public katana: Weapon;
public shuriken: ThrowableWeapon;
public constructor(
katana: IWeapon,
shuriken: IWeapon
@inject("Weapon") @targetName("katana") katana: Weapon,
@inject("ThrowableWeapon") @targetName("shuriken") shuriken: ThrowableWeapon
) {
this.katana = katana;
this.shuriken = shuriken;
}
public fight() { return this.katana.hit(); };
public sneak() { return this.shuriken.throw(); };
}
kernel.bind<ISamurai>("ISamurai").to(Samurai4);
kernel.bind<Warrior>("Warrior").to(Samurai4);
kernel.bind<IWeapon>("IWeapon").to(Katana).when((request: inversify.IRequest) => {
kernel.bind<Weapon>("Weapon").to(Katana).when((request: inversify.interfaces.Request) => {
return request.target.name.equals("katana");
});
kernel.bind<IWeapon>("IWeapon").to(Shuriken).when((request: inversify.IRequest) => {
kernel.bind<Weapon>("Weapon").to(Shuriken).when((request: inversify.interfaces.Request) => {
return request.target.name.equals("shuriken");
});
// custom constraints
let whenParentNamedCanThrowConstraint = (request: inversify.interfaces.Request) => {
return namedConstraint("canThrow")(request.parentRequest);
};
let whenAnyAncestorIsConstraint = (request: inversify.interfaces.Request) => {
return traverseAncerstors(request, typeConstraint(Ninja));
};
let whenAnyAncestorTaggedConstraint = (request: inversify.interfaces.Request) => {
return traverseAncerstors(request, taggedConstraint("canThrow")(true));
};
kernel.bind<Weapon>("Weapon").to(Shuriken).when(whenParentNamedCanThrowConstraint);
kernel.bind<Weapon>("Weapon").to(Shuriken).when(whenAnyAncestorIsConstraint);
kernel.bind<Weapon>("Weapon").to(Shuriken).when(whenAnyAncestorTaggedConstraint);
// Constraint helpers
kernel.bind<Weapon>("Weapon").to(Shuriken).whenInjectedInto(Ninja);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenInjectedInto("INinja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenParentNamed("chinese");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenParentTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenTargetNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenTargetTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorIs("INinja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorIs(Ninja);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorIs("INinja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint);
// multi-injection
@injectable()
class Samurai5 implements Warrior {
public katana: Weapon;
public shuriken: Weapon;
public constructor(
@multiInject("Weapon") wpns: Weapon[]
) {
this.katana = wpns[0];
this.shuriken = wpns[1];
}
public fight() { return this.katana.hit(); };
public sneak() { return this.shuriken.hit(); };
}
// symbols
let SYMBOLS = {
ThrowableWeapon: Symbol("ThrowableWeapon"),
Warrior: Symbol("Warrior"),
Weapon: Symbol("Weapon"),
};
@injectable()
class Ninja1 implements Warrior {
private _katana: Weapon;
private _shuriken: ThrowableWeapon;
public constructor(
@inject(SYMBOLS.Weapon) katana: Weapon,
@inject(SYMBOLS.ThrowableWeapon) shuriken: ThrowableWeapon
) {
this._katana = katana;
this._shuriken = shuriken;
}
public fight() { return this._katana.hit(); };
public sneak() { return this._shuriken.throw(); };
}
let kernel3 = new Kernel();
kernel3.bind<Warrior>(SYMBOLS.Warrior).to(Ninja);
kernel3.bind<Weapon>(SYMBOLS.Weapon).to(Katana);
kernel3.bind<ThrowableWeapon>(SYMBOLS.ThrowableWeapon).to(Shuriken).inSingletonScope();
let ninja4 = kernel3.get<Warrior>("Warrior");
console.log(ninja4);
// classes
@injectable()
class Ninja2 implements Warrior {
private _katana: Katana;
private _shuriken: Shuriken;
public constructor(
katana: Katana,
shuriken: Shuriken
) {
this._katana = katana;
this._shuriken = shuriken;
}
public fight() { return this._katana.hit(); };
public sneak() { return this._shuriken.throw(); };
}
let kernel4 = new Kernel();
kernel4.bind<Ninja>(Ninja).to(Ninja);
kernel4.bind<Katana>(Katana).to(Katana);
kernel4.bind<Shuriken>(Shuriken).to(Shuriken).inSingletonScope();
let ninja5 = kernel4.get<Ninja>(Ninja);
console.log(ninja5);
}
module property_injection {
let kernel = new Kernel();
let TYPES = { Weapon: "Weapon" };
interface Weapon {
durability: number;
use(): void;
}
@injectable()
class Sword implements Weapon {
public durability: number;
public constructor() {
this.durability = 100;
}
public use() {
this.durability = this.durability - 10;
}
}
@injectable()
class WarHammer implements Weapon {
public durability: number;
public constructor() {
this.durability = 100;
}
public use() {
this.durability = this.durability - 10;
}
}
let propertyMultiInject = makePropertyMultiInjectDecorator(kernel);
class Warrior1 {
@propertyMultiInject(TYPES.Weapon)
public weapons: Weapon[];
}
let propertyInject = makePropertyInjectDecorator(kernel);
interface Service {
count: number;
increment(): void;
}
@injectable()
class SomeService implements Service {
public count: number;
public constructor() {
this.count = 0;
}
public increment() {
this.count = this.count + 1;
}
}
class SomeWebComponent {
@propertyInject("Service")
private _service: Service;
public doSomething() {
let count = this._service.count;
this._service.increment();
return count;
}
}
let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel);
class Warrior2 {
@propertyInjectNammed(TYPES.Weapon, "not-throwwable")
@named("not-throwwable")
public primaryWeapon: Weapon;
@propertyInjectNammed(TYPES.Weapon, "throwwable")
@named("throwwable")
public secondaryWeapon: Weapon;
}
let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel);
class Warrior3 {
@propertyInjectTagged(TYPES.Weapon, "throwwable", false)
@tagged("throwwable", false)
public primaryWeapon: Weapon;
@propertyInjectTagged(TYPES.Weapon, "throwwable", true)
@tagged("throwwable", true)
public secondaryWeapon: Weapon;
}
kernel.snapshot();
kernel.restore();
}
+326 -85
View File
@@ -1,46 +1,62 @@
/// <reference path="inversify.d.ts" />
/// <reference path="./inversify.d.ts" />
/// <reference path="../harmony-proxy/harmony-proxy.d.ts" />
import {
Kernel,
inject, tagged, named, paramNames,
IKernel, IKernelOptions, INewable,
IKernelModule, IFactory, IProvider, IRequest
injectable, tagged, named, targetName,
inject, multiInject, traverseAncerstors,
taggedConstraint, namedConstraint, typeConstraint,
makePropertyMultiInjectDecorator,
makePropertyInjectTaggedDecorator,
makePropertyInjectNamedDecorator,
makePropertyInjectDecorator,
KernelModule, interfaces
} from "inversify";
namespace external_module_test {
import * as Proxy from "harmony-proxy";
interface INinja {
module external_module_test {
interface Warrior {
fight(): string;
sneak(): string;
}
interface IKatana {
interface Weapon {
hit(): string;
}
interface IShuriken {
interface ThrowableWeapon extends Weapon {
throw(): string;
}
class Katana implements IKatana {
@injectable()
class Katana implements Weapon {
public hit() {
return "cut!";
}
}
class Shuriken implements IShuriken {
@injectable()
class Shuriken implements ThrowableWeapon {
public throw() {
return "hit!";
}
public hit() {
return "hit!";
}
}
@inject("IKatana", "IShuriken")
class Ninja implements INinja {
@injectable()
class Ninja implements Warrior {
private _katana: IKatana;
private _shuriken: IShuriken;
private _katana: Weapon;
private _shuriken: ThrowableWeapon;
public constructor(katana: IKatana, shuriken: IShuriken) {
public constructor(
@inject("Weapon") katana: Weapon,
@inject("ThrowableWeapon") shuriken: ThrowableWeapon
) {
this._katana = katana;
this._shuriken = shuriken;
}
@@ -50,62 +66,73 @@ namespace external_module_test {
}
let kernel = new Kernel();
kernel.bind<INinja>("INinja").to(Ninja);
kernel.bind<IKatana>("IKatana").to(Katana);
kernel.bind<IShuriken>("IShuriken").to(Shuriken).inSingletonScope();
let kernel: interfaces.Kernel = new Kernel();
kernel.bind<Warrior>("Warrior").to(Ninja);
kernel.bind<Weapon>("Weapon").to(Katana);
kernel.bind<ThrowableWeapon>("ThrowableWeapon").to(Shuriken).inSingletonScope();
let ninja = kernel.get<INinja>("INinja");
let ninja = kernel.get<Warrior>("Warrior");
console.log(ninja);
// Unbind
kernel.unbind("INinja");
kernel.unbind("Warrior");
kernel.unbindAll();
// Kernel modules
let module: IKernelModule = (k: IKernel) => {
k.bind<INinja>("INinja").to(Ninja);
k.bind<IKatana>("IKatana").to(Katana).inTransientScope();
k.bind<IShuriken>("IShuriken").to(Shuriken).inSingletonScope();
};
let warriors: interfaces.KernelModule = new KernelModule((bind: interfaces.Bind) => {
bind<Warrior>("Warrior").to(Ninja);
});
let options: IKernelOptions = {
middleware: [],
modules: [module]
};
let weapons: interfaces.KernelModule = new KernelModule((bind: interfaces.Bind) => {
bind<Weapon>("Weapon").to(Katana);
bind<ThrowableWeapon>("ThrowableWeapon").to(Shuriken);
});
kernel = new Kernel(options);
let ninja2 = kernel.get<INinja>("INinja");
kernel = new Kernel();
kernel.load(warriors, weapons);
let ninja2 = kernel.get<Warrior>("Warrior");
console.log(ninja2);
// middleware
function logger(planAndResolve: interfaces.PlanAndResolve<any>): interfaces.PlanAndResolve<any> {
return (args: interfaces.PlanAndResolveArgs) => {
let start = new Date().getTime();
let result = planAndResolve(args);
let end = new Date().getTime();
console.log(end - start);
return result;
};
}
kernel.applyMiddleware(logger, logger);
// binding types
kernel.bind<IKatana>("IKatana").to(Katana);
kernel.bind<IKatana>("IKatana").toValue(new Katana());
kernel.bind<Weapon>("Weapon").to(Katana);
kernel.bind<Weapon>("Weapon").toConstantValue(new Katana());
kernel.bind<Weapon>("Weapon").toDynamicValue(() => { return new Katana(); });
kernel.bind<INewable<IKatana>>("IKatana").toConstructor<IKatana>(Katana);
kernel.bind<interfaces.Newable<Weapon>>("Weapon").toConstructor<Weapon>(Katana);
kernel.bind<IFactory<IKatana>>("IKatana").toFactory<IKatana>((context) => {
kernel.bind<interfaces.Factory<Weapon>>("Weapon").toFactory<Weapon>((context) => {
return () => {
return kernel.get<IKatana>("IKatana");
return kernel.get<Weapon>("Weapon");
};
});
kernel.bind<IFactory<IKatana>>("IKatana").toAutoFactory<IKatana>();
kernel.bind<interfaces.Factory<Weapon>>("Weapon").toAutoFactory<Weapon>("Weapon");
kernel.bind<IProvider<IKatana>>("IKatana").toProvider<IKatana>((context) => {
kernel.bind<interfaces.Provider<Weapon>>("Weapon").toProvider<Weapon>((context) => {
return () => {
return new Promise<IKatana>((resolve) => {
let katana = kernel.get<IKatana>("IKatana");
return new Promise<Weapon>((resolve) => {
let katana = kernel.get<Weapon>("Weapon");
resolve(katana);
});
};
});
kernel.bind<IKatana>("IKatana").to(Katana).proxy((katanaToBeInjected: IKatana) => {
// BLOCK http://stackoverflow.com/questions/35906938/how-to-enable-harmony-proxies-in-gulp-mocha
/*
kernel.bind<Weapon>("Weapon").to(Katana).onActivation((context: interfaces.Context, katanaToBeInjected: Weapon) => {
let handler = {
apply: function(target, thisArgument, argumentsList) {
apply: function(target: any, thisArgument: any, argumentsList: any[]) {
console.log(`Starting: ${performance.now()}`);
let result = target.apply(thisArgument, argumentsList);
console.log(`Finished: ${performance.now()}`);
@@ -113,88 +140,302 @@ namespace external_module_test {
}
};
return new Proxy(katanaToBeInjected, handler);
*/
return katanaToBeInjected;
});
interface IWeapon {}
interface ISamurai {
katana: IWeapon;
shuriken: IWeapon;
}
@inject("IWeapon", "IWeapon")
class Samurai implements ISamurai {
public katana: IWeapon;
public shuriken: IWeapon;
@injectable()
class Samurai implements Warrior {
public katana: Weapon;
public shuriken: ThrowableWeapon;
public constructor(
@tagged("canThrow", false) katana: IWeapon,
@tagged("canThrow", true) shuriken: IWeapon
@inject("Weapon") @tagged("canThrow", false) katana: Weapon,
@inject("ThrowableWeapon") @tagged("canThrow", true) shuriken: ThrowableWeapon
) {
this.katana = katana;
this.shuriken = shuriken;
}
public fight() { return this.katana.hit(); };
public sneak() { return this.shuriken.throw(); };
}
kernel.bind<Samurai>("Samurai").to(Samurai);
kernel.bind<IWeapon>("IWeapon").to(Katana).whenTargetTagged("canThrow", false);
kernel.bind<IWeapon>("IWeapon").to(Shuriken).whenTargetTagged("canThrow", true);
kernel.bind<Weapon>("IWeapon").to(Katana).whenTargetTagged("canThrow", false);
kernel.bind<ThrowableWeapon>("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true);
let throwable = tagged("canThrow", true);
let notThrowable = tagged("canThrow", false);
@inject("IWeapon", "IWeapon")
class Samurai2 implements ISamurai {
public katana: IWeapon;
public shuriken: IWeapon;
@injectable()
class Samurai2 implements Samurai {
public katana: Weapon;
public shuriken: ThrowableWeapon;
public constructor(
@throwable("canThrow", false) katana: IWeapon,
@notThrowable("canThrow", true) shuriken: IWeapon
@inject("Weapon") @throwable katana: Weapon,
@inject("ThrowableWeapon") @notThrowable shuriken: ThrowableWeapon
) {
this.katana = katana;
this.shuriken = shuriken;
}
public fight() { return this.katana.hit(); };
public sneak() { return this.shuriken.throw(); };
}
@inject("IWeapon", "IWeapon")
class Samurai3 implements ISamurai {
public katana: IWeapon;
public shuriken: IWeapon;
@injectable()
class Samurai3 implements Samurai {
public katana: Weapon;
public shuriken: ThrowableWeapon;
public constructor(
@named("strong") katana: IWeapon,
@named("weak") shuriken: IWeapon
@inject("Weapon") @named("strong") katana: Weapon,
@inject("ThrowableWeapon") @named("weak") shuriken: ThrowableWeapon
) {
this.katana = katana;
this.shuriken = shuriken;
}
public fight() { return this.katana.hit(); };
public sneak() { return this.shuriken.throw(); };
}
kernel.bind<ISamurai>("ISamurai").to(Samurai3);
kernel.bind<IWeapon>("IWeapon").to(Katana).whenTargetNamed("strong");
kernel.bind<IWeapon>("IWeapon").to(Shuriken).whenTargetNamed("weak");
kernel.bind<Warrior>("Warrior").to(Samurai3);
kernel.bind<Weapon>("Weapon").to(Katana).whenTargetNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenTargetNamed("weak");
@inject("IWeapon", "IWeapon")
@paramNames("katana", "shuriken")
class Samurai4 implements ISamurai {
public katana: IWeapon;
public shuriken: IWeapon;
@injectable()
class Samurai4 implements Samurai {
public katana: Weapon;
public shuriken: ThrowableWeapon;
public constructor(
katana: IWeapon,
shuriken: IWeapon
@inject("Weapon") @targetName("katana") katana: Weapon,
@inject("ThrowableWeapon") @targetName("shuriken") shuriken: ThrowableWeapon
) {
this.katana = katana;
this.shuriken = shuriken;
}
public fight() { return this.katana.hit(); };
public sneak() { return this.shuriken.throw(); };
}
kernel.bind<ISamurai>("ISamurai").to(Samurai4);
kernel.bind<Warrior>("Warrior").to(Samurai4);
kernel.bind<IWeapon>("IWeapon").to(Katana).when((request: IRequest) => {
kernel.bind<Weapon>("Weapon").to(Katana).when((request: interfaces.Request) => {
return request.target.name.equals("katana");
});
kernel.bind<IWeapon>("IWeapon").to(Shuriken).when((request: IRequest) => {
kernel.bind<Weapon>("Weapon").to(Shuriken).when((request: interfaces.Request) => {
return request.target.name.equals("shuriken");
});
// custom constraints
let whenParentNamedCanThrowConstraint = (request: interfaces.Request) => {
return namedConstraint("canThrow")(request.parentRequest);
};
let whenAnyAncestorIsConstraint = (request: interfaces.Request) => {
return traverseAncerstors(request, typeConstraint(Ninja));
};
let whenAnyAncestorTaggedConstraint = (request: interfaces.Request) => {
return traverseAncerstors(request, taggedConstraint("canThrow")(true));
};
kernel.bind<Weapon>("Weapon").to(Shuriken).when(whenParentNamedCanThrowConstraint);
kernel.bind<Weapon>("Weapon").to(Shuriken).when(whenAnyAncestorIsConstraint);
kernel.bind<Weapon>("Weapon").to(Shuriken).when(whenAnyAncestorTaggedConstraint);
// Constraint helpers
kernel.bind<Weapon>("Weapon").to(Shuriken).whenInjectedInto(Ninja);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenInjectedInto("INinja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenParentNamed("chinese");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenParentTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenTargetNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenTargetTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorIs("INinja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorIs(Ninja);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorIs("INinja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint);
// multi-injection
@injectable()
class Samurai5 implements Warrior {
public katana: Weapon;
public shuriken: Weapon;
public constructor(
@multiInject("Weapon") wpns: Weapon[]
) {
this.katana = wpns[0];
this.shuriken = wpns[1];
}
public fight() { return this.katana.hit(); };
public sneak() { return this.shuriken.hit(); };
}
// symbols
let SYMBOLS = {
ThrowableWeapon: Symbol("ThrowableWeapon"),
Warrior: Symbol("Warrior"),
Weapon: Symbol("Weapon"),
};
@injectable()
class Ninja1 implements Warrior {
private _katana: Weapon;
private _shuriken: ThrowableWeapon;
public constructor(
@inject(SYMBOLS.Weapon) katana: Weapon,
@inject(SYMBOLS.ThrowableWeapon) shuriken: ThrowableWeapon
) {
this._katana = katana;
this._shuriken = shuriken;
}
public fight() { return this._katana.hit(); };
public sneak() { return this._shuriken.throw(); };
}
let kernel3 = new Kernel();
kernel3.bind<Warrior>(SYMBOLS.Warrior).to(Ninja);
kernel3.bind<Weapon>(SYMBOLS.Weapon).to(Katana);
kernel3.bind<ThrowableWeapon>(SYMBOLS.ThrowableWeapon).to(Shuriken).inSingletonScope();
let ninja4 = kernel3.get<Warrior>("Warrior");
console.log(ninja4);
// classes
@injectable()
class Ninja2 implements Warrior {
private _katana: Katana;
private _shuriken: Shuriken;
public constructor(
katana: Katana,
shuriken: Shuriken
) {
this._katana = katana;
this._shuriken = shuriken;
}
public fight() { return this._katana.hit(); };
public sneak() { return this._shuriken.throw(); };
}
let kernel4 = new Kernel();
kernel4.bind<Ninja>(Ninja).to(Ninja);
kernel4.bind<Katana>(Katana).to(Katana);
kernel4.bind<Shuriken>(Shuriken).to(Shuriken).inSingletonScope();
let ninja5 = kernel4.get<Ninja>(Ninja);
console.log(ninja5);
}
module property_injection {
let kernel = new Kernel();
let TYPES = { Weapon: "Weapon" };
interface Weapon {
durability: number;
use(): void;
}
@injectable()
class Sword implements Weapon {
public durability: number;
public constructor() {
this.durability = 100;
}
public use() {
this.durability = this.durability - 10;
}
}
@injectable()
class WarHammer implements Weapon {
public durability: number;
public constructor() {
this.durability = 100;
}
public use() {
this.durability = this.durability - 10;
}
}
let propertyMultiInject = makePropertyMultiInjectDecorator(kernel);
class Warrior1 {
@propertyMultiInject(TYPES.Weapon)
public weapons: Weapon[];
}
let propertyInject = makePropertyInjectDecorator(kernel);
interface Service {
count: number;
increment(): void;
}
@injectable()
class SomeService implements Service {
public count: number;
public constructor() {
this.count = 0;
}
public increment() {
this.count = this.count + 1;
}
}
class SomeWebComponent {
@propertyInject("Service")
private _service: Service;
public doSomething() {
let count = this._service.count;
this._service.increment();
return count;
}
}
let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel);
class Warrior2 {
@propertyInjectNammed(TYPES.Weapon, "not-throwwable")
@named("not-throwwable")
public primaryWeapon: Weapon;
@propertyInjectNammed(TYPES.Weapon, "throwwable")
@named("throwwable")
public secondaryWeapon: Weapon;
}
let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel);
class Warrior3 {
@propertyInjectTagged(TYPES.Weapon, "throwwable", false)
@tagged("throwwable", false)
public primaryWeapon: Weapon;
@propertyInjectTagged(TYPES.Weapon, "throwwable", true)
@tagged("throwwable", true)
public secondaryWeapon: Weapon;
}
kernel.snapshot();
kernel.restore();
}
+258 -122
View File
@@ -1,141 +1,277 @@
// Type definitions for inversify 2.0.0-alpha.3
// Type definitions for inversify 2.0.0-beta.9
// Project: https://github.com/inversify/InversifyJS
// Definitions by: inversify <https://github.com/inversify>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../bluebird/bluebird.d.ts" />
interface Symbol {
toString(): string;
valueOf(): Object;
}
interface SymbolConstructor {
(description?: string|number): Symbol;
}
declare var Symbol: SymbolConstructor;
declare namespace inversify {
interface IKernelConstructor {
new(options?: IKernelOptions): IKernel;
namespace interfaces {
export interface KernelConstructor {
new(): Kernel;
}
export interface KernelModuleConstructor {
new(registry: (bind: Bind) => void): KernelModule;
}
export interface Newable<T> {
new(...args: any[]): T;
}
export type ServiceIdentifier<T> = (string|Symbol|Newable<T>);
export interface Binding<T> extends Clonable<Binding<T>> {
guid: string;
moduleId: string;
activated: boolean;
serviceIdentifier: ServiceIdentifier<T>;
implementationType: Newable<T>;
factory: FactoryCreator<any>;
provider: ProviderCreator<any>;
constraint: (request: Request) => boolean;
onActivation: (context: Context, injectable: T) => T;
cache: T;
dynamicValue: () => T;
scope: number; // BindingScope
type: number; // BindingType
}
export interface Factory<T> extends Function {
(...args: any[]): (((...args: any[]) => T)|T);
}
export interface FactoryCreator<T> extends Function {
(context: Context): Factory<T>;
}
export interface Provider<T> extends Function {
(): Promise<T>;
}
export interface ProviderCreator<T> extends Function {
(context: Context): Provider<T>;
}
export interface PlanAndResolve<T> {
(args: PlanAndResolveArgs): T[];
}
export interface PlanAndResolveArgs {
multiInject: boolean;
serviceIdentifier: ServiceIdentifier<any>;
target: Target;
contextInterceptor: (contexts: Context) => Context;
}
export interface Middleware extends Function {
(next: PlanAndResolve<any>): PlanAndResolve<any>;
}
export interface Context {
guid: string;
kernel: Kernel;
plan: Plan;
addPlan(plan: Plan): void;
}
export interface ReflectResult {
[key: string]: Metadata[];
}
export interface Metadata {
key: string;
value: any;
}
export interface Plan {
parentContext: Context;
rootRequest: Request;
}
export interface Planner {
createContext(kernel: Kernel): Context;
createPlan(parentContext: Context, binding: Binding<any>, target: Target): Plan;
getBindings<T>(kernel: Kernel, serviceIdentifier: ServiceIdentifier<T>): Binding<T>[];
getActiveBindings(parentRequest: Request, target: Target): Binding<any>[];
}
export interface QueryableString {
startsWith(searchString: string): boolean;
endsWith(searchString: string): boolean;
contains(searchString: string): boolean;
equals(compareString: string): boolean;
value(): string;
}
export interface Request {
guid: string;
serviceIdentifier: ServiceIdentifier<any>;
parentContext: Context;
parentRequest: Request;
childRequests: Request[];
target: Target;
bindings: Binding<any>[];
addChildRequest(
serviceIdentifier: ServiceIdentifier<any>,
bindings: (Binding<any>|Binding<any>[]),
target: Target
): Request;
}
export interface Target {
guid: string;
serviceIdentifier: ServiceIdentifier<any>;
name: QueryableString;
metadata: Array<Metadata>;
hasTag(key: string): boolean;
isArray(): boolean;
matchesArray(name: string|Symbol|Newable<any>): boolean;
isNamed(): boolean;
isTagged(): boolean;
matchesNamedTag(name: string): boolean;
matchesTag(key: string): (value: any) => boolean;
}
export interface Resolver {
resolve<T>(context: Context): T;
}
export interface Kernel {
guid: string;
bind<T>(serviceIdentifier: ServiceIdentifier<T>): BindingToSyntax<T>;
unbind(serviceIdentifier: ServiceIdentifier<any>): void;
unbindAll(): void;
isBound(serviceIdentifier: ServiceIdentifier<any>): boolean;
get<T>(serviceIdentifier: ServiceIdentifier<T>): T;
getNamed<T>(serviceIdentifier: ServiceIdentifier<T>, named: string): T;
getTagged<T>(serviceIdentifier: ServiceIdentifier<T>, key: string, value: any): T;
getAll<T>(serviceIdentifier: ServiceIdentifier<T>): T[];
load(...modules: KernelModule[]): void;
unload(...modules: KernelModule[]): void;
applyMiddleware(...middleware: Middleware[]): void;
getServiceIdentifierAsString(serviceIdentifier: ServiceIdentifier<any>): string;
snapshot(): void;
restore(): void;
}
export interface Bind extends Function {
<T>(serviceIdentifier: ServiceIdentifier<T>): BindingToSyntax<T>;
}
export interface KernelModule {
guid: string;
registry: (bind: Bind) => void;
}
export interface KernelSnapshot {
bindings: Lookup<Binding<any>>;
middleware: PlanAndResolve<any>;
}
export interface Clonable<T> {
clone(): T;
}
export interface Lookup<T> extends Clonable<Lookup<T>> {
add(serviceIdentifier: ServiceIdentifier<any>, value: T): void;
get(serviceIdentifier: ServiceIdentifier<any>): Array<T>;
remove(serviceIdentifier: ServiceIdentifier<any>): void;
removeByModuleId(moduleId: string): void;
hasKey(serviceIdentifier: ServiceIdentifier<any>): boolean;
}
export interface KeyValuePair<T> {
serviceIdentifier: ServiceIdentifier<any>;
value: Array<T>;
}
export interface BindingInSyntax<T> {
inSingletonScope(): BindingWhenOnSyntax<T>;
}
export interface BindingInWhenOnSyntax<T> extends BindingInSyntax<T>, BindingWhenOnSyntax<T> {}
export interface BindingOnSyntax<T> {
onActivation(fn: (context: Context, injectable: T) => T): BindingWhenSyntax<T>;
}
export interface BindingToSyntax<T> {
to(constructor: { new(...args: any[]): T; }): BindingInWhenOnSyntax<T>;
toConstantValue(value: T): BindingWhenOnSyntax<T>;
toDynamicValue(func: () => T): BindingWhenOnSyntax<T>;
toConstructor<T2>(constructor: Newable<T2>): BindingWhenOnSyntax<T>;
toFactory<T2>(factory: FactoryCreator<T2>): BindingWhenOnSyntax<T>;
toFunction(func: T): BindingWhenOnSyntax<T>;
toAutoFactory<T2>(serviceIdentifier: ServiceIdentifier<T2>): BindingWhenOnSyntax<T>;
toProvider<T2>(provider: ProviderCreator<T2>): BindingWhenOnSyntax<T>;
}
export interface BindingWhenOnSyntax<T> extends BindingWhenSyntax<T>, BindingOnSyntax<T> {}
export interface BindingWhenSyntax<T> {
when(constraint: (request: Request) => boolean): BindingOnSyntax<T>;
whenTargetNamed(name: string): BindingOnSyntax<T>;
whenTargetTagged(tag: string, value: any): BindingOnSyntax<T>;
whenInjectedInto(parent: (Function|string)): BindingOnSyntax<T>;
whenParentNamed(name: string): BindingOnSyntax<T>;
whenParentTagged(tag: string, value: any): BindingOnSyntax<T>;
whenAnyAncestorIs(ancestor: (Function|string)): BindingOnSyntax<T>;
whenNoAncestorIs(ancestor: (Function|string)): BindingOnSyntax<T>;
whenAnyAncestorNamed(name: string): BindingOnSyntax<T>;
whenAnyAncestorTagged(tag: string, value: any): BindingOnSyntax<T>;
whenNoAncestorNamed(name: string): BindingOnSyntax<T>;
whenNoAncestorTagged(tag: string, value: any): BindingOnSyntax<T>;
whenAnyAncestorMatches(constraint: (request: Request) => boolean): BindingOnSyntax<T>;
whenNoAncestorMatches(constraint: (request: Request) => boolean): BindingOnSyntax<T>;
}
}
export interface IKernel {
bind<T>(runtimeIdentifier: string): IBindingToSyntax<T>;
unbind(runtimeIdentifier: string): void;
unbindAll(): void;
get<T>(runtimeIdentifier: string): T;
getAll<T>(runtimeIdentifier: string): T[];
}
export var Kernel: interfaces.KernelConstructor;
export var KernelModule: interfaces.KernelModuleConstructor;
export var decorate: (decorator: (ClassDecorator|ParameterDecorator), target: any, parameterIndex?: number) => void;
export function injectable(): (typeConstructor: any) => void;
export function tagged(metadataKey: string, metadataValue: any): (target: any, targetKey: string, index?: number) => any;
export function named(name: string): (target: any, targetKey: string, index?: number) => any;
export function targetName(name: string): (target: any, targetKey: string, index: number) => any;
export function inject(serviceIdentifier: interfaces.ServiceIdentifier<any>): (target: any, targetKey: string, index?: number) => any;
export interface IKernelOptions {
middleware?: IMiddleware[];
modules?: IKernelModule[];
}
export function multiInject(
serviceIdentifier: interfaces.ServiceIdentifier<any>
): (target: any, targetKey: string, index?: number) => any;
interface IMiddleware extends Function {
(...args: any[]): any;
}
export function makePropertyInjectDecorator(kernel: interfaces.Kernel):
(serviceIdentifier: (string|Symbol|interfaces.Newable<any>)) => (proto: any, key: string) => void;
export interface IKernelModule extends Function {
(kernel: IKernel): void;
}
export function makePropertyInjectNamedDecorator(kernel: interfaces.Kernel):
(serviceIdentifier: (string|Symbol|interfaces.Newable<any>), named: string) => (proto: any, key: string) => void;
interface IBindingToSyntax<T> {
to(constructor: { new(...args: any[]): T; }): IBindingInWhenProxySyntax<T>;
toValue(value: T): IBindingInWhenProxySyntax<T>;
toConstructor<T2>(constructor: INewable<T2>): IBindingInWhenProxySyntax<T>;
toFactory<T2>(factory: IFactoryCreator<T2>): IBindingInWhenProxySyntax<T>;
toAutoFactory<T2>(): IBindingInWhenProxySyntax<T>;
toProvider<T2>(provider: IProviderCreator<T2>): IBindingInWhenProxySyntax<T>;
}
export function makePropertyInjectTaggedDecorator(kernel: interfaces.Kernel):
(serviceIdentifier: (string|Symbol|interfaces.Newable<any>), key: string, value: any) => (proto: any, propertyName: string) => void;
interface IBindingInWhenProxySyntax<T> {
inTransientScope(): IBindingInWhenProxySyntax<T>;
inSingletonScope(): IBindingInWhenProxySyntax<T>;
when(constraint: (request: IRequest) => boolean): IBindingInWhenProxySyntax<T>;
whenTargetNamed(name: string): IBindingInWhenProxySyntax<T>;
whenTargetTagged(tag: string, value: any): IBindingInWhenProxySyntax<T>;
proxy(fn: (injectable: T) => T): IBindingInWhenProxySyntax<T>;
}
export function makePropertyMultiInjectDecorator(kernel: interfaces.Kernel):
(serviceIdentifier: (string|Symbol|interfaces.Newable<any>)) => (proto: any, key: string) => void;
export interface IFactory<T> extends Function {
(): T;
}
// constraint helpers
export var traverseAncerstors: (request: interfaces.Request, constraint: (request: interfaces.Request) => boolean) => boolean;
export var taggedConstraint: (tag: string) => (value: any) => (request: interfaces.Request) => boolean;
export var namedConstraint: (value: any) => (request: interfaces.Request) => boolean;
export var typeConstraint: (type: (Function|string)) => (request: interfaces.Request) => boolean;
interface IFactoryCreator<T> extends Function {
(context: IContext): IFactory<T>;
}
export interface INewable<T> {
new(...args: any[]): T;
}
export interface IProvider<T> extends Function {
(): Promise<T>;
}
interface IProviderCreator<T> extends Function {
(context: IContext): IProvider<T>;
}
export interface IContext {
kernel: IKernel;
plan: IPlan;
addPlan(plan: IPlan): void;
}
export interface IPlan {
parentContext: IContext;
rootRequest: IRequest;
}
export interface IRequest {
service: string;
parentContext: IContext;
parentRequest: IRequest;
childRequests: IRequest[];
target: ITarget;
bindings: IBinding<any>[];
addChildRequest(
service: string,
bindings: (IBinding<any>|IBinding<any>[]),
target: ITarget): IRequest;
}
export interface IBinding<T> {
runtimeIdentifier: string;
implementationType: INewable<T>;
factory: IFactoryCreator<any>;
provider: IProviderCreator<any>;
constraint: (request: IRequest) => boolean;
proxyMaker: (injectable: T) => T;
cache: T;
scope: number; // BindingScope
type: number; // BindingType
}
export interface ITarget {
service: IQueryableString;
name: IQueryableString;
metadata: Array<IMetadata>;
isArray(): boolean;
isNamed(): boolean;
isTagged(): boolean;
matchesName(name: string): boolean;
matchesTag(name: IMetadata): boolean;
}
export interface IQueryableString {
startsWith(searchString: string): boolean;
endsWith(searchString: string): boolean;
contains(searchString: string): boolean;
equals(compareString: string): boolean;
value(): string;
}
export interface IMetadata {
key: string;
value: any;
}
export var Kernel: IKernelConstructor;
export var decorate: any;
export function inject(...typeIdentifiers: string[]): (typeConstructor: any) => void;
export var tagged: any;
export var named: any;
export var paramNames: any;
}
declare module "inversify" {
+2 -1
View File
@@ -179,6 +179,7 @@ declare namespace jasmine {
addCustomEqualityTester(equalityTester: CustomEqualityTester): void;
addMatchers(matchers: CustomMatcherFactories): void;
specFilter(spec: Spec): boolean;
throwOnExpectationFailure(value: boolean): void;
}
interface FakeTimer {
@@ -301,7 +302,7 @@ declare namespace jasmine {
toContain(expected: any, expectationFailOutput?: any): boolean;
toBeLessThan(expected: number, expectationFailOutput?: any): boolean;
toBeGreaterThan(expected: number, expectationFailOutput?: any): boolean;
toBeCloseTo(expected: number, precision: any, expectationFailOutput?: any): boolean;
toBeCloseTo(expected: number, precision?: any, expectationFailOutput?: any): boolean;
toThrow(expected?: any): boolean;
toThrowError(message?: string | RegExp): boolean;
toThrowError(expected?: new (...args: any[]) => Error, message?: string | RegExp): boolean;
@@ -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
});
+3
View File
@@ -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;
}
@@ -0,0 +1,14 @@
/// <reference path="./jquery-truncate-html.d.ts" />
function truncateHtmlString(): string {
return $.truncate('<p>Stuff and <i>Nonsense</i></p>', {
length: 13
});
}
function truncateVirtualElement (): JQuery {
return $('<p>Stuff and <i>Nonsense</i></p>').truncate({
length: 13
});
}
+22
View File
@@ -0,0 +1,22 @@
// Type definitions for jQuery-truncate-html.js
// Project: https://github.com/kbwood/timeentry
// Definitions by: Abraão Alves <https://github.com/abraaoalves>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface TruncateOptions{
length?: number;
stripTags?: boolean;
words?: boolean;
noBreaks?: boolean;
ellipsis?: string;
}
interface JQuery{
truncate(options: TruncateOptions) : JQuery;
}
interface JQueryStatic {
truncate(html: string, options: TruncateOptions) : string;
}
@@ -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 <https://github.com/EnableSoftware>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+16 -1
View File
@@ -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);
});
});
var options : IJQuerySlimScrollOptions = {
destroy: true,
position: 'left'
};
$('#slimtest3').slimScroll(options);
+77 -25
View File
@@ -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 <https://github.com/Promact>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
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 {
+18
View File
@@ -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.
*/
+12
View File
@@ -0,0 +1,12 @@
/// <reference path='jwt-simple.d.ts' />
import jwt = require('jwt-simple');
var payload = { foo: 'bar' };
var secret:string = 'xxx';
// encode
var token = jwt.encode(payload, secret);
// decode
var decoded = jwt.decode(token, secret);
console.log(decoded); //=> { foo: 'bar' }
+22
View File
@@ -0,0 +1,22 @@
// Type definitions for jwt-simple v0.2.0
// Project: https://github.com/hokaccha/node-jwt-simple
// Definitions by: Ken Fukuyama <https://github.com/kenfdev>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "jwt-simple" {
/**
* Decode jwt
* @param token
* @param key
* @param noVerify
* @api public
*/
export function decode(token:any, key:string, noVerify?:boolean):any;
/**
* Encode jwt
* @param payload
* @param key
* @param algorithm default is HS256
* @api public
*/
export function encode(payload:any, key:string, algorithm?:string):string;
}
+6 -4
View File
@@ -1,6 +1,6 @@
// Type definitions for jwt-simple v0.2.0
// Type definitions for jwt-simple v0.5.0
// Project: https://github.com/hokaccha/node-jwt-simple
// Definitions by: Ken Fukuyama <https://github.com/kenfdev>
// Definitions by: Ken Fukuyama <https://github.com/kenfdev>, Gael Magnan <https://github.com/GaelMagnan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "jwt-simple" {
/**
@@ -8,15 +8,17 @@ declare module "jwt-simple" {
* @param token
* @param key
* @param noVerify
* @param algorithm default is HS256
* @api public
*/
export function decode(token:any, key:string, noVerify?:boolean):any;
export function decode(token:any, key:string, noVerify?:boolean, algorithm?:string):any;
/**
* Encode jwt
* @param payload
* @param key
* @param algorithm default is HS256
* @param options
* @api public
*/
export function encode(payload:any, key:string, algorithm?:string):string;
export function encode(payload:any, key:string, algorithm?:string, options?:any):string;
}
+2
View File
@@ -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;

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