Merge remote-tracking branch 'upstream/master' into merge_7_25

This commit is contained in:
Ryan Cavanaugh 2016-07-27 10:57:46 -07:00
commit b488f3cb5f
312 changed files with 30700 additions and 5251 deletions

View File

@ -1123,10 +1123,11 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](moment/moment.d.ts) [Moment.js](https://github.com/timrwood/moment) by [Michael Lakerveld](https://github.com/Lakerfield), [Aaron King](https://github.com/kingdango), [Hiroki Horiuchi](https://github.com/horiuchi), [Dick van den Brink](https://github.com/DickvdBrink), [Adi Dahiya](https://github.com/adidahiya), [Matt Brooks](https://github.com/EnableSoftware)
* [:link:](moment-range/moment-range.d.ts) [Moment.js](https://github.com/gf3/moment-range) by [Bart van den Burg](https://github.com/Burgov), [Wilgert Velinga](https://github.com/wilgert)
* [:link:](mongodb/mongodb.d.ts) [MongoDB](https://github.com/mongodb/node-mongodb-native/tree/2.1) by [Federico Caselli](https://github.com/CaselIT)
* [:link:](mongoose/mongoose.d.ts) [Mongoose](http://mongoosejs.com) by [horiuchi](https://github.com/horiuchi)
* [:link:](mongoose/mongoose.d.ts) [Mongoose](http://mongoosejs.com) by [simonxca](https://github.com/simonxca), [horiuchi](https://github.com/horiuchi)
* [:link:](mongoose-auto-increment/mongoose-auto-increment.d.ts) [mongoose-auto-increment](https://github.com/codetunnel/mongoose-auto-increment) by [Aya Morisawa](https://github.com/AyaMorisawa)
* [:link:](mongoose-deep-populate/mongoose-deep-populate.d.ts) [mongoose-deep-populate](https://github.com/buunguyen/mongoose-deep-populate) by [Aya Morisawa](https://github.com/AyaMorisawa)
* [:link:](mongoose-mock/mongoose-mock.d.ts) [mongoose-mock](https://github.com/JohanObrink/mongoose-mock) by [jt000](https://github.com/jt000)
* [:link:](mongoose-promise/mongoose-promise.d.ts) [mongoose-promise](http://mongoosejs.com/docs/api.html#promise-js) by [simonxca](https://github.com/simonxca)
* [:link:](morgan/morgan.d.ts) [morgan](https://github.com/expressjs/morgan) by [James Roland Cabresos](https://github.com/staticfunction)
* [:link:](mousetrap/mousetrap-global-bind.d.ts) [Mousetrap 1.4.6's global-bind extension](http://craig.is/killing/mice#extensions.global) by [Andrew Bradley](https://github.com/cspotcode)
* [:link:](mousetrap/mousetrap.d.ts) [Mousetrap 1.5.x](http://craig.is/killing/mice) by [Dániel Tar](https://github.com/qcz)

View File

@ -20,4 +20,5 @@ Logging.level = 4;
auth.info("Logging message");
var userName: string = auth.getCachedUser().userName;
var userName: string = auth.getCachedUser().userName;var postLogoutRedirectUrl = auth.config.postLogoutRedirectUri;
var isValidRequest = auth.getRequestInfo('hash').valid;

44
adal/index.d.ts vendored
View File

@ -13,29 +13,30 @@ declare module 'adal' {
declare namespace adal {
interface Config {
tenant?: string,
clientId: string,
redirectUri?: string,
cacheLocation?: string,
displayCall?: (urlNavigate: string) => any,
correlationId?: string,
loginResource?: string,
resource?: string
endpoints?: any // If you need to send CORS api requests.
extraQueryParameter?: string
tenant?: string;
clientId: string;
redirectUri?: string;
cacheLocation?: string;
displayCall?: (urlNavigate: string) => any;
correlationId?: string;
loginResource?: string;
resource?: string;
endpoints?: any; // If you need to send CORS api requests.
extraQueryParameter?: string;
postLogoutRedirectUri?: string; // redirect url after succesful logout operation
}
interface User {
userName: string,
profile: any
userName: string;
profile: any;
}
interface RequestInfo {
valid: boolean,
parameters: any,
stateMatch: boolean,
stateResponse: string,
requestType: string
valid: boolean;
parameters: any;
stateMatch: boolean;
stateResponse: string;
requestType: string;
}
interface Logging {
@ -64,6 +65,10 @@ declare namespace adal {
* Saves the resulting Idtoken in localStorage.
*/
login(): void;
/**
* Indicates whether login is in progress now or not.
*/
loginInProgress(): boolean;
/**
@ -147,6 +152,11 @@ declare namespace adal {
*/
getResourceForEndpoint(endpoint: string): string;
/**
* Handles redirection after login operation.
* Gets access token from url and saves token to the (local/session) storage
* or saves error in case unsuccessful login.
*/
handleWindowCallback(): void;
log(level: number, message: string, error: any): void;

13
agenda/index.d.ts vendored
View File

@ -18,8 +18,8 @@ interface ResultCallback<T> {
(err?: Error, result?: T): void;
}
declare class Agenda extends EventEmitter {
declare class Agenda extends EventEmitter {
/**
* Constructs a new Agenda object.
* @param config Optional configuration to initialize the Agenda.
@ -164,6 +164,7 @@ declare class Agenda extends EventEmitter {
}
declare namespace Agenda {
/**
* Agenda Configuration.
*/
@ -318,6 +319,11 @@ declare namespace Agenda {
* The date/time the job last failed.
*/
failedAt: Date;
/**
* Job's state
*/
disabled: boolean
}
/**
@ -408,6 +414,11 @@ declare namespace Agenda {
* @param cb Called after the job has been saved to the database.
*/
touch(cb?: Callback): void;
/**
* Calculates next time the job should run
*/
computeNextRunAt(): Job;
}
interface JobOptions {

View File

@ -71,7 +71,7 @@ declare module 'angular' {
* @returns current animation state
*/
enabled(element: JQuery, value?: boolean): boolean;
enabled(value: boolean): boolean;
enabled(value?: boolean): boolean;
/**
* Cancels the provided animation.

View File

@ -14,6 +14,11 @@ declare namespace angular.environment {
* loads the correct environment variables.
*/
check: () => void;
/**
* Retrieves the correct version of a
* variable for the current environment.
*/
read: (key: string) => any;
}
interface Service {
/**

View File

@ -30,7 +30,11 @@ myApp.config((
myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng.material.IBottomSheetService) => {
$scope['openBottomSheet'] = () => {
$mdBottomSheet.show({
template: '<md-bottom-sheet>Hello!</md-bottom-sheet>'
template: '<md-bottom-sheet>Hello!</md-bottom-sheet>',
clickOutsideToClose: true,
disableBackdrop: true,
disableParentScroll: false,
parent: () => {}
});
};
$scope['hideBottomSheet'] = $mdBottomSheet.hide.bind($mdBottomSheet, 'hide');
@ -115,6 +119,14 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia
$scope['close'] = () => $mdSidenav(componentId).close();
$scope['isOpen'] = $mdSidenav(componentId).isOpen();
$scope['isLockedOpen'] = $mdSidenav(componentId).isLockedOpen();
$scope['asyncLookup'] = $mdSidenav(componentId, true).then((instance) => {
instance.toggle();
instance.open();
instance.close();
instance.isOpen();
instance.isLockedOpen();
});
});
myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => {

View File

@ -1,13 +1,12 @@
// Type definitions for Angular Material 1.0.0-rc5+ (angular.material module)
// Type definitions for Angular Material 1.1.0-rc5+ (angular.material module)
// Project: https://github.com/angular/material
// Definitions by: Alex Staroselsky <https://github.com/AlStar01>, Blake Bigelow <https://github.com/blbigelow>, Peter Hajdu <https://github.com/PeterHajdu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import * as angular from 'angular';
declare module 'angular-material' {
}
declare var _: string;
export = _;
declare module 'angular' {
export namespace material {
@ -18,11 +17,12 @@ declare module 'angular' {
preserveScope?: boolean; // default: false
controller?: string | Function;
locals?: { [index: string]: any };
targetEvent?: MouseEvent;
resolve?: { [index: string]: angular.IPromise<any> }
clickOutsideToClose?: boolean;
disableBackdrop?: boolean;
escapeToClose?: boolean;
resolve?: { [index: string]: angular.IPromise<any> };
controllerAs?: string;
bindToController?: boolean;
parent?: string | Element | JQuery; // default: root node
parent?: Function | string | Object; // default: root node
disableParentScroll?: boolean; // default: true
}
@ -68,16 +68,7 @@ declare module 'angular' {
interface IPromptDialog extends IPresetDialog<IPromptDialog> {
cancel(cancel: string): IPromptDialog;
placeholder(placeholder: string): IPromptDialog;
}
interface IPromptDialog extends IPresetDialog<IPromptDialog> {
placeholder(placeholder: string): IPromptDialog;
}
interface IPromptDialog extends IPresetDialog<IPromptDialog> {
cancel(cancel: string): IPromptDialog;
placeholder(placeholder: string): IPromptDialog;
initialValue(value: string): IPromptDialog;
initialValue(initialValue: string): IPromptDialog;
}
interface IDialogOptions {
@ -104,8 +95,8 @@ declare module 'angular' {
onShowing?: Function;
onComplete?: Function;
onRemoving?: Function;
fullscreen?: boolean; // default: false
skipHide?: boolean;
fullscreen?: boolean; // default: false
}
interface IDialogService {
@ -142,6 +133,7 @@ declare module 'angular' {
}
interface ISidenavService {
(component: string, enableWait: boolean): angular.IPromise<ISidenavObject>;
(component: string): ISidenavObject;
}
@ -307,13 +299,13 @@ declare module 'angular' {
panelClass?: string;
zIndex?: number; // default: 80
position?: IPanelPosition;
hasBackdrop?: boolean; // default: true
clickOutsideToClose?: boolean; // default: false
escapeToClose?: boolean; // default: false
trapFocus?: boolean; // default: false
focusOnOpen?: boolean; // default: true
fullscreen?: boolean; // default: false
animation?: IPanelAnimation;
hasBackdrop?: boolean; // default: false
disableParentScroll?: boolean; // default: false
onDomAdded?: Function;
onOpenComplete?: Function;

View File

@ -11,7 +11,7 @@ declare module 'angular' {
export namespace translate {
interface ITranslationTable {
[key: string]: any;
[key: string]: string | ITranslationTable;
}
interface ILanguageKeyAlias {
@ -94,7 +94,7 @@ declare module 'angular' {
storageKey(): string;
storageKey(key: string): void; // JeroMiya - the library should probably return ITranslateProvider but it doesn't here
useUrlLoader(url: string): ITranslateProvider;
useStaticFilesLoader(options: IStaticFilesLoaderOptions): ITranslateProvider;
useStaticFilesLoader(options: IStaticFilesLoaderOptions | { files: IStaticFilesLoaderOptions[] }): ITranslateProvider;
useLoader(loaderFactory: string, options?: any): ITranslateProvider;
useLocalStorage(): ITranslateProvider;
useCookieStorage(): ITranslateProvider;

View File

@ -379,12 +379,18 @@ declare module 'angular' {
* @default 'model-open'
*/
openedClass?: string;
/**
* CSS class(es) to be added to the top modal window.
*/
windowTopClass?: string;
/**
* Appends the modal to a specific element.
*
* @default 'body'
*/
appendTo?: angular.IAugmentedJQuery;
}
interface IModalStackService {

View File

@ -42,6 +42,10 @@ declare module 'angular' {
* Function, returns HTML content string
*/
templateProvider?: Function | Array<string | Function>;
/**
* String, component name
*/
component?: string;
/**
* A controller paired to the state. Function, annotated array or name as String
*/

View File

@ -53,4 +53,46 @@ declare namespace angular.xeditable {
*/
activationEvent: string;
}
interface IEditableFormController extends angular.IFormController {
/**
* Shows form with editable controls.
*/
$show(): void;
/**
* Hides form with editable controls without saving.
*/
$hide(): void;
/**
* Sets focus on form field specified by `name`.<br/>
* When trying to set the focus on a form field of a new row in the editable table, the `$activate` call needs to be wrapped in a `$timeout` call so that the form is rendered before the `$activate` function is called.
*
* @param name name of field
*/
$activate(name: string): void;
/**
* Triggers `oncancel` event and calls `$hide()`.
*/
$cancel(): void;
$setWaiting(value: boolean): void;
/**
* Shows error message for particular field.
*
* @param name name of field
* @param msg error message
*/
$setError(name: string, msg: string): void;
$submit(): void;
$save(): void;
}
}

View File

@ -1097,6 +1097,12 @@ function parseTyping() {
}
}
function parseWithParams() {
var $parse: angular.IParseService;
var compiledExp = $parse('a.b.c', () => null);
var compiledExp = $parse('a.b.c', null, false);
}
function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjectorService {
if (mode === 'debug') {
return angular.bootstrap(element, ['main', function($provide: ng.auto.IProvideService) {
@ -1104,11 +1110,11 @@ function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjector
$delegate['debug'] = true;
});
}, 'debug-helpers'], {
debugInfoEnabled: true
strictDi: true
});
}
return angular.bootstrap(element, ['main'], {
debugInfoEnabled: false
strictDi: false
});
}

14
angular/index.d.ts vendored
View File

@ -43,7 +43,6 @@ declare namespace angular {
interface IAngularBootstrapConfig {
strictDi?: boolean;
debugInfoEnabled?: boolean;
}
///////////////////////////////////////////////////////////////////////////
@ -876,7 +875,7 @@ declare namespace angular {
// see http://docs.angularjs.org/api/ng.$parseProvider
///////////////////////////////////////////////////////////////////////////
interface IParseService {
(expression: string): ICompiledExpression;
(expression: string, interceptorFn?: (value: any, scope: IScope, locals: any) => any, expensiveChecks?: boolean): ICompiledExpression;
}
interface IParseProvider {
@ -988,7 +987,10 @@ declare namespace angular {
// DocumentService
// see http://docs.angularjs.org/api/ng.$document
///////////////////////////////////////////////////////////////////////////
interface IDocumentService extends JQuery {}
interface IDocumentService extends JQuery {
// Must return intersection type for index signature compatibility with JQuery
[index: number]: HTMLElement & Document;
}
///////////////////////////////////////////////////////////////////////////
// ExceptionHandlerService
@ -1718,6 +1720,12 @@ declare namespace angular {
* Whether transclusion is enabled. Enabled by default.
*/
transclude?: boolean | string | {[slot: string]: string};
/**
* Requires the controllers of other directives and binds them to this component's controller.
* The object keys specify the property names under which the required controllers (object values) will be bound.
* Note that the required controllers will not be available during the instantiation of the controller,
* but they are guaranteed to be available just before the $onInit method is executed!
*/
require?: {[controller: string]: string};
}

View File

@ -886,7 +886,7 @@ declare namespace angular {
// see http://docs.angularjs.org/api/ng.$parseProvider
///////////////////////////////////////////////////////////////////////////
interface IParseService {
(expression: string): ICompiledExpression;
(expression: string, interceptorFn?: (value: any, scope: IScope, locals: any) => any, expensiveChecks?: boolean): ICompiledExpression;
}
interface IParseProvider {

View File

@ -0,0 +1,82 @@
/// <reference path="../react/react.d.ts" />
/// <reference path="./aphrodite.d.ts" />
import * as React from "react";
import { StyleSheet, css, StyleSheetServer, StyleSheetTestUtils } from "aphrodite";
const styles = StyleSheet.create({
red: {
backgroundColor: 'red'
},
blue: {
backgroundColor: 'blue'
},
hover: {
':hover': {
backgroundColor: 'red'
}
},
small: {
'@media (max-width: 600px)': {
backgroundColor: 'red',
}
}
});
const coolFont = {
fontFamily: "CoolFont",
fontStyle: "normal",
fontWeight: "normal",
src: "url('coolfont.woff2') format('woff2')"
};
const withFont = StyleSheet.create({
headingText: {
fontFamily: coolFont,
fontSize: 20
},
bodyText: {
fontFamily: [coolFont, "sans-serif"],
fontSize: 12
}
});
class App extends React.Component<{}, {}> {
render() {
return <div>
<span className={css(styles.red)}>
This is red.
</span>
<span className={css(styles.hover)}>
This turns red on hover.
</span>
<span className={css(styles.small)}>
This turns red when the browser is less than 600px width.
</span>
<span className={css(styles.red, styles.blue)}>
This is blue.
</span>
<span className={css(styles.blue, styles.small)}>
This is blue and turns red when the browser is less than
600px width.
</span>
<span className={css(withFont.bodyText)}>
With font
</span>
</div>;
}
}
const output = StyleSheetServer.renderStatic(() => {
return "test";
});
output.css.content;
output.css.renderedClassNames;
output.html;
StyleSheet.rehydrate(output.css.renderedClassNames);
StyleSheetTestUtils.suppressStyleInjection();
StyleSheetTestUtils.clearBufferAndResumeStyleInjection();

76
aphrodite/aphrodite.d.ts vendored Normal file
View File

@ -0,0 +1,76 @@
// Type definitions for Aphrodite 0.5.0
// Project: https://github.com/Khan/aphrodite
// Definitions by: Alexey Svetliakov <https://github.com/asvetliakov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../react/react.d.ts" />
declare module "aphrodite" {
import * as React from "react";
/**
* Aphrodite style declaration
*/
export interface StyleDeclaration {
[key: string]: React.CSSProperties;
}
interface StyleSheetStatic {
/**
* Create style sheet
*/
create<T extends StyleDeclaration>(styles: T): T;
/**
* Rehydrate class names from server renderer
*/
rehydrate(renderedClassNames: string[]): void;
}
export var StyleSheet: StyleSheetStatic;
/**
* Get class names from passed styles
*/
export function css(...styles: any[]): string;
interface StaticRendererResult {
html: string;
css: {
content: string;
renderedClassNames: string[];
}
}
/**
* Utilities for using Aphrodite server-side.
*/
interface StyleSheetServerStatic {
renderStatic(renderFunc: () => string): StaticRendererResult;
}
export var StyleSheetServer: StyleSheetServerStatic;
interface StyleSheetTestUtilsStatic {
/**
* Prevent styles from being injected into the DOM.
*
* This is useful in situations where you'd like to test rendering UI
* components which use Aphrodite without any of the side-effects of
* Aphrodite happening. Particularly useful for testing the output of
* components when you have no DOM, e.g. testing in Node without a fake DOM.
*
* Should be paired with a subsequent call to
* clearBufferAndResumeStyleInjection.
*/
suppressStyleInjection(): void;
/**
* Opposite method of preventStyleInject.
*/
clearBufferAndResumeStyleInjection(): void;
}
export var StyleSheetTestUtils: StyleSheetTestUtilsStatic;
}
declare module "aphrodite/no-important" {
export * from "aphrodite";
}

View File

@ -0,0 +1,10 @@
/// <reference path="app-root-path.d.ts" />
import * as root from 'app-root-path';
let resolvedPath: string;
resolvedPath = root.resolve('../dir');
resolvedPath = root.path;
resolvedPath = root.toString();
let resolvedModule: any = root.require('app-root-path');
root.setPath('C:\\app-root');

39
app-root-path/app-root-path.d.ts vendored Normal file
View File

@ -0,0 +1,39 @@
// Type definitions for app-root-path 1.2.1
// Project: https://github.com/inxilpro/node-app-root-path
// Definitions by: Shant Marouti <https://github.com/shantmarouti>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'app-root-path' {
interface RootPath {
/**
* Application root directory absolute path
* @type {string}
*/
path: string;
/**
* Resolves relative path from root to absolute path
* @param {string} pathToModule
* @returns {string}
*/
resolve(pathToModule: string): string;
/**
* Resolve module by relative addressing from root
* @param {string} pathToModule
* @returns {*}
*/
require(pathToModule: string): any;
/**
* Explicitly set root path
* @param {string} explicitlySetPath
*/
setPath(explicitlySetPath: string): void;
toString(): string;
}
var RootPath: RootPath;
export = RootPath;
}

View File

@ -1,4 +1,4 @@
// Type definitions for ApplicationInsights-JS v0.22.14
// Type definitions for ApplicationInsights-JS v0.23.2
// Project: https://github.com/Microsoft/ApplicationInsights-JS
// Definitions by: Kamil Szostak <https://github.com/kamilszostak>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@ -788,3 +788,9 @@ declare module Microsoft.ApplicationInsights {
_onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error): any;
}
}
declare module 'applicationinsights-js' {
export = appInsights;
}
declare var appInsights: Microsoft.ApplicationInsights.IAppInsights;

View File

@ -1,4 +1,4 @@
// Type definitions for ArcGIS API for JavaScript v3.16
// Type definitions for ArcGIS API for JavaScript v3.17
// Project: http://js.arcgis.com
// Definitions by: Esri <http://www.esri.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@ -18,7 +18,6 @@ declare module "esri" {
import BasemapLayer = require("esri/dijit/BasemapLayer");
import Symbol = require("esri/symbols/Symbol");
import BookmarkItem = require("esri/dijit/BookmarkItem");
import Units = require("esri/units");
import Color = require("esri/Color");
import LocationProviderBase = require("esri/tasks/locationproviders/LocationProviderBase");
import PictureMarkerSymbol = require("esri/symbols/PictureMarkerSymbol");
@ -45,6 +44,7 @@ declare module "esri" {
import QueryTask = require("esri/tasks/QueryTask");
import TextSymbol = require("esri/symbols/TextSymbol");
import StandardGeographyQueryTask = require("esri/tasks/geoenrichment/StandardGeographyQueryTask");
import WMSLayerInfo = require("esri/layers/WMSLayerInfo");
import WMTSLayerInfo = require("esri/layers/WMTSLayerInfo");
export interface AGSMouseEvent extends MouseEvent {
@ -354,7 +354,7 @@ declare module "esri" {
/** Radius of the circle. */
radius?: number;
/** Unit of the radius. */
radiusUnit?: Units;
radiusUnit?: string;
}
export interface CircleOptions2 {
/** The center point of the circle. */
@ -366,7 +366,7 @@ declare module "esri" {
/** The radius of the circle. */
radius?: number;
/** Unit of the radius. */
radiusUnit?: Units;
radiusUnit?: string;
}
export interface ClassedColorSliderOptions {
/** Data map containing renderer information. */
@ -643,6 +643,8 @@ declare module "esri" {
minStops?: number;
/** When true, stops on the route are re-ordered to provide an optimal route. */
optimalRoute?: boolean;
/** If specified, this specifies the portal where the produced route layers are going to be stored and accessed. */
portalUrl?: string;
/** URL link to a custom print page. */
printPage?: string;
/** If available, this print task is used to display an overview map of the route on the directions print page (Added at v3.11). */
@ -677,6 +679,8 @@ declare module "esri" {
showReturnToStartOption?: boolean;
/** Display the 'Show Reverse Stops' button. */
showReverseStopsButton?: boolean;
/** Applicable if the widget works with a Network Analyst Server federated with ArcGIS Online or Portal. */
showSaveButton?: boolean;
/** Highlight the route segment when a directions step is clicked. */
showSegmentHighlight?: boolean;
/** Display a popup with segment details when a direction step is clicked. */
@ -911,6 +915,8 @@ declare module "esri" {
layer: FeatureLayer;
}
export interface FeatureTableOptions {
/** The number of features a service will try to fetch. */
batchCount?: number;
/** Object defining the date options specifically for formatting date and time editors. */
dateOptions?: any;
/** Sets the editing state for the FeatureTable. */
@ -931,12 +937,18 @@ declare module "esri" {
menuFunctions?: any[];
/** Attribute fields to include in the FeatureTable. */
outFields?: string[];
/** Displays or hides the attachment column. */
showAttachments?: boolean;
/** Displays the data type of the field right under the field label. */
showDataTypes?: boolean;
/** Displays or hides total number of features and selected number of features in the grid header. */
showFeatureCount?: boolean;
/** Displays or hides the FeatureTable header. */
showGridHeader?: boolean;
/** Displays or hides 'Options' drop-down menu of the FeatureTable. */
showGridMenu?: boolean;
/** Displays or hides the 'Statistics' option in column menus for numeric fields. */
showStatistics?: boolean;
/** Enables an interaction between the map and the feature table. */
syncSelection?: boolean;
/** Enables pan/zoom to selected features on the map when the table in 'sync selection' mode. */
@ -1187,10 +1199,20 @@ declare module "esri" {
gdbVersion?: string;
}
export interface ImageServiceMeasureOptions {
/** The angular unit in which directions of line segments will be calculated. */
angularUnit?: string;
/** The area unit in which areas of polygons will be calculated. */
areaUnit?: string;
/** Defines whether to show the widget result in a popup or in the widget's result area when the widget has 'toolbar' layout. */
displayMeasureResultInPopup?: boolean;
/** Symbol to be used when drawing a polygon or extent. */
fillSymbol?: SimpleFillSymbol;
/** Image service layer with which the toolbar is associated. */
layer: ArcGISImageServiceLayer;
/** Defines the layout of the widget. */
layout?: string;
/** The linear unit in which height, length, or perimeters will be calculated. */
linearUnit?: string;
/** Symbol to be used when drawing a line. */
lineSymbol?: SimpleLineSymbol;
/** Map instance with which the toolbar is associate. */
@ -1402,9 +1424,9 @@ declare module "esri" {
/** Flag for showing full list of units in the Location tool. */
advancedLocationUnits?: boolean;
/** The default area unit for the measure area tool. */
defaultAreaUnit?: Units;
defaultAreaUnit?: string;
/** The default length unit for the measure distance tool. */
defaultLengthUnit?: Units;
defaultLengthUnit?: string;
/** Allows the user to immediately measure previously-created geometry on dijit creation. */
geometry?: Point | Polyline | Polygon;
/** Line symbol used to draw the lines for the measure line and measure distance tools. */
@ -2190,6 +2212,28 @@ declare module "esri" {
/** The well-known ID of the spatial reference used by the WFSLayer. */
wkid?: string;
}
export interface WMSLayerInfoOptions {
/** All the bounding extents defined for this layer. */
allExtents?: Extent[];
/** A description of the WMS layer. */
description?: string;
/** The extent of the WMS Layer. */
extent?: Extent;
/** The URL to the legend image. */
legendURL?: string;
/** The name of the WMS layer. */
name: string;
/** Returns true if the layer can be queried and the service supports GetFeatureInfo with either text/html or text/plain formats. */
queryable?: boolean;
/** Indicates if this layer should be included in the popup. */
showPopup?: boolean;
/** All the spatial references defined for this layer. */
spatialReferences?: SpatialReference[];
/** WMSLayerInfos of the layer's sub layers. */
subLayers?: WMSLayerInfo[];
/** The title of the WMS layer. */
title?: string;
}
export interface WMSLayerOptions {
/** Specify the map image format, valid options are png,jpg,bmp,gif,svg. */
format?: string;
@ -3732,6 +3776,8 @@ declare module "esri/dijit/Directions" {
maxStopsReached: boolean;
/** Read-only: The graphic for the calculated route. */
mergedRouteGraphic: Graphic;
/** If specified, this specifies the portal where the produced route layers are going to be stored and accessed. */
portalUrl: string;
/** Routing parameters for the widget. */
routeParams: RouteParameters;
/** Routing task for the widget. */
@ -3744,6 +3790,8 @@ declare module "esri/dijit/Directions" {
showClearButton: boolean;
/** If true, the toggle button group allowing user to choose between Miles and Kilometers is shown. */
showMilesKilometersOption: boolean;
/** Applicable if the widget works with a Network Analyst Server federated with ArcGIS Online or Portal. */
showSaveButton: boolean;
/** If true, and supported by the service, then two toggle button groups are shown: one to allow user to choose between driving a car, a truck, or walking, and one more group to choose between fastest or shortest routes. */
showTravelModesOption: boolean;
/** An array of graphics that define the stop locations along the route. */
@ -3792,6 +3840,11 @@ declare module "esri/dijit/Directions" {
* @param index The index of the route segment to highlight.
*/
highlightSegment(index: number): void;
/**
* Loads a stored route layer from either ArcGIS Online or Portal
* @param itemId The itemId of the stored route layer from either ArcGIS Online or Portal.
*/
loadRoute(itemId: string): any;
/**
* Remove the stop at the specified index.
* @param index The index of the stop to remove.
@ -3801,6 +3854,16 @@ declare module "esri/dijit/Directions" {
removeStops(): any;
/** Resets the directions widget removing any directions, stops and map graphics. */
reset(): any;
/**
* Specify the language used for the directions.
* @param locale The locale used for the directions.
*/
setDirectionsLanguage(locale: string): any;
/**
* Specify the length units used for the directions widget.
* @param units The length units used for the directions widget.
*/
setDirectionsLengthUnits(units: string): any;
/**
* If widget runs with Travel Modes enabled, call this method to switch to particular Travel mode programmatically.
* @param travelModeName Travel mode.
@ -3843,10 +3906,16 @@ declare module "esri/dijit/Directions" {
on(type: "directions-finish", listener: (event: { result: RouteResult; target: Directions }) => void): esri.Handle;
/** Fires when the route services starts to calculate the route. */
on(type: "directions-start", listener: (event: { target: Directions }) => void): esri.Handle;
/** Fires after a user clicks the Save or Save as New button and subsequently does not have permission to create an item in ArcGIS Online or Portal. */
on(type: "feature-collection-created", listener: (event: { target: Directions }) => void): esri.Handle;
/** Fires when the directions widget has fully loaded. */
on(type: "load", listener: (event: { target: Directions }) => void): esri.Handle;
/** Fires when the widget starts or stops listening for map clicks. */
on(type: "map-click-active", listener: (event: { mapClickActive: boolean; target: Directions }) => void): esri.Handle;
/** Fires after a user clicks the Save or Save as New button for the first time in order to store a new route in either ArcGIS Online or Portal. */
on(type: "route-item-created", listener: (event: { target: Directions }) => void): esri.Handle;
/** Fires when a existing route layer item is successfully updated in ArcGIS Online or Portal after user clicks the Save button. */
on(type: "route-item-updated", listener: (event: { target: Directions }) => void): esri.Handle;
/** Fired when you hover over a route segment in the directions display. */
on(type: "segment-highlight", listener: (event: { graphic: Graphic; target: Directions }) => void): esri.Handle;
/** Fires when a route segment is selected in the directions display. */
@ -3901,6 +3970,8 @@ declare module "esri/dijit/FeatureTable" {
/** Creates an instance of the FeatureTable widget within the provided DOM node. */
class FeatureTable {
/** The number of features a service will try to fetch. */
batchCount: number;
/** Read-only: A reference to the column objects and their parameters. */
columns: any[];
/** Read-only: Reference to the dataStore used by the dGrid. */
@ -3909,6 +3980,8 @@ declare module "esri/dijit/FeatureTable" {
dateOptions: any;
/** Sets the editing state for the FeatureTable. */
editable: boolean;
/** Event trigger(s) used to display editing interface for an individual cell. */
editOn: string | any;
/** Read-only: Number of records displayed in FeatureTable. */
featureCount: number;
/** The featureLayer that the table is associated with. */
@ -3937,12 +4010,18 @@ declare module "esri/dijit/FeatureTable" {
selectedRowIds: number[];
/** Read-only: Each element in the array is an object that contains name-value pair of fields and field values associated with the selected rows. */
selectedRows: any[];
/** Displays the data type of the field right under the field label in the column header. */
/** Displays or hides the attachment column. */
showAttachments: boolean;
/** Displays or hides the data type of the field right under the field label in the column header. */
showDataTypes: boolean;
/** Displays or hides total number of features and selected number of features in the grid header. */
showFeatureCount: boolean;
/** Displays or hides the FeatureTable header. */
showGridHeader: boolean;
/** Displays or hides 'Options' drop-down menu of the FeatureTable. */
showGridMenu: boolean;
/** Displays or hides the 'Statistics' option in column menus for numeric fields. */
showStatistics: boolean;
/** Enables an interaction between the map and the feature table. */
syncSelection: boolean;
/** Enables pans to selected features on the map when the table in 'sync selection' mode. */
@ -3953,6 +4032,29 @@ declare module "esri/dijit/FeatureTable" {
* @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into.
*/
constructor(params: esri.FeatureTableOptions, srcNodeRef: Node | string);
/** Removes all current selections including subsets from filterSelectedRecords(). */
clearSelection(): void;
/** Destroys the FeatureTable widget. */
destroy(): void;
/**
* Allows users to see the sub-set of currently selected records (uses dGrid.query).
* @param toggle When true only a subset of currently selected features will be displayed in the FeatureTable.
*/
filterSelectedRecords(toggle: boolean): void;
/**
* Queries and gets selected features from the FeatureLayer instead of the store.
* @param id Array of row ids
*/
getFeatureDataById(id: number[]): any;
/**
* Gets row object by the row ID.
* @param id row ID
*/
getRowDataById(id: number): any;
/** Refreshes the data in the grid. */
refresh(): void;
/** Resizes the grid's container. */
resize(): void;
/** Finalizes the creation of the widget. */
startup(): void;
/** Fires when the grid column is resized. */
@ -4286,8 +4388,13 @@ declare module "esri/dijit/ImageServiceMeasure" {
/**
* Creates an instance of the ImageServiceMeasure widget.
* @param params An Object containing constructor options.
* @param srcNode Reference or id of the HTML element where the widget should be rendered.
*/
constructor(params: esri.ImageServiceMeasureOptions);
constructor(params: esri.ImageServiceMeasureOptions, srcNode: Node | string);
/** Destroys the ImageServiceMeasure widget. */
destroy(): void;
/** Finalizes the creation of the widget. */
startup(): void;
}
export = ImageServiceMeasure;
}
@ -4528,9 +4635,14 @@ declare module "esri/dijit/LayerSwipe" {
declare module "esri/dijit/Legend" {
import esri = require("esri");
import Map = require("esri/map");
/** The legend dijit displays a label and symbol for some or all of the layers in the map. */
class Legend {
/** Specify a subset of the layers in the map to display in the legend. */
layerInfos: any[];
/** Reference to the map. */
map: Map;
/**
* Creates a new Legend dijit.
* @param params Parameters used to configure the dijit.
@ -4555,7 +4667,7 @@ declare module "esri/dijit/LocateButton" {
import Symbol = require("esri/symbols/Symbol");
import Graphic = require("esri/graphic");
/** LocateButton provides a simple button to locate and zoom to the users current location. */
/** LocateButton provides a simple button to locate and zoom to the user's location. */
class LocateButton {
/** Centers the map to the location when a new position is returned. */
centerAt: boolean;
@ -6767,7 +6879,7 @@ declare module "esri/dijit/editing/Add" {
import esri = require("esri");
import OperationBase = require("esri/OperationBase");
/** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */
/** This class is used with the UndoManager to provide undo/redo functionality of Add operations when editing. */
class Add extends OperationBase {
/**
* Create a new Add operation.
@ -6810,7 +6922,7 @@ declare module "esri/dijit/editing/Cut" {
import esri = require("esri");
import OperationBase = require("esri/OperationBase");
/** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */
/** This class is used with the UndoManager to provide undo/redo functionality of Cut operations when editing. */
class Cut extends OperationBase {
/**
* Create a new Cut operation.
@ -6829,7 +6941,7 @@ declare module "esri/dijit/editing/Delete" {
import esri = require("esri");
import OperationBase = require("esri/OperationBase");
/** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */
/** This class is used with the UndoManager to provide undo/redo functionality of Delete operations when editing. */
class Delete extends OperationBase {
/**
* Create a new Delete operation.
@ -6929,7 +7041,7 @@ declare module "esri/dijit/editing/Union" {
import esri = require("esri");
import OperationBase = require("esri/OperationBase");
/** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */
/** This class is used with the UndoManager to provide undo/redo functionality of Union operations when editing. */
class Union extends OperationBase {
/**
* Create a new Union operation.
@ -6948,7 +7060,7 @@ declare module "esri/dijit/editing/Update" {
import esri = require("esri");
import OperationBase = require("esri/OperationBase");
/** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */
/** This class is used with the UndoManager to provide undo/redo functionality of Update operations when editing. */
class Update extends OperationBase {
/**
* Create a new Update operation.
@ -8353,8 +8465,9 @@ declare module "esri/geometry/webMercatorUtils" {
/**
* Converts geometry from Web Mercator units to geographic units.
* @param geometry The geometry to convert.
* @param isLinear Indicates whether to work with linear values, i.e., do not normalize.
*/
webMercatorToGeographic(geometry: Geometry): Geometry;
webMercatorToGeographic(geometry: Geometry, isLinear?: boolean): Geometry;
/**
* Translates the given Web Mercator coordinates to Longitude and Latitude.
* @param x The x coordinate value to convert.
@ -10809,8 +10922,6 @@ declare module "esri/layers/VectorTileLayer" {
initialExtent: Extent;
/** The spatial reference of the layer. */
spatialReference: SpatialReference;
/** The style object of the service with fully qualified URLs for glyphs and sprite. */
style: any;
/** Contains information about the tiling scheme for the layer. */
tileInfo: TileInfo;
/** The URL to the vector tile service or style JSON that will be used to draw the layer. */
@ -10821,6 +10932,8 @@ declare module "esri/layers/VectorTileLayer" {
* @param options Optional parameters.
*/
constructor(url: string | any, options?: esri.VectorTileLayerOptions);
/** Returns an object that contains the current style information for the layer. */
getStyle(): any;
/**
* Changes the style properties used to render the layers.
* @param styleUrl A url to a JSON file containing the stylesheet information to render the layer.
@ -10835,14 +10948,15 @@ declare module "esri/layers/VectorTileLayer" {
declare module "esri/layers/WFSLayer" {
import esri = require("esri");
import GraphicsLayer = require("esri/layers/GraphicsLayer");
import Field = require("esri/layers/Field");
import Extent = require("esri/geometry/Extent");
import Graphic = require("esri/graphic");
import InfoTemplate = require("esri/InfoTemplate");
import Renderer = require("esri/renderers/Renderer");
/** (Currently in beta) A layer for OGC Web Feature Services (WFS). */
class WFSLayer {
/** (Currently in beta) A layer for OGC Web Feature Services (WFS). */
class WFSLayer extends GraphicsLayer {
/** An array of fields in the layer. */
fields: Field[];
/** The full extent of the layer. */
@ -10864,17 +10978,11 @@ declare module "esri/layers/WFSLayer" {
* @param options See options table below for full descriptions of the properties needed for this object.
*/
constructor(options: esri.WFSLayerOptions);
/** Creates the getFeature parameter based on the version, nsLayerName, nsGeometryFieldName, mode, wkid, inverseFilter, maxFeatures constructor parameters. */
buildRequest(): string;
/**
* Gets the WFS layer capabilities.
* @param callback An array of WFS layers in JSON format.
* Creates a WFSLayer using the provided JSON object.
* @param json The input JSON.
*/
getCapabilities(callback?: Function): void;
/** Performs the getFeature request. */
getFeature(): void;
/** Returns a JSON Object containing all of the WFS parameters. */
getWFSParameters(): any;
fromJson(json: Object): void;
/** Redraws all the graphics in the layer. */
redraw(): void;
/** Refreshes the features in the WFS layer. */
@ -10885,8 +10993,8 @@ declare module "esri/layers/WFSLayer" {
setPointSymbol(): void;
/** Sets the default polygon symbol to be used if no renderer is specified. */
setPolygonSymbol(): void;
/** Sets the WFS parameters using the provided JSON Object. */
setWFSParameters(): void;
/** Converts the WFSLayer instance to a JSON object. */
toJson(): any;
}
export = WFSLayer;
}
@ -10952,6 +11060,7 @@ declare module "esri/layers/WMSLayer" {
}
declare module "esri/layers/WMSLayerInfo" {
import esri = require("esri");
import Extent = require("esri/geometry/Extent");
/** The WMSLayerInfo class defines and provides information about layers in a WMS service. */
@ -10966,6 +11075,10 @@ declare module "esri/layers/WMSLayerInfo" {
legendURL: string;
/** The layer name. */
name: string;
/** Returns true if the layer can be queried and the service supports GetFeatureInfo with either text/html or text/plain formats */
queryable: boolean;
/** Indicates if this layer should be included in the popup. */
showPopup: boolean;
/** An array of WKIDs of all spatial references defined for the layer. */
spatialReferences: number[];
/** WMSLayerInfos of the layer's sub layers. */
@ -10974,9 +11087,9 @@ declare module "esri/layers/WMSLayerInfo" {
title: string;
/**
* Creates a new WMSLayerInfo object.
* @param layer WMSLayerInfo layer object.
* @param options See options list for parameters.
*/
constructor(layer: any);
constructor(options?: esri.WMSLayerInfoOptions);
}
export = WMSLayerInfo;
}
@ -11584,7 +11697,7 @@ declare module "esri/opsdashboard/DataSourceProxy" {
displayFieldName: string;
/** Read-only: The collection of fields. */
fields: Field[];
/** The geometry type. */
/** Read-only: The geometry type. */
geometryType: string;
/** Read-only: The id of the data source. */
id: string;
@ -11611,8 +11724,8 @@ declare module "esri/opsdashboard/DataSourceProxy" {
executeQuery(query: Query): any;
/** An object that contains service level metadata about whether or not the layer supports queries using statistics, order by fields, DISTINCT, pagination, query with distance, and returning queries with extents. */
getAdvancedQueryCapabilities(): any;
/** Retrieve the associated data source that supports selection. */
getAssociatedSelectionDataSourceProxy(): any;
/** Retrieve the associated id of the data source that supports selection. */
getAssociatedSelectionDataSourceId(): any;
/** Get the associated popupInfo for the data source if any available. */
getPopupInfo(): any;
/** Get the associated render object for the data source if any available. */
@ -11666,12 +11779,17 @@ declare module "esri/opsdashboard/ExtensionBase" {
static POLYLINE: any;
/** Read-only: Indicates if the host application is the Windows Operations Dashboard. */
isNative: boolean;
/** Read Only: It will list all of the Portal helper services. */
portalHelperServices: string;
/** Read-only: The URL to the ArcGIS.com site or in-house portal that you are currently signed in to. */
portalUrl: string;
/** Get the collection of data sources from the host application. */
getDataSourceProxies(): any;
/** Get the data source corresponding to the data source id from the host application. */
getDataSourceProxy(): any;
/**
* Get the data source corresponding to the data source id from the host application.
* @param dataSourceId The data source id
*/
getDataSourceProxy(dataSourceId: string): any;
/** Get the collection of map widgets from the host application. */
getMapWidgetProxies(): any;
/**
@ -11791,7 +11909,7 @@ declare module "esri/opsdashboard/GraphicsLayerProxy" {
minScale: number;
/** Read-only: The current host graphics layer opacity ratio. */
opacity: number;
/** The current renderer used by the host graphics layer. */
/** Read-only: The current renderer used by the host graphics layer. */
renderer: Renderer;
/** Read-only: The current host graphics layer visibility. */
visible: boolean;
@ -11928,8 +12046,6 @@ declare module "esri/opsdashboard/MapWidgetProxy" {
destroyGraphicsLayerProxy(graphicsLayerProxy: GraphicsLayerProxy): void;
/** Gets the current host map extent. */
getMapExtent(): any;
/** Called by the host application when the extent of the host map has changed. */
mapExtentChanged(): void;
/**
* Pans the map to a new location.
* @param mapPoint A new location with the same spatial reference as the host map.
@ -14088,7 +14204,7 @@ declare module "esri/tasks/FindTask" {
url: string;
/**
* Creates a new FindTask object.
* @param url URL to the ArcGIS Server REST resource that represents a layer in a service.
* @param url URL to the ArcGIS Server REST resource that represents a map service.
* @param options Optional parameters.
*/
constructor(url: string, options?: esri.FindTaskOptions);
@ -15343,6 +15459,8 @@ declare module "esri/tasks/RouteParameters" {
startTimeIsUTC: boolean;
/** The set of stops loaded as network locations during analysis. */
stops: any;
/** If true , the TimeWindowStart and TimeWindowEnd attributes of a stop are in UTC time (milliseconds). */
timeWindowsAreUTC: boolean;
/** Travel modes define how a pedestrian, car, truck or other medium of transportation moves through the street network. */
travelMode: any;
/** If true, the hierarchy attribute for the network should be used in analysis. */
@ -16696,7 +16814,7 @@ declare module "esri/tasks/query" {
static SPATIAL_REL_TOUCHES: any;
/** The feature from feature class 1 is completely enclosed by the feature from feature class 2. */
static SPATIAL_REL_WITHIN: any;
/** Distance to buffer input geometry. */
/** Buffer distance for input geometries. */
distance: number;
/** The geometry to apply to the spatial filter. */
geometry: Geometry;
@ -16738,7 +16856,7 @@ declare module "esri/tasks/query" {
text: string;
/** Specify a time extent for the query. */
timeExtent: TimeExtent;
/** Distance unit. */
/** The unit for calculating the buffer distance. */
units: string;
/** A where clause for the query. */
where: string;
@ -17055,7 +17173,7 @@ declare module "esri/toolbars/navigation" {
* @param symbol The SimpleFillSymbol used for the rubber band zoom.
*/
setZoomSymbol(symbol: Symbol): void;
/** Zoom to full extent of base layer. */
/** Zoom to initial extent of base layer. */
zoomToFullExtent(): void;
/** Zoom to next extent in extent history. */
zoomToNextExtent(): void;

2
archiver/index.d.ts vendored
View File

@ -24,7 +24,7 @@ interface nameInterface {
interface Archiver extends STREAM.Transform {
pipe(writeStream: FS.WriteStream): void;
append(readStream: FS.ReadStream, name: nameInterface): void;
append(source: FS.ReadStream | Buffer | string, name: nameInterface): void;
finalize(): void;
}

2
autobahn/index.d.ts vendored
View File

@ -47,7 +47,7 @@ declare namespace autobahn {
interface IInvocation {
caller?: number;
progress?: boolean;
progress?: (args : any[], kwargs : any) => void;
procedure: string;
}

View File

@ -4,7 +4,7 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "avoscloud-sdk" {
namespace AV{
namespace AV {
var applicationId: string;
var applicationKey: string;
@ -301,6 +301,7 @@ declare module "avoscloud-sdk" {
fetch<T>(options?: Object.FetchOptions): Promise<T>;
get(attr: string): any;
getACL(): ACL;
getObjectId(): string;
has(attr: string): boolean;
hasChanged(attr: string): boolean;
increment(attr: string, amount?: number): any;
@ -529,6 +530,7 @@ declare module "avoscloud-sdk" {
constructor(objectClass: any);
static and(...var_args: Query[]): Query;
static or(...var_args: Query[]): Query;
addAscending(key: string): Query;
@ -628,7 +630,7 @@ declare module "avoscloud-sdk" {
signUp<T>(attrs: any, options?: SuccessFailureOptions): Promise<T>;
logIn<T>(options?: SuccessFailureOptions): Promise<T>;
fetch<T>(options?: SuccessFailureOptions): Promise<T>;
save<T>(arg1: any, arg2: any, arg3: any): Promise<T>;
save<T>(arg1?: any, arg2?: any, arg3?: any): Promise<T>;
authenticated(): boolean;
isCurrent(): boolean;

43
aws-sdk/index.d.ts vendored
View File

@ -88,8 +88,6 @@ export interface Services {
export interface ClientConfigPartial extends Services {
credentials?: Credentials;
region?: string;
accessKeyId: string;
secretAccessKey: string;
computeChecksums?: boolean;
convertResponseTypes?: boolean;
logger?: Logger;
@ -152,17 +150,22 @@ export declare class SimpleWorkflow {
export declare class S3 {
constructor(options?: any);
putObject(params: s3.PutObjectRequest, callback: (err: any, data: any) => void): void;
getObject(params: s3.GetObjectRequest, callback: (err: any, data: any) => void): void;
getObject(params: s3.GetObjectRequest, callback: (err: Error, data: any) => void): void;
putObject(params: s3.PutObjectRequest, callback: (err: Error, data: any) => void): void;
deleteObject(params: s3.DeleteObjectRequest, callback: (err: Error, data: any) => void): void;
headObject(params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void;
getSignedUrl(operation: string, params: any): string;
getSignedUrl(operation: string, params: any, callback: (err: Error, url: string) => void): void;
upload(params?: s3.PutObjectRequest, options?: s3.UploadOptions, callback?: (err: Error, 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.
*/
@ -306,6 +309,7 @@ export declare module DynamoDB {
ScanFilter?: _DDBDC_KeyComparison;
TotalSegments?: number;
}
interface GetParam extends _DDBDC_Reader {
Key: _DDBDC_Keys;
}
@ -394,7 +398,7 @@ export declare module SQS {
}
export interface SendMessageParams {
QueueUrl: string;
QueueUrl?: string;
MessageBody: string;
DelaySeconds?: number;
MessageAttributes?: { [name: string]: MessageAttribute; }
@ -1272,6 +1276,33 @@ export declare module s3 {
VersionId?: string;
}
export interface DeleteObjectRequest {
Bucket: string;
Key: string;
MFA?: string;
RequestPayer?: string;
VersionId?: string;
}
export interface HeadObjectRequest {
Bucket: string;
Key: string;
IfMatch?: string;
IfModifiedSince?: Date;
IfNoneMatch?: string;
IfUnmodifiedSince?: Date;
Range?: string;
RequestPayer?: string;
SSECustomerAlgorithm?: string;
SSECustomerKey?: Buffer | string;
SSECustomerKeyMD5?: string;
VersionId?: string;
}
export interface UploadOptions {
partSize?: number;
queueSize?: number;
}
}
export declare module ecs {

View File

@ -0,0 +1,12 @@
/// <reference path="bazinga-translator.d.ts" />
Translator.fallback = 'en';
Translator.defaultDomain = 'messages';
Translator.add("test", "it work", "frontend", "en");
Translator.trans('key', {}, 'frontend');
Translator.trans('key', {"foo": "bar"}, 'DOMAIN_NAME');
Translator.transChoice('key', 1, {}, 'frontend');
Translator.transChoice('key', 123, {"foo": "bar"}, 'DOMAIN_NAME');

View File

@ -0,0 +1,99 @@
// Type definitions for Translator
// Project: https://github.com/willdurand/BazingaJsTranslationBundle
// Definitions by: Alex <https://github.com/alexndlm>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface BazingaTranslator {
/**
* The current locale.
*
* @type {String}
*/
locale: string;
/**
* Fallback locale.
*
* @type {String}
*/
fallback: string;
/**
* Placeholder prefix.
*
* @type {String}
*/
placeHolderPrefix: string;
/**
* Placeholder suffix.
*
* @type {String}
*/
placeHolderSuffix: string;
/**
* Default domain.
*
* @type {String}
*/
defaultDomain: string;
/**
* Plural separator.
*
* @type {String}
*/
pluralSeparator: string;
/**
* Adds a translation entry.
*
* @param {String} id The message id
* @param {String} message The message to register for the given id
* @param {String} [domain] The domain for the message or null to use the default
* @param {String} [locale] The locale or null to use the default
*
* @return {Object} Translator
*/
add(id: string, message: string, domain: string, locale: string): BazingaTranslator;
/**
* Translates the given message.
*
* @param {String} id The message id
* @param {Object} [parameters] An array of parameters for the message
* @param {String} [domain] The domain for the message or null to guess it
* @param {String} [locale] The locale or null to use the default
*
* @return {String} The translated string
*/
trans(id: string, parameters: any, domain: string, locale?: string): string;
/**
* Translates the given choice message by choosing a translation according to a number.
*
* @param {String} id The message id
* @param {Number} number The number to use to find the indice of the message
* @param {Object} [parameters] An array of parameters for the message
* @param {String} [domain] The domain for the message or null to guess it
* @param {String} [locale] The locale or null to use the default
*
* @return {String} The translated string
*/
transChoice(id: string, number: number, parameters: any, domain: string, locale?: string): string,
/**
* Loads translations from JSON.
*
* @param {String} data A JSON string or object literal
*
* @return {Object} Translator
*/
fromJSON(data: string): BazingaTranslator;
reset(): void;
}
declare var Translator: BazingaTranslator;

View File

@ -1,27 +1,29 @@
/// <reference path="./bezier-js.d.ts" />
function test() {
var bezierjs: typeof BezierJs;
var bezier = new bezierjs.Bezier([1,2,3,4]);
var bezier = new bezierjs.Bezier([1, 2, 3, 4]);
var cap = new bezierjs.BezierCap([]);
var point: BezierJs.Point = { x: 0, y: 0 };
var utils = bezier.getUtils();
var line: BezierJs.Line = { p1: { x:0, y: 0}, p2: {x:1, y: 1}};
var line: BezierJs.Line = { p1: { x: 0, y: 0 }, p2: { x: 1, y: 1 } };
var abc: BezierJs.ABC = { A: null, B: null, C: null };
var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1 };
var bbox: BezierJs.BBox = bezier.bbox();
var closest: BezierJs.Closest = { mdist: 1, mpos: 0 };
var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z:[0] };
var closest: BezierJs.Closest = { mdist: 1, mpos: 0 };
var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z: [0] };
var minmax: BezierJs.MinMax = { min: 0, max: 0 };
var offset: BezierJs.Offset = { x: 0, y: 0, c: point, n: point };
var pair: BezierJs.Pair = { left: bezier, right: bezier };
var poly: BezierJs.PolyBezier = bezier.outline(1);
var projection: BezierJs.Projection = { x: 0, y: 0, t: 9, d: 4 };
var shape: BezierJs.Shape = { startcap: cap, endcap: cap, forward: bezier, back: bezier, bbox: bbox };
var shape: BezierJs.Shape = {
startcap: cap, endcap: cap, forward: bezier, back: bezier, bbox: bbox, intersections: function (shape) { return [[0]]; }
};
var split: BezierJs.Split = { left: bezier, right: bezier, span: [point] };
bezier.arcs();
bezier.clockwise;
bezier.compute(.5);
@ -36,10 +38,10 @@ function test() {
bezier.length();
bezier.lineIntersects(line);
bezier.normal(0);
bezier.offset(1,2);
bezier.offset(1, 2);
bezier.on(point, 0);
bezier.order = 5;
bezier.outlineshapes(1,3);
bezier.outlineshapes(1, 3);
bezier.overlaps(bezier);
bezier.point(9);
bezier.project(point);
@ -52,9 +54,9 @@ function test() {
bezier.split(0.5).left;
bezier.toSVG();
bezier.update();
cap.virtual = true;
poly.addCurve(bezier);
poly.bbox();
poly.curve(7);
@ -62,12 +64,12 @@ function test() {
poly.length();
poly.offset(9).points[0].y;
poly.points[0];
utils.abcratio(0, 1);
utils.align([point], line);
utils.angle(point, point, point);
utils.approximately(5, 7, .001);
utils.arcfn(1, function(){});
utils.arcfn(1, function () { });
utils.bboxoverlap(bbox, bbox);
utils.between(0, 0, 1);
utils.closest([point], point);
@ -78,7 +80,7 @@ function test() {
utils.findbbox([bezier]);
utils.getccenter(point, point, point);
utils.getminmax(bezier, 'x', [0]);
utils.length(function(){});
utils.length(function () { });
utils.lerp(1, point, point);
utils.lli(offset, offset);
utils.lli4(point, point, point, point);
@ -92,5 +94,5 @@ function test() {
utils.roots([point], line);
utils.round(.999, .001);
utils.shapeintersections(shape, bbox, shape, bbox);
}

View File

@ -57,6 +57,7 @@ declare module BezierJs {
back: Bezier;
endcap: BezierCap;
bbox: BBox;
intersections: (shape: Shape) => string[][] | number[][];
}
interface ABC {
A: Point;
@ -76,8 +77,8 @@ declare module BezierJs {
*
*/
class Bezier {
clockwise: boolean;
private _linear;
clockwise: boolean;
_3d: boolean;
_t1: number;
_t2: number;
@ -124,16 +125,16 @@ declare module BezierJs {
overlaps(curve: Bezier): boolean;
offset(t: number, d?: number): Offset | Bezier[];
simple(): boolean;
reduce(): any[];
reduce(): Bezier[];
scale(d: Function): Bezier;
scale(d: number): Bezier;
outline(d1: number, d2?: number, d3?: number, d4?: number): PolyBezier;
outlineshapes(d1: number, d2: number): Shape[];
intersects(curve: Bezier): string[] | number[];
outlineshapes(d1: number, d2: number, curveIntersectionThreshold?: number): Shape[];
intersects(curve: Bezier, curveIntersectionThreshold?: number): string[] | number[];
intersects(curve: Line): string[] | number[];
lineIntersects(line: Line): number[];
selfintersects(): string[];
curveintersects(c1: Bezier[], c2: Bezier[]): string[];
selfintersects(curveIntersectionThreshold?: number): string[];
curveintersects(c1: Bezier[], c2: Bezier[], curveIntersectionThreshold?: number): string[];
arcs(errorThreshold?: number): Arc[];
private _error(pc, np1, s, e);
private _iterate(errorThreshold, circles);
@ -165,8 +166,8 @@ declare module BezierJs.utils {
function lli(v1: Offset, v2: Offset): Point;
function makeline(p1: Point, p2: Point): Bezier;
function findbbox(sections: Bezier[]): BBox;
function shapeintersections(s1: Shape, bbox1: BBox, s2: Shape, bbox2: BBox): string[][] | number[][];
function makeshape(forward: Bezier, back: Bezier): Shape;
function shapeintersections(s1: Shape, bbox1: BBox, s2: Shape, bbox2: BBox, curveIntersectionThreshold?: number): string[][] | number[][];
function makeshape(forward: Bezier, back: Bezier, curveIntersectionThreshold?: number): Shape;
function getminmax(curve: Bezier, d: string, list: number[]): MinMax;
function align(points: Point[], line: Line): Point[];
function roots(points: Point[], line: Line): number[];
@ -174,7 +175,7 @@ declare module BezierJs.utils {
function inflections(points: Point[]): number[];
function bboxoverlap(b1: BBox, b2: BBox): boolean;
function expandbox(bbox: BBox, _bbox: BBox): void;
function pairiteration(c1: Bezier, c2: Bezier): string[];
function pairiteration(c1: Bezier, c2: Bezier, curveIntersectionThreshold?: number): string[];
function getccenter(p1: Point, p2: Point, p3: Point): Arc;
}
declare module BezierJs {

View File

@ -35,7 +35,7 @@ interface SliderOptions {
* Default: 'horizontal'
* set the orientation. Accepts 'vertical' or 'horizontal'
*/
orientation?: number;
orientation?: string;
/**
* Default: 5
* initial value. Use array to have a range slider.

View File

@ -0,0 +1,27 @@
/// <reference path="chai-dom.d.ts" />
import * as chai from 'chai';
import * as chaiDom from 'chai-dom';
chai.use(chaiDom);
var expect = chai.expect;
function test() {
var testElement = '<div></div>';
expect(testElement).to.have.attribute('foo', 'bar');
expect(testElement).to.have.attr('foo').match(/bar/);
expect(testElement).to.have.class('foo');
expect(testElement).to.have.id('id');
expect(testElement).to.have.html('foo');
expect(testElement).to.have.text('foo');
expect(testElement).to.have.text(['foo', 'bar']);
expect(testElement).to.have.value('foo');
expect(testElement).to.be.empty;
expect(testElement).to.have.length(2);
expect(testElement).to.exist;
expect(testElement).to.match('foo');
expect(testElement).to.contain('foo');
expect(testElement).to.contain(document.body);
}

38
chai-dom/chai-dom.d.ts vendored Normal file
View File

@ -0,0 +1,38 @@
// Type definitions for chai-dom
// Project: https://github.com/nathanboktae/chai-dom
// Definitions by: Matt Lewis <https://github.com/mattlewis92>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../chai/chai.d.ts" />
declare namespace Chai {
interface Assertion {
attr(name: string, value?: string): Assertion;
attribute(name: string, value?: string): Assertion;
class(className: string): Assertion;
id(id: string): Assertion;
html(html: string): Assertion;
text(text: string|string[]): Assertion;
value(text: string): Assertion;
}
}
declare module "chai-dom" {
function chaiDom(chai: any, utils: any): void;
namespace chaiDom {
}
export = chaiDom;
}

View File

@ -0,0 +1,45 @@
/// <reference path="../react/react.d.ts" />
/// <reference path="./chai-enzyme.d.ts" />
/// <reference path="../enzyme/enzyme.d.ts" />
/// <reference path="../chai/chai.d.ts" />
import * as React from "react";
import * as chaiEnzyme from "chai-enzyme";
import { expect } from "chai";
import { shallow } from "enzyme";
const Test = () => <div/>;
class Test2 extends React.Component<{}, {}> {
render() {
return <div/>;
}
}
chai.use(chaiEnzyme());
const wrapper = shallow(<Test />);
expect(wrapper).to.be.checked();
expect(wrapper).to.have.className("test");
expect(wrapper).to.have.descendants({ a: "b" });
expect(wrapper).to.have.descendants(Test);
expect(wrapper).to.have.exactly(1).descendants(Test2);
expect(wrapper).to.have.descendants("div");
expect(wrapper).to.be.disabled();
expect(wrapper).to.be.blank();
expect(wrapper).to.be.present();
expect(wrapper).to.have.html("<div></div>");
expect(wrapper).to.have.id("test");
expect(wrapper).to.have.ref("test");
expect(wrapper).to.be.selected();
expect(wrapper).to.have.tagName("div");
expect(wrapper).to.have.text("");
expect(wrapper).to.have.value("test");
expect(wrapper).to.have.attr("test", "test");
expect(wrapper).to.have.data("test", "Test");
expect(wrapper).to.have.style("background", "green");
expect(wrapper).to.have.state("test", "test");
expect(wrapper).to.have.prop("test", 5);
expect(wrapper).to.contain(<Test/>);
expect(wrapper).to.match(<Test/>);

153
chai-enzyme/chai-enzyme.d.ts vendored Normal file
View File

@ -0,0 +1,153 @@
// Type definitions for chai-enzyme 0.5.0
// Project: https://github.com/producthunt/chai-enzyme
// Definitions by: Alexey Svetliakov <https://github.com/asvetliakov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../enzyme/enzyme.d.ts" />
/// <reference path="../chai/chai.d.ts" />
/// <reference path="../react/react.d.ts" />
declare namespace Chai {
type EnzymeSelector = string | __React.StatelessComponent<any> | __React.ComponentClass<any> | { [key: string]: any };
interface Match {
/**
* Assert that the wrapper matches given selector:
* @param selector
*/
(selector: EnzymeSelector): Assertion;
}
interface Include {
/**
* Assert that the wrapper contains a given node:
* @param code
*/
(selector: EnzymeSelector): Assertion;
}
interface Assertion {
/**
* Assert that the given wrapper is checked:
*/
checked(): Assertion;
/**
* Assert that the wrapper has a given class:
* @param name
*/
className(name: string): Assertion;
/**
* Assert that the wrapper contains a descendant matching the given selector:
* @param selector
*/
descendants(selector?: EnzymeSelector): Assertion;
/**
* Assert that the wrapper contains an exact amount of descendants matching the given selector:
*/
exactly(count?: number): Assertion;
/**
* Assert that the given wrapper is disabled:
*/
disabled(): Assertion;
/**
* Assert that the given wrapper is empty:
*/
blank(): Assertion;
/**
* Assert that the given wrapper exists:
*/
present(): Assertion;
/**
* Assert that the wrapper has given html:
* @param str
*/
html(str?: string): Assertion;
/**
* Assert that the wrapper has given ID attribute:
* @param str
*/
id(str: string): Assertion;
/**
* Assert that the wrapper has a given ref
* @param key
*/
ref(key: string): Assertion;
/**
* Assert that the given wrapper is selected:
*/
selected(): Assertion;
/**
* Assert that the given wrapper has the tag name:
* @param str
*/
tagName(str: string): Assertion;
/**
* Assert that the given wrapper has the supplied text:
* @param str
*/
text(str?: string): Assertion;
/**
* Assert that the given wrapper has given value:
* @param str
*/
value(str: string): Assertion;
/**
* Assert that the wrapper has given attribute [with value]:
* @param key
* @param val
*/
attr(key: string, val?: string): Assertion;
/**
* Assert that the wrapper has a given data attribute [with value]:
* @param key
* @param val
*/
data(key: string, val?: string): Assertion;
/**
* Assert that the wrapper has given style:
* @param key
* @param val
*/
style(key: string, val?: string): Assertion;
/**
* Assert that the wrapper has given state [with value]:
* @param key
* @param val
*/
state(key: string, val?: any): Assertion;
/**
* Assert that the wrapper has given prop [with value]:
* @param key
* @param val
*/
prop(key: string, val?: any): Assertion;
}
}
declare module "chai-enzyme" {
import { ShallowWrapper, ReactWrapper, CheerioWrapper } from "enzyme";
type DebugWrapper = ShallowWrapper<any,any> | CheerioWrapper<any, any> | ReactWrapper<any, any>;
function chaiEnzyMe(wrapper?: (debugWrapper: DebugWrapper) => string): (chai: any) => void;
module chaiEnzyMe {
}
export = chaiEnzyMe;
}

View File

@ -17,7 +17,7 @@ declare namespace Chai {
html(html: string): Assertion;
text(text: string): Assertion;
value(text: string): Assertion;
(selector: string): Assertion;
descendants(selector: string): Assertion;
visible: Assertion;
hidden: Assertion;
selected: Assertion;

381
chart.js/chart.js.d.ts vendored Normal file
View File

@ -0,0 +1,381 @@
// Type definitions for Chart.js
// Project: https://github.com/nnnick/Chart.js
// Definitions by: Alberto Nuti <https://github.com/anuti>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare enum ChartType {
line, bar, radar, doughnut, polarArea, bubble
}
declare enum TimeUnit {
millisecond, second, minute,
hour, day, week,
month, quarter, year
}
interface ChartLegendItem {
text?: string;
fillStyle?: string;
hidden?: boolean;
lineCap?: string;
lineDash?: number[];
lineDashOffset?: number;
lineJoin?: string;
lineWidth?: number;
strokeStyle?: string;
}
interface ChartTooltipItem {
xLabel?: string;
yLabel?: string;
datasetIndex?: number;
index?: number;
}
interface ChartTooltipCallback {
beforeTitle?: (item?: ChartTooltipItem[], data?: any) => void;
title?: (item?: ChartTooltipItem[], data?: any) => void;
afterTitle?: (item?: ChartTooltipItem[], data?: any) => void;
beforeBody?: (item?: ChartTooltipItem[], data?: any) => void;
beforeLabel?: (tooltipItem?: ChartTooltipItem, data?: any) => void;
label?: (tooltipItem?: ChartTooltipItem, data?: any) => void;
afterLabel?: (tooltipItem?: ChartTooltipItem, data?: any) => void;
afterBody?: (item?: ChartTooltipItem[], data?: any) => void;
beforeFooter?: (item?: ChartTooltipItem[], data?: any) => void;
footer?: (item?: ChartTooltipItem[], data?: any) => void;
afterfooter?: (item?: ChartTooltipItem[], data?: any) => void;
}
interface ChartAnimationParameter {
chartInstance?: any;
animationObject?: any;
}
interface ChartPoint {
x?: number;
y?: number;
}
interface ChartConfiguration {
type?: string;
data?: ChartData;
options?: ChartOptions;
}
interface ChartData {
}
interface LinearChartData extends ChartData {
labels?: string[];
datasets?: ChartDataSets[];
}
interface ChartOptions {
responsive?: boolean;
responsiveAnimationDuration?: number;
maintainAspectRatio?: boolean;
events?: string[];
onClick?: (any?: any) => any;
title?: ChartTitleOptions;
legend?: ChartLegendOptions;
tooltip?: ChartTooltipOptions;
hover?: ChartHoverOptions;
animation?: ChartAnimationOptions;
elements?: ChartElementsOptions;
scales?: ChartScales;
}
interface ChartFontOptions {
defaultFontColor?: string;
defaultFontFamily?: string;
defaultFontSize?: number;
defaultFontStyle?: string;
}
interface ChartTitleOptions {
display?: boolean;
position?: string;
fullWdith?: boolean;
fontSize?: number;
fontFamily?: string;
fontColor?: string;
fontStyle?: string;
padding?: number;
text?: string;
}
interface ChartLegendOptions {
display?: boolean;
position?: string;
fullWidth?: boolean;
onClick?: (event: any, legendItem: any) => void;
labels?: ChartLegendLabelOptions;
}
interface ChartLegendLabelOptions {
boxWidth?: number;
fontSize?: number;
fontStyle?: number;
fontColor?: string;
fontFamily?: string;
padding?: number;
generateLabels?: (chart: any) => any;
}
interface ChartTooltipOptions {
enabled?: boolean;
custom?: (a: any) => void;
mode?: string;
backgroundColor?: string;
titleFontFamily?: string;
titleFontSize?: number;
titleFontStyle?: string;
titleFontColor?: string;
titleSpacing?: number;
titleMarginBottom?: number;
bodyFontFamily?: string;
bodyFontSize?: number;
bodyFontStyle?: string;
bodyFontColor?: string;
bodySpacing?: number;
footerFontFamily?: string;
footerFontSize?: number;
footerFontStyle?: string;
footerFontColor?: string;
footerSpacing?: number;
footerMarginTop?: number;
xPadding?: number;
yPadding?: number;
caretSize?: number;
cornerRadius?: number;
multiKeyBackground?: string;
callbacks?: ChartTooltipCallback;
}
interface ChartHoverOptions {
mode?: string;
animationDuration?: number;
onHover?: (active: any) => void;
}
interface ChartAnimationObject {
currentStep?: number;
numSteps?: number;
easing?: string;
render?: (arg: any) => void;
onAnimationProgress?: (arg: any) => void;
onAnimationComplete?: (arg: any) => void;
}
interface ChartAnimationOptions {
duration?: number;
easing?: string;
onProgress?: (chart: any) => void;
onComplete?: (chart: any) => void;
}
interface ChartElementsOptions {
point?: ChartPointOptions;
line?: ChartLineOptions;
arg?: ChartArcOtpions;
rectangle?: ChartRectangleOptions;
}
interface ChartArcOtpions {
backgroundColor?: string;
borderColor?: string;
borderWidth?: number;
}
interface ChartLineOptions {
tension?: number;
backgroundColor?: string;
borderWidth?: number;
borderColor?: string;
borderCapStyle?: string;
borderDash?: any[];
borderDashOffset?: number;
borderJoinStyle?: string;
}
interface ChartPointOptions {
radius?: number;
pointStyle?: string;
backgroundColor?: string;
borderWidth?: number;
borderColor?: string;
hitRadius?: number;
hoverRadius?: number;
hoverBorderWidth?: number;
}
interface ChartRectangleOptions {
backgroundColor?: string;
borderWidth?: number;
borderColor?: string;
borderSkipped?: string;
}
interface GridLineOptions {
display?: boolean;
color?: string;
lineWidth?: number;
drawBorder?: boolean;
drawOnChartArea?: boolean;
drawticks?: boolean;
tickMarkLength?: number;
zeroLineWidth?: number;
zeroLineColor?: string;
offsetGridLines?: boolean;
}
interface ScaleTitleOptions {
display?: boolean;
labelString?: string;
fontColor?: string;
fontFamily?: string;
fontSize?: number;
fontStyle?: string;
}
interface TickOptions {
autoSkip?: boolean;
callback?: (value: any, index: any, values: any) => string;
display?: boolean;
fontColor?: string;
fontFamily?: string;
fontSize?: number;
fontStyle?: string;
labelOffset?: number;
maxRotation?: number;
minRotation?: number;
mirror?: boolean;
padding?: number;
reverse?: boolean;
min?: any;
max?: any;
}
interface AngleLineOptions {
display?: boolean;
color?: string;
lineWidth?: number;
}
interface PointLabelOptions {
callback?: (arg: any) => any;
fontColor?: string;
fontFamily?: string;
fontSize?: number;
fontStyle?: string;
}
interface TickOptions {
backdropColor?: string;
backdropPaddingX?: number;
backdropPaddingY?: number;
maxTicksLimit?: number;
showLabelBackdrop?: boolean;
}
interface LinearTickOptions extends TickOptions {
beginAtZero?: boolean;
min?: number;
max?: number;
maxTicksLimit?: number;
stepSize?: number;
suggestedMin?: number;
suggestedMax?: number;
}
interface LogarithmicTickOptions extends TickOptions {
min?: number;
max?: number;
}
interface ChartDataSets {
backgroundColor?: string[];
borderWidth?: number;
borderColor?: string[];
borderCapStyle?: string;
borderDash?: number[];
borderDashOffset?: number;
borderJoinStyle?: string;
data?: number[] | ChartPoint[];
fill?: boolean;
label?: string;
lineTension?: number;
pointBorderColor?: string | string[];
pointBackgroundColor?: string | string[];
pointBorderWidth?: number | number[];
pointRadius?: number | number[];
pointHoverRadius?: number | number[];
pointHitRadius?: number | number[];
pointHoverBackgroundColor?: string | string[];
pointHoverBorderColor?: string | string[];
pointHoverBorderWidth?: number | number[];
pointStyle?: string | string[] | HTMLImageElement | HTMLImageElement[];
xAxisID?: string;
yAxisID?: string;
}
interface ChartScales {
type?: string;
display?: boolean;
position?: string;
beforeUpdate?: (scale?: any) => void;
beforeSetDimension?: (scale?: any) => void;
beforeDataLimits?: (scale?: any) => void;
beforeBuildTicks?: (scale?: any) => void;
beforeTickToLabelConversion?: (scale?: any) => void;
beforeCalculateTickRotation?: (scale?: any) => void;
beforeFit?: (scale?: any) => void;
afterUpdate?: (scale?: any) => void;
afterSetDimension?: (scale?: any) => void;
afterDataLimits?: (scale?: any) => void;
afterBuildTicks?: (scale?: any) => void;
afterTickToLabelConversion?: (scale?: any) => void;
afterCalculateTickRotation?: (scale?: any) => void;
afterFit?: (scale?: any) => void;
gridLines?: GridLineOptions;
scaleLabel?: ScaleTitleOptions;
ticks?: TickOptions;
}
interface LinearScale extends ChartScales {
ticks?: LinearTickOptions;
}
interface LogarithmicScale extends ChartScales {
ticks?: LogarithmicTickOptions;
}
interface TimeScale extends ChartScales {
displayFormats?: string;
isoWeekday?: boolean;
max?: string;
min?: string;
parser?: string | ((arg: any) => any);
round?: string;
tooltipFormat?: string;
unit?: TimeUnit;
unitStepSize?: number;
}
interface RadialLinearScale {
lineArc?: boolean;
angleLines?: AngleLineOptions;
pointLabels?: PointLabelOptions;
ticks?: TickOptions;
}
declare var Chart: {
new (context: CanvasRenderingContext2D, options: ChartConfiguration): {};
destroy: () => {};
update: (duration: any, lazy: any) => {};
render: (duration: any, lazy: any) => {};
stop: () => {};
resize: () => {};
clear: () => {};
toBase64: () => string;
generateLegend: () => {};
getElementAtEvent: (e: any) => {};
getElementsAtEvent: (e: any) => {}[];
getDatasetAtEvent: (e: any) => {}[];
defaults: {
global: ChartOptions;
}
};

View File

@ -1,8 +1,26 @@
$(".chzn-select").chosen({ no_results_text: "No results matched" });
$("#form_field").chosen().change();
$("#form_field").trigger("liszt:updated");
// Options
$(".my_select_box").chosen();
$(".chzn-select").chosen();
$(".chzn-select-deselect").chosen({ allow_single_deselect: true });
$(".my_select_box").chosen({});
$(".my_select_box").chosen({
disable_search_threshold: 10,
max_selected_options: 5,
no_results_text: "Oops, nothing found!",
width: "95%"
});
// Destroy
$(".my_select_box").chosen("destroy");
// Triggered Events
$(".my_select_box").on("change", function(evt, params) {
evt.preventDefault();
let s = params.selected;
console.log(s);
});
// Triggerable Events
$(".my_select_box").trigger("chosen:updated");

108
chosen/index.d.ts vendored
View File

@ -1,30 +1,98 @@
// Type definitions for Chosen.JQuery 1.4.2
// Type definitions for Chosen.JQuery 1.6.1
// Project: http://harvesthq.github.com/chosen/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, denis <https://github.com/denisname/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="jquery"/>
interface ChosenOptions {
allow_single_deselect?: boolean;
disable_search?: boolean;
disable_search_threshold?: number;
enable_split_word_search?: boolean;
inherit_select_classes?: boolean;
max_selected_options?: number;
no_results_text?: string;
placeholder_text_multiple?: string;
placeholder_text_single?: string;
search_contains?: boolean;
single_backstroke_delete?: boolean;
width?: number|string;
display_disabled_options?: boolean;
display_selected_options?: boolean;
include_group_label_in_selected?: boolean;
declare namespace Chosen {
type OnEvent = "chosen:ready" | "chosen:maxselected" | "chosen:showing_dropdown" | "chosen:hiding_dropdown" | "chosen:no_results";
type TriggerEvent = "chosen:updated" | "chosen:activate" | "chosen:open" | "chosen:close";
interface Options {
/**When set to true on a single select, Chosen adds a UI element which selects the first element (if it is blank).
* @default: false
*/
allow_single_deselect?: boolean;
/**By default Chosen's search is case-insensitive. Setting this option to true makes the search case-sensitive.
* @default: false
*/
case_sensitive_search?: boolean;
/**When set to true, Chosen will not display the search field (single selects only).
* @default: false
*/
disable_search?: boolean;
/**Hide the search input on single selects if there are n or fewer options.
* @default: 0
*/
disable_search_threshold?: number;
/**By default, searching will match on any word within an option tag. Set this option to false if you want to only match on the entire text of an option tag.
* @default: true
*/
enable_split_word_search?: boolean;
/**When set to true, Chosen will grab any classes on the original select field and add them to Chosens container div.
* @default: false
*/
inherit_select_classes?: boolean;
/**Limits how many options the user can select. When the limit is reached, the chosen:maxselected event is triggered.
* @default: Infinity
*/
max_selected_options?: number;
/**The text to be displayed when no matching results are found. The current search is shown at the end of the text (e.g., No results match "Bad Search").
* @default: "No results match"
*/
no_results_text?: string;
/**The text to be displayed as a placeholder when no options are selected for a multiple select.
* @default: "Select Some Options"
*/
placeholder_text_multiple?: string;
/**The text to be displayed as a placeholder when no options are selected for a single select.
* @default: "Select an Option"
*/
placeholder_text_single?: string;
/**By default, Chosens search matches starting at the beginning of a word. Setting this option to true allows matches starting from anywhere within a word. This is especially useful for options that include a lot of special characters or phrases in ()s and []s.
* @default: false
*/
search_contains?: boolean;
/**By default, pressing delete/backspace on multiple selects will remove a selected choice. When false, pressing delete/backspace will highlight the last choice, and a second press deselects it.
* @default: true
*/
single_backstroke_delete?: boolean;
/**The width of the Chosen select box. By default, Chosen attempts to match the width of the select box you are replacing. If your select is hidden when Chosen is instantiated, you must specify a width or the select will show up with a width of 0. */
width?: string;
/**By default, Chosen includes disabled options in search results with a special styling. Setting this option to false will hide disabled results and exclude them from searches.
* @default: true
*/
display_disabled_options?: boolean;
/**By default, Chosen includes selected options in search results with a special styling. Setting this option to false will hide selected results and exclude them from searches.
* Note: this is for multiple selects only. In single selects, the selected result will always be displayed.
* @default: true
*/
display_selected_options?: boolean;
/**By default, Chosen only shows the text of a selected option. Setting this option to true will show the text and group (if any) of the selected option.
* @default: false
*/
include_group_label_in_selected?: boolean;
/**Only show the first (n) matching options in the results. This can be used to increase performance for selects with very many options.
* @default: Infinity
*/
max_shown_results?: number;
}
interface SelectedData {
selected: string;
deselected: string;
}
}
interface JQuery {
chosen(): JQuery;
chosen(options: ChosenOptions): JQuery;
chosen(options: Chosen.Options | "destroy"): JQuery;
/**Chosen triggers the standard DOM event whenever a selection is made (it also sends a selected or deselected parameter that tells you which option was changed). */
on(events: "change", handler: (eventObject: JQueryEventObject, args: Chosen.SelectedData) => any): JQuery;
on(events: Chosen.OnEvent, handler: (eventObject: JQueryEventObject) => any): JQuery;
trigger(eventType: Chosen.TriggerEvent): JQuery;
}

View File

@ -0,0 +1,120 @@
/// <reference path="chroma-js-0.5.6.d.ts" />
function test_chroma() {
chroma("red");
chroma("#ff0000");
chroma("#f00");
chroma("FF0000");
chroma(255, 0, 0);
chroma([255, 0, 0]);
chroma(0, 1, 0.5, 'hsl');
chroma([0, 1, 0.5], 'hsl');
chroma(0, 1, 1, 'hsv');
chroma("rgb(255,0,0)");
chroma("rgb(100%,0%,0%)");
chroma("hsl(0,100%,50%)");
chroma(53.24, 80.09, 67.20, 'lab');
chroma(53.24, 104.55, 40, 'lch');
chroma(1, 0, 0, 'gl');
chroma.hex("#ff0000");
chroma.hex("red");
chroma.hex("rgb(255, 0, 0)");
chroma.rgb(255, 0, 0);
chroma.hsl(0, 1, 0.5);
chroma.hsv(120, 0.5, 0.5);
chroma.lab(53.24, 80.09, 67.20);
chroma.lch(53.24, 104.55, 40);
chroma.gl(1, 0, 0);
chroma.interpolate('white', 'black', 0) // #ffffff
chroma.interpolate('white', 'black', 1) // #000000
chroma.interpolate('white', 'black', 0.5) // #7f7f7f
chroma.interpolate('white', 'black', 0.5, 'hsv') // #808080
chroma.interpolate('white', 'black', 0.5, 'lab') // #777777
chroma.interpolate('rgba(0,0,0,0)', 'rgba(255,0,0,1)', 0.5).css() //"rgba(127.5,0,0,0.5)"
var bezInterpolator = chroma.interpolate.bezier(['white', 'yellow', 'red', 'black']);
bezInterpolator(0).hex() // #ffffff
bezInterpolator(0.33).hex() // #ffcc67
bezInterpolator(0.66).hex() // #b65f1a
bezInterpolator(1).hex() // #000000
chroma.luminance('black') // 0
chroma.luminance('white') // 1
chroma.luminance('#ff0000') // 0.2126
chroma.contrast('white', 'navy') // 16.00 ok
chroma.contrast('white', 'yellow') // 1.07 not ok!
}
function test_color() {
chroma('red').hex() // "#FF0000""
chroma('red').rgb() // [255, 0, 0]
chroma('red').hsv() // [0, 1, 1]
chroma('red').hsl() // [0, 1, 0.5]
chroma('red').lab() // [53.2407, 80.0924, 67.2031]
chroma('red').lch() // [53.2407, 104.5517, 39.9990]
chroma('red').rgba() // [255, 0, 0, 1]
chroma('red').css() // "rgb(255,0,0)"
chroma('red').alpha(0.7).css() // "rgba(255,0,0,0.7)"
chroma('red').css('hsl') // "hsl(0,100%,50%)"
chroma('red').alpha(0.7).css('hsl') // "hsla(0,100%,50%,0.7)"
chroma('blue').css('hsla') // "hsla(240,100%,50%,1)"
var red = chroma('red');
red.alpha(0.5);
red.css(); // rgba(255,0,0,0.5);
chroma('red').darken().hex() // #BC0000
chroma('red').brighten().hex() // #FF603B
chroma('#eecc99').saturate().hex() // #fcc973
chroma('red').desaturate().hex() // #ec3d23
chroma('black').luminance() // 0
chroma('white').luminance() // 1
chroma('red').luminance() // 0.2126
}
function test_scale() {
var scale = chroma.scale(['lightyellow', 'navy']);
scale(0.5); // #7F7FB0
chroma.scale('RdYlBu');
var col = scale(0.5);
col.hex(); // #7F7FB0
col.rgb(); // [127.5, 127.5, 176]
scale = chroma.scale(['lightyellow', 'navy']).out('hex');
scale(0.5); // "#7F7FB0"
var scale = chroma.scale(['lightyellow', 'navy']);
scale.mode('hsv')(0.5); // #54C08A
scale.mode('hsl')(0.5); // #31FF98
scale.mode('lab')(0.5); // #967CB2
scale.mode('lch')(0.5); // #D26662
var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 400]);
scale(200); // #7F7FB0
var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 100, 200, 300, 400]);
scale(98); // #7F7FB0
scale(99); // #7F7FB0
scale(100); // #AAAAC0
scale(101); // #AAAAC0
chroma.scale(['#eee', '#900']).domain([0, 400], 7);
chroma.scale(['#eee', '#900']).domain([1, 1000000], 7, 'log');
chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'quantiles');
chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'k-means');
chroma.scale(['white', 'red']).domain([0, 100], 4).domain() // [0, 25, 50, 75, 100]
chroma.scale().range(['lightyellow', 'navy']);
chroma.scale(['lightyellow', 'navy']).correctLightness(true);
chroma.scale('RdYlGn').domain([0,1], 5).colors()
}

317
chroma-js/chroma-js-0.5.6.d.ts vendored Normal file
View File

@ -0,0 +1,317 @@
// Type definitions for Chroma.js v0.5.6
// Project: https://github.com/gka/chroma.js
// Definitions by: Sebastian Brückner <https://github.com/invliD>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Chroma.js is a tiny library for all kinds of color conversions and color scales.
*/
declare namespace Chroma {
export interface ChromaStatic {
/**
* Creates a color from a string representation (as supported in CSS).
*
* @param color The string to convert to a color.
* @return the color object.
*/
(color: string): Color;
/**
* Create a color in the specified color space using a, b and c as values.
*
* @param a
* @param b
* @param c
* @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb".
* @return the color object.
*/
(a: number, b: number, c: number, colorSpace?: string): Color;
/**
* Create a color in the specified color space using values.
*
* @param values An array of values (e.g. [r, g, b, a?]).
* @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb".
* @return the color object.
*/
(values: number[], colorSpace?: string): Color;
/**
* Create a color in the specified color space using a, b and c as values.
*
* @param a
* @param b
* @param c
* @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb".
* @return the color object.
*/
color(a: number, b: number, c: number, colorSpace?: string): Color;
/**
* Calculate the contrast ratio of two colors.
*
* @param color1 The first color.
* @param color2 The second color.
* @return the contrast ratio.
*/
contrast(color1: Color, color2: Color): number;
/**
* Calculate the contrast ratio of two colors.
*
* @param color1 The first color.
* @param color2 The second color.
* @return the contrast ratio.
*/
contrast(color1: Color, color2: string): number;
/**
* Calculate the contrast ratio of two colors.
*
* @param color1 The first color.
* @param color2 The second color.
* @return the contrast ratio.
*/
contrast(color1: string, color2: Color): number;
/**
* Calculate the contrast ratio of two colors.
*
* @param color1 The first color.
* @param color2 The second color.
* @return the contrast ratio.
*/
contrast(color1: string, color2: string): number;
/**
* Create a color from a hex or string representation (as supported in CSS).
*
* This is an alias of chroma.hex().
*
* @param color The string to convert to a color.
* @return the color object.
*/
css(color: string): Color;
/**
* Create a color from a hex or string representation (as supported in CSS).
*
* This is an alias of chroma.css().
*
* @param color The string to convert to a color.
* @return the color object.
*/
hex(color: string): Color;
rgb(red: number, green: number, blue: number, alpha?: number): Color;
hsl(hue: number, saturation: number, lightness: number, alpha?: number): Color;
hsv(hue: number, saturation: number, value: number, alpha?: number): Color;
lab(lightness: number, a: number, b: number, alpha?: number): Color;
lch(lightness: number, chroma: number, hue: number, alpha?: number): Color;
gl(red: number, green: number, blue: number, alpha?: number): Color;
interpolate: InterpolateFunction;
mix: InterpolateFunction;
luminance(color: Color): number;
luminance(color: string): number;
/**
* Creates a color scale using a pre-defined color scale.
*
* @param name The name of the color scale.
* @return the resulting color scale.
*/
scale(name: string): Scale;
/**
* Creates a color scale function from the given set of colors.
*
* @param colors An Array of at least two color names or hex values.
* @return the resulting color scale.
*/
scale(colors?: string[]): Scale;
scales: PredefinedScales;
}
interface InterpolateFunction {
(color1: Color, color2: Color, f: number, mode?: string): Color;
(color1: Color, color2: string, f: number, mode?: string): Color;
(color1: string, color2: Color, f: number, mode?: string): Color;
(color1: string, color2: string, f: number, mode?: string): Color;
bezier(colors: any[]): (t: number) => Color;
}
interface PredefinedScales {
[key: string]: Scale;
cool: Scale;
hot: Scale;
}
export interface Color {
/**
* Creates a color from a string representation (as supported in CSS).
*
* @param color The string to convert to a color.
*/
new(color: string): Color;
/**
* Create a color in the specified color space using a, b and c as values.
*
* @param a
* @param b
* @param c
* @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb".
*/
new(a: number, b: number, c: number, colorSpace?: string): Color;
/**
* Create a color in the specified color space using a, b and c as color values and alpha as the alpha value.
*
* @param a
* @param b
* @param c
* @param alpha The alpha value of the color.
* @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb".
*/
new(a: number, b: number, c: number, alpha: number, colorSpace?: string): Color;
/**
* Create a color in the specified color space using values.
*
* @param values An array of values (e.g. [r, g, b, a?]).
* @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb".
*/
new(values: number[], colorSpace: string): Color;
/**
* Convert this color to CSS hex representation.
*
* @return this color's hex representation.
*/
hex(): string;
/**
* @return the relative luminance of the color, which is a value between 0 (black) and 1 (white).
*/
luminance(): number;
/**
* @return the X11 name of this color or its hex value if it does not have a name.
*/
name(): string;
/**
* @return the alpha value of the color.
*/
alpha(): number;
/**
* Set the alpha value.
*
* @param alpha The alpha value.
* @return this
*/
alpha(alpha: number): Color;
css(mode?: string): string;
interpolate(color: Color, f: number, mode?: string): Color;
interpolate(color: string, f: number, mode?: string): Color;
premultiply(): Color;
rgb(): number[];
rgba(): number[];
hsl(): number[];
hsv(): number[];
lab(): number[];
lch(): number[];
hsi(): number[];
gl(): number[];
darken(amount?: number): Color;
darker(amount: number): Color;
brighten(amount?: number): Color;
brighter(amount: number): Color;
saturate(amount?: number): Color;
desaturate(amount?: number): Color;
toString(): string;
}
export interface Scale {
/**
* Interpolate a color using the currently set range and domain.
*
* @param value The value to use for interpolation.
* @return the interpolated hex color OR a Color object (depending on the mode set on this Scale).
*/
(value: number): any;
/**
* Retreive all possible colors generated by this scale if it has distinct classes.
*
* @param mode The output mode to use. Must be one of Color's getters. Defaults to "hex".
* @return an array of colors in the type specified by mode.
*/
colors(mode?: string): any[];
correctLightness(): boolean;
/**
* Enable or disable automatic lightness correction of this scale.
*
* @param Whether to enable or disable automatic lightness correction.
* @return this
*/
correctLightness(enable: boolean): Scale;
/**
* Get the current domain.
*
* @return The current domain.
*/
domain(): number[];
/**
* Set the domain.
*
* @param domain An Array of at least two numbers (min and max).
* @param classes The number of fixed classes to create between min and max.
* @param mode The scale to use. Examples: log, quantiles, k-means.
* @return this
*/
domain(domain: number[], classes?: number, mode?: string): Scale;
/**
* Specify in which color space the colors should be interpolated. Defaults to "rgb".
* You can use any of the following spaces: rgb, hsv, hsl, lab, lch
*
* @param colorSpace The color space to use for interpolation.
* @return this
*/
mode(colorSpace: string): Scale;
/**
* Set the output mode of this Scale.
*
* @param mode The output mode to use. Must be one of Color's getters.
* @return this
*/
out(mode: string): Scale;
/**
* Set the color range after initialization.
*
* @param colors An Array of at least two color names or hex values.
* @return this
*/
range(colors: string[]): Scale;
}
}
declare var chroma: Chroma.ChromaStatic;

View File

@ -1,120 +1,166 @@
function test_chroma() {
chroma("red");
chroma("#ff0000");
chroma("#f00");
chroma("FF0000");
chroma(255, 0, 0);
chroma([255, 0, 0]);
chroma(0, 1, 0.5, 'hsl');
chroma([0, 1, 0.5], 'hsl');
chroma(0, 1, 1, 'hsv');
chroma("rgb(255,0,0)");
chroma("rgb(100%,0%,0%)");
chroma("hsl(0,100%,50%)");
chroma(53.24, 80.09, 67.20, 'lab');
chroma(53.24, 104.55, 40, 'lch');
chroma(1, 0, 0, 'gl');
chroma.hex("#ff0000");
chroma.hex("red");
chroma.hex("rgb(255, 0, 0)");
chroma.rgb(255, 0, 0);
chroma.hsl(0, 1, 0.5);
chroma.hsv(120, 0.5, 0.5);
chroma.lab(53.24, 80.09, 67.20);
chroma.lch(53.24, 104.55, 40);
chroma.gl(1, 0, 0);
chroma.interpolate('white', 'black', 0) // #ffffff
chroma.interpolate('white', 'black', 1) // #000000
chroma.interpolate('white', 'black', 0.5) // #7f7f7f
chroma.interpolate('white', 'black', 0.5, 'hsv') // #808080
chroma.interpolate('white', 'black', 0.5, 'lab') // #777777
chroma.interpolate('rgba(0,0,0,0)', 'rgba(255,0,0,1)', 0.5).css() //"rgba(127.5,0,0,0.5)"
var bezInterpolator = chroma.interpolate.bezier(['white', 'yellow', 'red', 'black']);
bezInterpolator(0).hex() // #ffffff
bezInterpolator(0.33).hex() // #ffcc67
bezInterpolator(0.66).hex() // #b65f1a
bezInterpolator(1).hex() // #000000
chroma.luminance('black') // 0
chroma.luminance('white') // 1
chroma.luminance('#ff0000') // 0.2126
chroma.contrast('white', 'navy') // 16.00 ok
chroma.contrast('white', 'yellow') // 1.07 not ok!
chroma('hotpink');
chroma('#ff3399');
chroma('F39');
chroma.hex("#fff");
chroma(0xff3399);
chroma(0xff, 0x33, 0x99);
chroma(255, 51, 153);
chroma([255, 51, 153]);
chroma(330, 1, 0.6, 'hsl');
chroma.hsl(330, 1, 0.6);
chroma.lch(80, 40, 130);
chroma(80, 40, 130, 'lch');
chroma.cmyk(0.2, 0.8, 0, 0);
chroma(0.2, 0.8, 0, 0, 'cmyk');
chroma.gl(0.6, 0, 0.8);
chroma.gl(0.6, 0, 0.8, 0.5);
chroma(0.6, 0, 0.8, 'gl');
chroma.temperature(2000);
chroma.temperature(3500);
chroma.temperature(6000);
chroma.mix('red', 'blue');
chroma.mix('red', 'blue', 0.25);
chroma.mix('red', 'blue', 0.5, 'rgb');
chroma.mix('red', 'blue', 0.5, 'hsl');
chroma.mix('red', 'blue', 0.5, 'lab');
chroma.mix('red', 'blue', 0.5, 'lch');
chroma.blend('4CBBFC', 'EEEE22', 'multiply');
chroma.blend('4CBBFC', 'EEEE22', 'darken');
chroma.blend('4CBBFC', 'EEEE22', 'lighten');
chroma.random();
chroma.contrast('pink', 'hotpink');
chroma.contrast('pink', 'purple');
chroma.brewer.OrRd;
var data = [3.0, 3.5, 3.6, 3.8, 3.8, 4.1, 4.3, 4.4,
4.6, 4.9, 5.2, 5.3, 5.4, 5.7, 5.8, 5.9,
6.2, 6.5, 6.8, 7.2, 9];
chroma.limits(data, 'e', 5);
chroma.limits(data, 'q', 5);
chroma.limits(data, 'k', 5);
}
function test_color() {
chroma('red').hex() // "#FF0000""
chroma('red').rgb() // [255, 0, 0]
chroma('red').hsv() // [0, 1, 1]
chroma('red').hsl() // [0, 1, 0.5]
chroma('red').lab() // [53.2407, 80.0924, 67.2031]
chroma('red').lch() // [53.2407, 104.5517, 39.9990]
chroma('red').rgba() // [255, 0, 0, 1]
chroma('red').css() // "rgb(255,0,0)"
chroma('red').alpha(0.7).css() // "rgba(255,0,0,0.7)"
chroma('red').css('hsl') // "hsl(0,100%,50%)"
chroma('red').alpha(0.7).css('hsl') // "hsla(0,100%,50%,0.7)"
chroma('blue').css('hsla') // "hsla(240,100%,50%,1)"
var red = chroma('red');
red.alpha(0.5);
red.css(); // rgba(255,0,0,0.5);
chroma('red').darken().hex() // #BC0000
chroma('red').brighten().hex() // #FF603B
chroma('#eecc99').saturate().hex() // #fcc973
chroma('red').desaturate().hex() // #ec3d23
chroma('black').luminance() // 0
chroma('white').luminance() // 1
chroma('red').luminance() // 0.2126
chroma('red').alpha(0.5);
chroma('rgba(255,0,0,0.35)').alpha();
chroma('hotpink').darken();
chroma('hotpink').darken(2);
chroma('hotpink').brighten();
chroma('slategray').saturate();
chroma('slategray').saturate(2);
chroma('hotpink').desaturate();
chroma('hotpink').desaturate(2);
chroma('hotpink').desaturate(3);
// change hue to 0 deg (=red)
chroma('skyblue').set('hsl.h', 0);
// set chromacity to 30
chroma('hotpink').set('lch.c', 30);
// half Lab lightness
chroma('orangered').set('lab.l', '*0.5');
// double Lch saturation
chroma('darkseagreen').set('lch.c', '*2');
chroma('orangered').get('lab.l');
chroma('orangered').get('hsl.l');
chroma('orangered').get('rgb.g');
chroma('white').luminance();
chroma('aquamarine').luminance();
chroma('hotpink').luminance();
chroma('darkslateblue').luminance();
chroma('black').luminance();
chroma('white').luminance(0.5);
chroma('aquamarine').luminance(0.5);
chroma('hotpink').luminance(0.5);
chroma('darkslateblue').luminance(0.5);
chroma('aquamarine').luminance(0.5);
chroma('aquamarine').luminance(0.5, 'lab');
chroma('aquamarine').luminance(0.5, 'hsl');
chroma('orange').hex();
chroma('#ffa500').name();
chroma('#ffa505').name();
chroma('teal').css();
chroma('teal').alpha(0.5).css();
chroma('teal').css('hsl');
chroma('orange').rgb();
chroma('orange').hsl();
chroma('white').hsl();
chroma('orange').hsv();
chroma('white').hsv();
chroma('orange').hsi();
chroma('white').hsi();
chroma('orange').lab();
chroma('skyblue').lch();
chroma('skyblue').hcl();
chroma('#ff3300').temperature();
chroma('#ff8a13').temperature();
chroma('#ffe3cd').temperature();
chroma('#cbdbff').temperature();
chroma('#b3ccff').temperature();
chroma('33cc00').gl();
}
function test_scale() {
var scale = chroma.scale(['lightyellow', 'navy']);
scale(0.5); // #7F7FB0
var f = chroma.scale();
f(0.25);
f(0.5);
f(0.75);
chroma.scale(['yellow', '008ae5']);
chroma.scale(['yellow', 'red', 'black']);
// default domain is [0,1]
chroma.scale(['yellow', '008ae5']);
// set domain to [0,100]
chroma.scale(['yellow', '008ae5']).domain([0, 100]);
// default domain is [0,1]
chroma.scale(['yellow', 'lightgreen', '008ae5'])
.domain([0, 0.25, 1]);
chroma.scale(['yellow', '008ae5']);
chroma.scale(['yellow', 'navy']);
chroma.scale(['yellow', 'navy']).mode('lab');
chroma.scale(['yellow', 'navy']).mode('lab');
chroma.scale(['yellow', 'navy']).mode('hsl');
chroma.scale(['yellow', 'navy']).mode('lch');
chroma.scale('YlGnBu');
chroma.scale('Spectral');
chroma.scale('Spectral').domain([1, 0]);
chroma.brewer.OrRd;
chroma.scale(['yellow', '008ae5']).mode('lch');
chroma.scale(['yellow', '008ae5'])
.mode('lch')
.correctLightness();
// linear interpolation
chroma.scale(['yellow', 'red', 'black']);
// bezier interpolation
chroma.bezier(['yellow', 'red', 'black']);
// convert bezier interpolator into chroma.scale
chroma.bezier(['yellow', 'red', 'black'])
.scale().colors(5);
// use the default helix...
chroma.cubehelix();
// or customize it
chroma.cubehelix()
.start(200)
.rotations(-0.5)
.gamma(0.8)
.lightness([0.3, 0.8]);
chroma.cubehelix()
.start(200)
.rotations(-0.35)
.gamma(0.7)
.lightness([0.3, 0.8])
.scale() // convert to chroma.scale
.correctLightness()
.colors(5);
chroma.scale('RdYlBu');
chroma.scale('RdYlBu').padding(0.15);
var col = scale(0.5);
col.hex(); // #7F7FB0
col.rgb(); // [127.5, 127.5, 176]
chroma.scale('OrRd');
chroma.scale('OrRd').padding([0.2, 0]);
scale = chroma.scale(['lightyellow', 'navy']).out('hex');
scale(0.5); // "#7F7FB0"
var scale = chroma.scale(['lightyellow', 'navy']);
scale.mode('hsv')(0.5); // #54C08A
scale.mode('hsl')(0.5); // #31FF98
scale.mode('lab')(0.5); // #967CB2
scale.mode('lch')(0.5); // #D26662
var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 400]);
scale(200); // #7F7FB0
var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 100, 200, 300, 400]);
scale(98); // #7F7FB0
scale(99); // #7F7FB0
scale(100); // #AAAAC0
scale(101); // #AAAAC0
chroma.scale(['#eee', '#900']).domain([0, 400], 7);
chroma.scale(['#eee', '#900']).domain([1, 1000000], 7, 'log');
chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'quantiles');
chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'k-means');
chroma.scale(['white', 'red']).domain([0, 100], 4).domain() // [0, 25, 50, 75, 100]
chroma.scale().range(['lightyellow', 'navy']);
chroma.scale(['lightyellow', 'navy']).correctLightness(true);
chroma.scale('RdYlGn').domain([0,1], 5).colors()
chroma.scale('OrRd').classes(5);
chroma.scale('OrRd').classes(8);
}

400
chroma-js/index.d.ts vendored
View File

@ -1,14 +1,14 @@
// Type definitions for Chroma.js v0.5.6
// Type definitions for Chroma.js v1.1.1
// Project: https://github.com/gka/chroma.js
// Definitions by: Sebastian Brückner <https://github.com/invliD>
// Definitions by: Sebastian Brückner <https://github.com/invliD>, Marcin Pacholec <https://github.com/mpacholec>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Chroma.js is a tiny library for all kinds of color conversions and color scales.
*/
declare namespace Chroma {
export interface ChromaStatic {
/**
* Creates a color from a string representation (as supported in CSS).
*
@ -17,6 +17,14 @@ declare namespace Chroma {
*/
(color: string): Color;
/**
* Creates a color from a number representation [0; 16777215]
*
* @param color The number to convert to a color.
* @return the color object.
*/
(number: number): Color;
/**
* Create a color in the specified color space using a, b and c as values.
*
@ -25,72 +33,20 @@ declare namespace Chroma {
* @param c
* @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb".
* @return the color object.
*/
*/
(a: number, b: number, c: number, colorSpace?: string): Color;
(a: number, b: number, c: number, d: number, colorSpace?: string): Color;
/**
* Create a color in the specified color space using values.
*
* @param values An array of values (e.g. [r, g, b, a?]).
* @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb".
* @return the color object.
*/
* Create a color in the specified color space using values.
*
* @param values An array of values (e.g. [r, g, b, a?]).
* @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb".
* @return the color object.
*/
(values: number[], colorSpace?: string): Color;
/**
* Create a color in the specified color space using a, b and c as values.
*
* @param a
* @param b
* @param c
* @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb".
* @return the color object.
*/
color(a: number, b: number, c: number, colorSpace?: string): Color;
/**
* Calculate the contrast ratio of two colors.
*
* @param color1 The first color.
* @param color2 The second color.
* @return the contrast ratio.
*/
contrast(color1: Color, color2: Color): number;
/**
* Calculate the contrast ratio of two colors.
*
* @param color1 The first color.
* @param color2 The second color.
* @return the contrast ratio.
*/
contrast(color1: Color, color2: string): number;
/**
* Calculate the contrast ratio of two colors.
*
* @param color1 The first color.
* @param color2 The second color.
* @return the contrast ratio.
*/
contrast(color1: string, color2: Color): number;
/**
* Calculate the contrast ratio of two colors.
*
* @param color1 The first color.
* @param color2 The second color.
* @return the contrast ratio.
*/
contrast(color1: string, color2: string): number;
/**
* Create a color from a hex or string representation (as supported in CSS).
*
* This is an alias of chroma.hex().
*
* @param color The string to convert to a color.
* @return the color object.
*/
css(color: string): Color;
/**
* Create a color from a hex or string representation (as supported in CSS).
*
@ -101,217 +57,209 @@ declare namespace Chroma {
*/
hex(color: string): Color;
rgb(red: number, green: number, blue: number, alpha?: number): Color;
hsl(hue: number, saturation: number, lightness: number, alpha?: number): Color;
hsv(hue: number, saturation: number, value: number, alpha?: number): Color;
hsl(h: number, s: number, l: number): Color;
hsv(h: number, s: number, v: number): Color;
lab(lightness: number, a: number, b: number, alpha?: number): Color;
lch(lightness: number, chroma: number, hue: number, alpha?: number): Color;
lch(l: number, c: number, h: number): Color;
rgb(r: number, g: number, b: number): Color;
/**
* GL is a variant of RGB(A), with the only difference that the components are normalized to the range of 0..1.
*/
gl(red: number, green: number, blue: number, alpha?: number): Color;
interpolate: InterpolateFunction;
mix: InterpolateFunction;
/**
* light 2000K, bright sunlight 6000K. Based on Neil Bartlett's implementation.
* https://github.com/neilbartlett/color-temperature
*/
temperature(t: number): Color;
luminance(color: Color): number;
luminance(color: string): number;
mix(col1: string | Color, col2: string | Color, f?: number, colorSpace?: string): Color;
interpolate(col1: string | Color, col2: string | Color, f?: number, colorSpace?: string): Color;
/**
* Creates a color scale using a pre-defined color scale.
*
* @param name The name of the color scale.
* @return the resulting color scale.
* Blends two colors using RGB channel-wise blend functions. Valid blend modes are multiply, darken, lighten, screen, overlay, burn, and dogde.
*/
blend(col1: string, col2: string, blendMode: string): Color;
/**
* Returns a random color.
*/
random(): Color;
/**
* Computes the WCAG contrast ratio between two colors.
* A minimum contrast of 4.5:1 is recommended to ensure that text is still readable against a background color.
*
* @param color1 The first color.
* @param color2 The second color.
* @return the contrast ratio.
*/
contrast(col1: string | Color, col2: string | Color): number;
bezier(colors: string[]): Scale;
/**
* chroma.brewer is an map of ColorBrewer scales that are included in chroma.js for convenience.
* chroma.scale uses the colors to construct.
*/
brewer: {
OrRd: string[];
PuBu: string[];
BuPu: string[];
Oranges: string[];
BuGn: string[];
YlOrBr: string[];
YlGn: string[];
Reds: string[];
RdPu: string[];
Greens: string[];
YlGnBu: string[];
Purples: string[];
GnBu: string[];
Greys: string[];
YlOrRd: string[];
PuRd: string[];
Blues: string[];
PuBuGn: string[];
Spectral: string[];
RdYlGn: string[];
RdBu: string[];
PiYG: string[];
PRGn: string[];
RdYlBu: string[];
BrBG: string[];
RdGy: string[];
PuOr: string[];
Set2: string[];
Accent: string[];
Set1: string[];
Set3: string[];
Dark2: string[];
Paired: string[];
Pastel2: string[];
Pastel1: string[];
};
/**
* Helper function that computes class breaks for you, based on actual data.
* Supports three different modes: equidistant breaks, quantiles breaks and breaks based on k-means clusting.
*/
limits(data: number[], mode: string, c: number): number[];
scale(name: string): Scale;
/**
* Creates a color scale function from the given set of colors.
*
* @param colors An Array of at least two color names or hex values.
* @return the resulting color scale.
*/
scale(colors?: string[]): Scale;
scales: PredefinedScales;
}
cubehelix(): Cubehelix;
interface InterpolateFunction {
(color1: Color, color2: Color, f: number, mode?: string): Color;
(color1: Color, color2: string, f: number, mode?: string): Color;
(color1: string, color2: Color, f: number, mode?: string): Color;
(color1: string, color2: string, f: number, mode?: string): Color;
bezier(colors: any[]): (t: number) => Color;
}
interface PredefinedScales {
[key: string]: Scale;
cool: Scale;
hot: Scale;
cmyk(c: number, m: number, y: number, k: number): Color;
/**
* Create a color from a hex or string representation (as supported in CSS).
*
* This is an alias of chroma.hex().
*
* @param color The string to convert to a color.
* @return the color object.
*/
css(col: string, mode?: string): string;
}
export interface Color {
/**
* Creates a color from a string representation (as supported in CSS).
*
* @param color The string to convert to a color.
*/
new(color: string): Color;
alpha(a?: number): Color;
/**
* Create a color in the specified color space using a, b and c as values.
*
* @param a
* @param b
* @param c
* @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb".
*/
new(a: number, b: number, c: number, colorSpace?: string): Color;
darken(f?: number): Color;
/**
* Create a color in the specified color space using a, b and c as color values and alpha as the alpha value.
*
* @param a
* @param b
* @param c
* @param alpha The alpha value of the color.
* @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb".
*/
new(a: number, b: number, c: number, alpha: number, colorSpace?: string): Color;
brighten(f?: number): Color;
/**
* Create a color in the specified color space using values.
*
* @param values An array of values (e.g. [r, g, b, a?]).
* @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb".
*/
new(values: number[], colorSpace: string): Color;
saturate(s?: number): Color;
/**
* Convert this color to CSS hex representation.
*
* @return this color's hex representation.
*/
hex(): string;
desaturate(s?: number): Color;
set(modechan: string, v: number | string): Color;
get(modechan: string): number;
/**
* @return the relative luminance of the color, which is a value between 0 (black) and 1 (white).
*/
luminance(): number;
/**
* @return the X11 name of this color or its hex value if it does not have a name.
*/
luminance(l: number, mode?: string): Color;
hex(): string;
name(): string;
/**
* @return the alpha value of the color.
*/
alpha(): number;
/**
* Set the alpha value.
* Create a color from a hex or string representation (as supported in CSS).
*
* @param alpha The alpha value.
* @return this
* This is an alias of chroma.hex().
*
* @param color The string to convert to a color.
* @return the color object.
*/
alpha(alpha: number): Color;
css(mode?: string): string;
interpolate(color: Color, f: number, mode?: string): Color;
interpolate(color: string, f: number, mode?: string): Color;
premultiply(): Color;
rgb(): number[];
rgba(): number[];
hsl(): number[];
hsv(): number[];
lab(): number[];
lch(): number[];
hsi(): number[];
lab(): number[];
lch(): number[];
hcl(): number[];
temperature(): number;
gl(): number[];
darken(amount?: number): Color;
darker(amount: number): Color;
brighten(amount?: number): Color;
brighter(amount: number): Color;
saturate(amount?: number): Color;
desaturate(amount?: number): Color;
toString(): string;
}
export interface Scale {
/**
* Interpolate a color using the currently set range and domain.
*
* @param value The value to use for interpolation.
* @return the interpolated hex color OR a Color object (depending on the mode set on this Scale).
*/
(c: string[]): Scale;
(value: number): any;
/**
* Retreive all possible colors generated by this scale if it has distinct classes.
*
* @param mode The output mode to use. Must be one of Color's getters. Defaults to "hex".
* @return an array of colors in the type specified by mode.
*/
colors(mode?: string): any[];
domain(d?: number[], n?: number, mode?: string): Scale;
correctLightness(): boolean;
mode(mode: string): Scale;
/**
* Enable or disable automatic lightness correction of this scale.
*
* @param Whether to enable or disable automatic lightness correction.
* @return this
*/
correctLightness(enable: boolean): Scale;
correctLightness(enable?: boolean): Scale;
/**
* Get the current domain.
*
* @return The current domain.
*/
domain(): number[];
bezier(colors: string[]): Scale;
/**
* Set the domain.
*
* @param domain An Array of at least two numbers (min and max).
* @param classes The number of fixed classes to create between min and max.
* @param mode The scale to use. Examples: log, quantiles, k-means.
* @return this
*/
domain(domain: number[], classes?: number, mode?: string): Scale;
padding(p: number | number[]): Scale;
/**
* Specify in which color space the colors should be interpolated. Defaults to "rgb".
* You can use any of the following spaces: rgb, hsv, hsl, lab, lch
*
* @param colorSpace The color space to use for interpolation.
* @return this
*/
mode(colorSpace: string): Scale;
colors(c?: number): string[];
classes(c: number | number[]): (t: number) => Color;
range(arg: string[]): Scale;
scale(): Scale;
/**
* Set the output mode of this Scale.
*
* @param mode The output mode to use. Must be one of Color's getters.
* @return this
*/
out(mode: string): Scale;
/**
* Set the color range after initialization.
*
* @param colors An Array of at least two color names or hex values.
* @return this
*/
range(colors: string[]): Scale;
}
export interface Cubehelix extends Scale {
start(s: number): Cubehelix;
rotations(r: number): Cubehelix;
gamma(g: number): Cubehelix;
lightness(l: number[]): Cubehelix;
}
}
declare var chroma: Chroma.ChromaStatic;

View File

@ -6,6 +6,17 @@
/// <reference path="chrome.d.ts"/>
/// <reference types="filesystem"/>
////////////////////
// App
////////////////////
declare namespace chrome.app {
interface AppDetails extends chrome.runtime.Manifest {
id: string;
}
export function getDetails(): AppDetails;
}
////////////////////
// App Runtime
////////////////////

10
chrome/index.d.ts vendored
View File

@ -7219,7 +7219,7 @@ declare namespace chrome.webRequest {
* Optional.
* If the request method is POST and the body is a sequence of key-value pairs encoded in UTF8, encoded as either multipart/form-data, or application/x-www-form-urlencoded, this dictionary is present and for each key contains the list of all values for that key. If the data is of another media type, or if it is malformed, the dictionary is not present. An example value of this dictionary is {'key': ['value1', 'value2']}.
*/
formData?: Object;
formData?: { [key: string]: string[] };
/**
* Optional.
* If the request method is PUT or POST, and the body is not already parsed in formData, then the unparsed request body elements are contained in this array.
@ -7233,6 +7233,7 @@ declare namespace chrome.webRequest {
}
interface ResourceRequest {
url: string;
/** The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request. */
requestId: string;
/** The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. */
@ -7251,7 +7252,6 @@ declare namespace chrome.webRequest {
}
interface WebRequestDetails extends ResourceRequest {
url: string;
/** Standard HTTP method. */
method: string;
}
@ -7304,7 +7304,7 @@ declare namespace chrome.webRequest {
interface WebAuthenticationChallengeDetails extends WebResponseHeadersDetails {
/** The authentication scheme, e.g. Basic or Digest. */
schema: string;
scheme: string;
/** The authentication realm provided by the server, if there is one. */
realm?: string;
/** The server requesting authentication. */
@ -7336,7 +7336,9 @@ declare namespace chrome.webRequest {
interface WebRedirectionResponseEvent extends _WebResponseHeadersEvent<WebRedirectionResponseDetails> {}
interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void> {}
interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void> {
addListener(callback: (details: WebAuthenticationChallengeDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void;
}
interface WebResponseErrorEvent extends _WebResponseHeadersEvent<WebResponseErrorDetails> {}

1
cors/index.d.ts vendored
View File

@ -16,6 +16,7 @@ declare namespace e {
exposedHeaders?: any;
credentials?: boolean;
maxAge?: number;
preflightContinue?: boolean;
}
}

View File

@ -0,0 +1,42 @@
/// <reference path="countdown.d.ts" />
import { countdown, Timespan, CountdownStatic, Format } from 'countdown';
let ts: Timespan;
let interval: number;
ts = <Timespan>countdown(new Date());
ts = <Timespan>countdown(150);
interval = <number>countdown(new Date(),
function (ts: Timespan) {
document.getElementById('pageTimer').innerHTML = ts.toHTML('strong');
},
countdown.HOURS | countdown.MINUTES | countdown.SECONDS,
2,
2
);
clearInterval(interval);
ts.toString('foo');
ts.toHTML('em', 'foo');
countdown.resetFormat();
countdown.setLabels('a', 'b', 'c', 'd', 'e');
countdown.setLabels('a', 'b', 'c', 'd', 'e', function (value: number): string {
return 'ok';
}, function (value: number, unit: number): string {
return 'ok';
});
countdown.setLabels(null, null, null, null, 'Now.');
countdown.setLabels(
' millisecond| second| minute| hour| day| week| month| year| decade| century| millennium',
' milliseconds| seconds| minutes| hours| days| weeks| months| years| decades| centuries| millennia',
' and ',
', ',
'',
n => n.toString());

69
countdown/countdown.d.ts vendored Normal file
View File

@ -0,0 +1,69 @@
// Type definitions for countdown.js
// Project: http://countdownjs.org/
// Definitions by: Gabriel Juchault <https://github.com/gjuchault>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'countdown' {
export type DateFunction = (timespan: Timespan) => void;
export type DateTime = number | Date | DateFunction;
export interface Timespan {
start?: Date;
end?: Date;
units?: number;
value?: number;
millennia?: number;
centuries?: number;
decades?: number;
years?: number;
months?: number;
days?: number;
hours?: number;
minutes?: number;
seconds?: number;
milliseconds?: number;
toString(label?: string): string;
toHTML(tagName?: string, label?: string): string;
}
export interface Format {
singular?: string | Array<string>;
plural?: string | Array<string>;
last?: string;
delim?: string;
empty?: string;
formatNumber?(value: number): string;
formatter?(value: number, unit: number): string;
}
export interface CountdownStatic {
(start: DateTime, end?: DateTime, units?: number, max?: number, digits?: number): Timespan | number;
MILLENNIA: number;
CENTURIES: number;
DECADES: number;
YEARS: number;
MONTHS: number;
WEEKS: number;
DAYS: number;
HOURS: number;
MINUTES: number;
SECONDS: number;
MILLISECONDS: number;
ALL: number;
DEFAULTS: number;
resetLabels(): void;
setLabels(
singular?: string,
plural?: string,
last?: string,
delim?: string,
empty?: string,
formatNumber?: (value: number) => string,
formatter?: (value: number, unit: number) => string
): void;
resetFormat(): void;
setFormat(format: Format): void;
}
export let countdown: CountdownStatic;
}

View File

@ -1 +1,15 @@
import * as Cropper from 'cropperjs';
var image = <HTMLImageElement>document.getElementById('image');
var cropper = new Cropper(image, {
aspectRatio: 16 / 9,
crop: function(e) {
console.log(e.detail.x);
console.log(e.detail.y);
console.log(e.detail.width);
console.log(e.detail.height);
console.log(e.detail.rotate);
console.log(e.detail.scaleX);
console.log(e.detail.scaleY);
}
});

19
cropperjs/index.d.ts vendored
View File

@ -10,7 +10,26 @@ declare namespace cropperjs {
CanvasShouldNotBeWithInTheContainer = 2,
ContainerSshouldBeWithInTheCanvas = 3
}
export interface CropperCustomEvent extends CustomEvent {
detail: Data;
}
export interface CropperOptions {
/**
* Function called when crop box is moved or resized
*/
crop?: (event: CropperCustomEvent) => void;
/**
* Function called at start of crop box being moved or resized
*/
cropstart?: (event: CropperCustomEvent) => void;
/**
* Function called when crop box is moved
*/
cropmove?: (event: CropperCustomEvent) => void;
/**
* Function called when crop box is finished being moved or resized
*/
cropend?: (event: CropperCustomEvent) => void;
/**
* Define the view mode of the cropper.
* @default 0

View File

@ -97,6 +97,7 @@ declare namespace CryptoJS {
Base64: Encoder;
};
mode: {
CBC: Mode;
CFB: Mode;
CTR: Mode;
CTRGladman: Mode;

4
csurf/index.d.ts vendored
View File

@ -1,4 +1,4 @@
// Type definitions for csurf
// Type definitions for csurf 1.9.0
// Project: https://www.npmjs.org/package/csurf
// Definitions by: Hiroki Horiuchi <https://github.com/horiuchi/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@ -17,6 +17,8 @@ declare module "csurf" {
function csurf(options?: {
value?: (req: express.Request) => string;
cookie?: csurf.CookieOptions | boolean;
ignoreMethods?: string[];
sessionKey?: string;
}): express.RequestHandler;
namespace csurf {

2
dojo/dijit.d.ts vendored
View File

@ -1606,7 +1606,7 @@ declare module dijit {
* already removed/destroyed manually.
*
*/
own(): any;
own(...args: any[]): any[];
/**
* Place this widget somewhere in the DOM based
* on standard domConstruct.place() conventions.

4
dojo/index.d.ts vendored
View File

@ -5617,7 +5617,7 @@ declare namespace dojo {
* @param scope The scope to use when method executes. If method is a string,scope is also the object containing method.
* @param method A function to be hitched to scope, or the name of the method inscope to be hitched.
*/
hitch(scope: Object, method: Function): any;
hitch(scope: Object, method: (...args: any[]) => any, ...args: any[]): any;
/**
* Returns a function that will only ever execute in the a given scope.
* This allows for easy use of object member functions
@ -5631,7 +5631,7 @@ declare namespace dojo {
* @param scope The scope to use when method executes. If method is a string,scope is also the object containing method.
* @param method A function to be hitched to scope, or the name of the method inscope to be hitched.
*/
hitch(scope: Object, method: String[]): any;
hitch(scope: Object, method: string, ...args: any[]): any;
/**
* Returns true if it is a built-in function or some other kind of
* oddball that should report as a function but doesn't

277
draft-js/draft-js-0.2.2.d.ts vendored Normal file
View File

@ -0,0 +1,277 @@
// Type definitions for draft-js 0.2.2
// Project: https://github.com/facebook/draft-js
// Definitions by: Pavel Evsegneev <https://github.com/Ahineya>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "draft-js" {
namespace Draft {
interface IEditor {
new(): Editor
}
interface EditorState {
getCurrentContent(): ContentState,
getSelection(): SelectionState,
getCurrentInlineStyle(): any,
getBlockTree(): any,
createEmpty(decorator?: any): EditorState,
createWithContent(contentState: ContentState, decorator?: any): EditorState,
create(config: any): EditorState,
push(editorState: EditorState, contentState: ContentState, actionType: string): EditorState,
undo(editorState: EditorState): EditorState,
redo(editorState: EditorState): EditorState,
acceptSelection(editorState: EditorState, selectionState: SelectionState): EditorState,
forceSelection(editorState: EditorState, selectionState: SelectionState): EditorState,
moveFocusToEnd(editorState: EditorState): EditorState
}
interface CompositeDecorator {
getDecorations(): Array<any>,
getComponentForKey(): any,
getPropsForKey(): any
}
interface Entity {
create(type: string, mutability: string, data?: Object): EntityInstance,
add(instance: EntityInstance): string,
get(key: string): EntityInstance,
mergeData(key: string, toMerge: any): EntityInstance,
replaceData(key: string, newData: any): EntityInstance
}
interface EntityInstance {
getData(): any,
getKey(): string,
getMutability(): string
}
interface BlockMapBuilder {
createFromArray(blocks: Array<ContentBlock>): BlockMap
}
interface CharacterMetadata {
create(config?: any): CharacterMetadata,
applyStyle(record: CharacterMetadata,
style: string): CharacterMetadata,
removeStyle(record: CharacterMetadata,
style: string): CharacterMetadata,
applyEntity(record: CharacterMetadata,
entityKey?: string): CharacterMetadata,
getStyle(): any,
hasStyle(style: string): boolean,
getEntity(): string
}
interface IContentBlock {
new(draftContentBlock: any): ContentBlock;
}
interface ContentBlock {
key: string,
type: string,
text: string,
characterList: any,
depth: number,
getKey(): string,
getType(): string,
getText(): string,
getCharacterList(): any,
getLength(): number,
getDepth(): number,
getInlineStyleAt(offset: number): any,
getEntityAt(offset: number): string,
findStyleRanges(filterFn: Function, callback: Function): void,
findEntityRanges(filterFn: Function, callback: Function): void
}
interface ContentState {
createFromText(text: string): ContentState,
createFromBlockArray(blocks: Array<ContentBlock>): ContentState,
getBlockMap(): BlockMap,
getSelectionBefore(): SelectionState,
getSelectionAfter(): SelectionState,
getBlockForKey(key: string): ContentBlock,
getKeyBefore(key: string): string,
getKeyAfter(key: string): string,
getBlockBefore(key: string): ContentBlock,
getBlockAfter(key: string): ContentBlock,
getBlocksAsArray(): Array<ContentBlock>,
getPlainText(): string,
hasText(): boolean,
set(key: string, value: any): ContentState,
toJS(): any
}
interface ISelectionState {
new(draftSelectionState: any): SelectionState;
createEmpty(blockKey: string): SelectionState;
}
interface SelectionState {
getStartKey(): string,
getStartOffset(): number,
getEndKey(): string,
getEndOffset(): number,
getAnchorKey(): string,
getAnchorOffset(): number,
getFocusKey(): string,
getFocusOffset(): number,
getIsBackward(): boolean,
getHasFocus(): boolean,
isCollapsed(): boolean,
hasEdgeWithin(blockKey: string, start: number, end: number): boolean,
serialize(): string,
get(key: string): any,
set(key: string, value: any): SelectionState
}
interface BlockMap {
get(key: string): ContentBlock,
set(key: string, value: any): BlockMap,
delete(key: string): BlockMap,
find(cb: any): ContentBlock
}
interface Modifier {
replaceText(contentState: ContentState,
rangeToReplace: SelectionState,
text: string,
inlineStyle?: any,
entityKey?: string): ContentState,
insertText(contentState: ContentState,
targetRange: SelectionState,
text: string,
inlineStyle?: any,
entityKey?: string): ContentState,
moveText(contentState: ContentState,
removalRange: SelectionState,
targetRange: SelectionState): ContentState,
replaceWithFragment(contentState: ContentState,
targetRange: SelectionState,
fragment: BlockMap): ContentState,
removeRange(contentState: ContentState,
rangeToRemove: SelectionState,
removalDirection: string): ContentState,
splitBlock(contentState: ContentState,
selectionState: SelectionState): ContentState,
applyInlineStyle(contentState: ContentState,
selectionState: SelectionState,
inlineStyle: string): ContentState,
removeInlineStyle(contentState: ContentState,
selectionState: SelectionState,
inlineStyle: string): ContentState,
setBlockType(contentState: ContentState,
selectionState: SelectionState,
blockType: string): ContentState,
applyEntity(contentState: ContentState,
selectionState: SelectionState,
entityKey: string): ContentState
}
interface RichUtils {
currentBlockContainsLink(editorState: EditorState): boolean,
getCurrentBlockType(editor: EditorState): string,
handleKeyCommand(editorState: EditorState, command: string): any,
insertSoftNewline(editorState: EditorState): EditorState,
onBackspace(editorState: EditorState): EditorState,
onDelete(editorState: EditorState): EditorState,
onTab(event: Event, editorState: EditorState, maxDepth: number): EditorState,
toggleBlockType(editorState: EditorState, blockType: string): EditorState,
toggleCode(editorState: EditorState): EditorState,
toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState,
tryToRemoveBlockStyle(editorState: EditorState): EditorState
}
interface EditorProps {
editorState: EditorState,
onChange(editorState: EditorState): void,
placeholder?: string,
textAlignment?: any,
blockRendererFn?: (ContentBlock: ContentBlock) => any,
blockStyleFn?: (ContentBlock: ContentBlock) => string,
customStyleMap?: any,
readOnly?: boolean,
spellCheck?: boolean,
stripPastedStyles?: boolean,
handleReturn?: (e: any) => boolean,
handleKeyCommand?: (command: string) => boolean,
handleBeforeInput?: (chars: string) => boolean,
handlePastedFiles?: (files: Array<Blob>) => boolean,
handleDroppedFiles?: (selection: SelectionState, files: Array<Blob>) => boolean,
handleDrop?: (selection: SelectionState, dataTransfer: any, isInternal: any) => boolean,
onEscape?: (e: any) => void,
onTab?: (e: any) => void,
onUpArrow?: (e: any) => void,
onDownArrow?: (e: any) => void,
suppressContentEditableWarning?: any,
onBlur?: (e: any) => void,
onFocus?: (e: any) => void
}
interface Editor {
props: EditorProps
state: any,
refs: any,
context: any,
setState(): any,
render(): any,
forceUpdate(): any
}
var Editor: IEditor;
var EditorState: EditorState;
var CompositeDecorator: CompositeDecorator;
var Entity: Entity;
var EntityInstance: EntityInstance;
var BlockMapBuilder: BlockMapBuilder;
var CharacterMetadata: CharacterMetadata;
var ContentBlock: IContentBlock;
var ContentState: ContentState;
var SelectionState: ISelectionState;
var Modifier: Modifier;
var RichUtils: RichUtils;
function convertFromRaw(rawState: any): Array<ContentBlock>;
function convertToRaw(contentState: ContentState): any;
function genKey(): string
}
export = Draft;
}

View File

@ -0,0 +1,183 @@
/// <reference path="draft-js-0.2.2.d.ts" />
/// <reference path="../react/react-global.d.ts" />
/// <reference path="../react/react-dom.d.ts"/>
import * as React from "react";
import {
Editor,
EditorState,
Entity,
CharacterMetadata,
ContentBlock,
Modifier,
SelectionState,
genKey
} from "draft-js";
export class Tag extends React.Component<any, any> {
constructor(props: any) {
super(props);
}
remove = (): void => {
this.props.blockProps.removeBlock(this.props.block.getKey());
}
render () {
const {block} = this.props;
if (block.getEntityAt(0)) {
const data = Entity.get(block.getEntityAt(0)).getData();
return (
<div className="tag" contentEditable={false} >
{data.content.name}
<span className="remove" onClick={this.remove}>
<i className="material-icons">clear</i>
</span>
</div>
);
}
}
}
export class Hint extends React.Component<any, any> {
constructor(props: any) {
super(props);
}
render () {
const {block} = this.props;
if (block.getEntityAt(0)) {
const data = Entity.get(block.getEntityAt(0)).getData();
return (
<div className="hint" contentEditable={false} >
<span className="autocomplete">{this.props.blockProps.autocomplete}</span>
{data.content.text}
</div>
);
}
}
}
export function removeBlock(editorState: EditorState, blockKey: string) {
const content = editorState.getCurrentContent();
const targetRange = new SelectionState({
anchorKey: blockKey,
anchorOffset: 0,
focusKey: blockKey,
focusOffset: 1
});
const withoutTag = Modifier.removeRange(content, targetRange, "backward");
const resetBlock = Modifier.setBlockType(
withoutTag,
withoutTag.getSelectionAfter(),
"unstyled"
);
const newState = EditorState.push(editorState, resetBlock, "remove-range");
return EditorState.forceSelection(newState, resetBlock.getSelectionAfter());
}
export function applyEntity(editorState: EditorState, blockKey: string, entityKey: string) {
const content = editorState.getCurrentContent();
const targetRange = new SelectionState({
anchorKey: blockKey,
anchorOffset: 0,
focusKey: blockKey,
focusOffset: 1
});
const withNewEntity = Modifier.applyEntity(
content,
targetRange,
entityKey
)
const newState = EditorState.push(editorState, withNewEntity, "change-entity");
return EditorState.forceSelection(newState, withNewEntity.getSelectionAfter());
}
export function addTagBlock(content: any, editorState: EditorState): any {
const contentState = editorState.getCurrentContent();
const entityKey = Entity.create(
"TOKEN",
"IMMUTABLE",
{content}
);
const charData = CharacterMetadata.create({entity: entityKey});
const tag = new ContentBlock({
key: genKey(),
type: "tag",
text: "",
characterList: [],
});
const withTag = contentState.set("blockMap", contentState.getBlockMap().set(tag.key, tag));
const withRemovedPreviousBlock = withTag.set("blockMap", withTag.getBlockMap().delete(contentState.getSelectionBefore().getAnchorKey()))
const withTagBlock = EditorState.push(editorState, withRemovedPreviousBlock, "insert-fragment");
return withTagBlock;
}
export function addHintBlock(content: any, editorState: EditorState): any {
const contentState = editorState.getCurrentContent();
const selectionState = editorState.getSelection();
const entityKey = Entity.create(
"TOKEN",
"IMMUTABLE",
{content}
);
const charData = CharacterMetadata.create({entity: entityKey});
const hint = new ContentBlock({
key: genKey(),
type: "hint",
text: "",
characterList: [],
});
const empty = new ContentBlock({
key: genKey(),
type: "unstyled",
text: "",
characterList: [],
});
const withEmpty = contentState.set("blockMap", contentState.getBlockMap().set(empty.key, empty));
const withHint = withEmpty.set("blockMap", withEmpty.getBlockMap().set(hint.key, hint));
return {
editorState: EditorState.forceSelection(EditorState.push(editorState, withHint, "insert-fragment"), selectionState),
blockKey: hint.key
}
}
export class SearchField extends React.Component<any, any> {
public onChange: any;
constructor(props: any) {
super(props);
this.onChange = (editorState: EditorState) => {
this.setState({editorState})
};
}
render() {
const {editorState} = this.state;
return (
<Editor suppressContentEditableWarning
editorState={editorState}
onChange={this.onChange}
/>
)
}
}

View File

@ -1,182 +1,178 @@
/// <reference types="react" />
/// <reference types="react-dom"/>
import * as React from "react";
import * as ReactDOM from "react-dom";
import {Map} from "immutable";
import {
Editor,
EditorState,
Entity,
CharacterMetadata,
ContentBlock,
Modifier,
SelectionState,
genKey
} from "draft-js";
import {Editor, EditorState, RichUtils, DefaultDraftBlockRenderMap, ContentBlock} from 'draft-js';
export class Tag extends React.Component<any, any> {
constructor(props: any) {
super(props);
class RichEditorExample extends React.Component<{}, { editorState: EditorState }> {
constructor() {
super();
this.state = { editorState: EditorState.createEmpty() };
}
remove = (): void => {
this.props.blockProps.removeBlock(this.props.block.getKey());
onChange: (editorState: EditorState) => void = (editorState: EditorState) => this.setState({ editorState });
handleKeyCommand: (command: string) => boolean = (command: string) => {
const {editorState} = this.state;
const newState = RichUtils.handleKeyCommand(editorState, command);
if (newState) {
this.onChange(newState);
return true;
}
return false;
}
render () {
const {block} = this.props;
if (block.getEntityAt(0)) {
const data = Entity.get(block.getEntityAt(0)).getData();
toggleBlockType: (blockType: string) => void = (blockType: string) => {
this.onChange(RichUtils.toggleBlockType(this.state.editorState, blockType));
}
toggleInlineStyle: (inlineStyle: string) => void = (inlineStyle: string) => {
this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, inlineStyle));
}
render(): React.ReactElement<{}> {
// If the user changes block type before entering any text, we can
// either style the placeholder or hide it. Let's just hide it now.
let className = 'RichEditor-editor';
var contentState = this.state.editorState.getCurrentContent();
if (!contentState.hasText()) {
if (contentState.getBlockMap().first().getType() !== 'unstyled') {
className += ' RichEditor-hidePlaceholder';
}
}
return (
<div className="tag" contentEditable={false} >
{data.content.name}
<span className="remove" onClick={this.remove}>
<i className="material-icons">clear</i>
</span>
<div className="RichEditor-root">
<BlockStyleControls
editorState={this.state.editorState}
onToggle={this.toggleBlockType}
/>
<InlineStyleControls
editorState={this.state.editorState}
onToggle={this.toggleInlineStyle}
/>
<div className={className}>
<Editor
blockStyleFn={getBlockStyle}
customStyleMap={styleMap}
editorState={this.state.editorState}
handleKeyCommand={this.handleKeyCommand}
onChange={this.onChange}
placeholder="Tell a story..."
ref="editor"
spellCheck={true}
/>
</div>
</div>
);
}
}
}
export class Hint extends React.Component<any, any> {
constructor(props: any) {
super(props);
}
// Custom overrides for "code" style.
const styleMap = {
CODE: {
backgroundColor: 'rgba(0, 0, 0, 0.05)',
fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace',
fontSize: 16,
padding: 2,
},
};
render () {
const {block} = this.props;
if (block.getEntityAt(0)) {
const data = Entity.get(block.getEntityAt(0)).getData();
return (
<div className="hint" contentEditable={false} >
<span className="autocomplete">{this.props.blockProps.autocomplete}</span>
{data.content.text}
</div>
);
}
}
function getBlockStyle(block: ContentBlock) {
switch (block.getType()) {
case 'blockquote': return 'RichEditor-blockquote';
default: return null;
}
}
export function removeBlock(editorState: EditorState, blockKey: string) {
const content = editorState.getCurrentContent();
class StyleButton extends React.Component<{key: string, active: boolean, label: string, onToggle: (blockType: string) => void, style: string}, {}> {
constructor() {
super();
}
const targetRange = new SelectionState({
anchorKey: blockKey,
anchorOffset: 0,
focusKey: blockKey,
focusOffset: 1
});
onToggle: (event: Event) => void = (event: Event) => {
event.preventDefault();
this.props.onToggle(this.props.style);
};
const withoutTag = Modifier.removeRange(content, targetRange, "backward");
const resetBlock = Modifier.setBlockType(
withoutTag,
withoutTag.getSelectionAfter(),
"unstyled"
render(): React.ReactElement<{}> {
let className = 'RichEditor-styleButton';
if (this.props.active) {
className += ' RichEditor-activeButton';
}
return (
<span className={className} onMouseDown={this.onToggle}>
{this.props.label}
</span>
);
const newState = EditorState.push(editorState, resetBlock, "remove-range");
return EditorState.forceSelection(newState, resetBlock.getSelectionAfter());
}
}
export function applyEntity(editorState: EditorState, blockKey: string, entityKey: string) {
const content = editorState.getCurrentContent();
const BLOCK_TYPES = [
{ label: 'H1', style: 'header-one' },
{ label: 'H2', style: 'header-two' },
{ label: 'H3', style: 'header-three' },
{ label: 'H4', style: 'header-four' },
{ label: 'H5', style: 'header-five' },
{ label: 'H6', style: 'header-six' },
{ label: 'Blockquote', style: 'blockquote' },
{ label: 'UL', style: 'unordered-list-item' },
{ label: 'OL', style: 'ordered-list-item' },
{ label: 'Code Block', style: 'code-block' },
];
const targetRange = new SelectionState({
anchorKey: blockKey,
anchorOffset: 0,
focusKey: blockKey,
focusOffset: 1
});
const BlockStyleControls = (props: {editorState: EditorState, onToggle: (blockType: string) => void}) => {
const {editorState} = props;
const selection = editorState.getSelection();
const blockType = editorState
.getCurrentContent()
.getBlockForKey(selection.getStartKey())
.getType();
const withNewEntity = Modifier.applyEntity(
content,
targetRange,
entityKey
)
const newState = EditorState.push(editorState, withNewEntity, "change-entity");
return EditorState.forceSelection(newState, withNewEntity.getSelectionAfter());
}
export function addTagBlock(content: any, editorState: EditorState): any {
const contentState = editorState.getCurrentContent();
const entityKey = Entity.create(
"TOKEN",
"IMMUTABLE",
{content}
return (
<div className="RichEditor-controls">
{BLOCK_TYPES.map((type) =>
<StyleButton
key={type.label}
active={type.style === blockType}
label={type.label}
onToggle={props.onToggle}
style={type.style}
/>
) }
</div>
);
};
const charData = CharacterMetadata.create({entity: entityKey});
const tag = new ContentBlock({
key: genKey(),
type: "tag",
text: "",
characterList: [],
});
var INLINE_STYLES = [
{ label: 'Bold', style: 'BOLD' },
{ label: 'Italic', style: 'ITALIC' },
{ label: 'Underline', style: 'UNDERLINE' },
{ label: 'Monospace', style: 'CODE' },
];
const withTag = contentState.set("blockMap", contentState.getBlockMap().set(tag.key, tag));
const withRemovedPreviousBlock = withTag.set("blockMap", withTag.getBlockMap().delete(contentState.getSelectionBefore().getAnchorKey()))
const withTagBlock = EditorState.push(editorState, withRemovedPreviousBlock, "insert-fragment");
return withTagBlock;
}
export function addHintBlock(content: any, editorState: EditorState): any {
const contentState = editorState.getCurrentContent();
const selectionState = editorState.getSelection();
const entityKey = Entity.create(
"TOKEN",
"IMMUTABLE",
{content}
);
const charData = CharacterMetadata.create({entity: entityKey});
const hint = new ContentBlock({
key: genKey(),
type: "hint",
text: "",
characterList: [],
});
const empty = new ContentBlock({
key: genKey(),
type: "unstyled",
text: "",
characterList: [],
});
const withEmpty = contentState.set("blockMap", contentState.getBlockMap().set(empty.key, empty));
const withHint = withEmpty.set("blockMap", withEmpty.getBlockMap().set(hint.key, hint));
return {
editorState: EditorState.forceSelection(EditorState.push(editorState, withHint, "insert-fragment"), selectionState),
blockKey: hint.key
}
}
export class SearchField extends React.Component<any, any> {
public onChange: any;
constructor(props: any) {
super(props);
this.onChange = (editorState: EditorState) => {
this.setState({editorState})
};
}
render() {
const {editorState} = this.state;
const InlineStyleControls = (props: {editorState: EditorState, onToggle: (blockType: string) => void}) => {
var currentStyle = props.editorState.getCurrentInlineStyle();
return (
<Editor suppressContentEditableWarning
editorState={editorState}
onChange={this.onChange}
<div className="RichEditor-controls">
{INLINE_STYLES.map(type =>
<StyleButton
key={type.label}
active={currentStyle.has(type.style) }
label={type.label}
onToggle={props.onToggle}
style={type.style}
/>
)
}
}
) }
</div>
);
};
ReactDOM.render(
<RichEditorExample />,
document.getElementById('target')
);

1190
draft-js/index.d.ts vendored

File diff suppressed because it is too large Load Diff

1
durandal/index.d.ts vendored
View File

@ -693,6 +693,7 @@ declare module 'plugins/dialog' {
}
interface Dialog {
host: HTMLElement;
owner: any;
context: DialogContext;
activator: DurandalActivator<any>;

View File

@ -38,6 +38,8 @@ declare module Elasticsearch {
create(params: IndicesCreateParams): PromiseLike<any>;
exists(params: IndicesIndexExitsParams, callback: (error: any, response: any, status: any) => void): void;
exists(params: IndicesIndexExitsParams): PromiseLike<any>;
existsType(params: IndicesIndexExitsParams & {type: string}, callback: (error: any, response: any, status: any) => void): void;
existsType(params: IndicesIndexExitsParams & {type: string}): PromiseLike<any>;
get(params: IndicesGetParams, callback: (error: any, response: any, status: any) => void): void;
get(params: IndicesGetParams): PromiseLike<any>;
getAlias(params: IndicesGetAliasParams, callback: (error: any, response: any, status: any) => void): void;
@ -46,6 +48,8 @@ declare module Elasticsearch {
putAlias(params: IndicesPutAliasParams): PromiseLike<any>;
putTemplate(params: IndicesPutTemplateParams, callback: (error: any, response: any) => void): void;
putTemplate(params: IndicesPutTemplateParams): PromiseLike<any>;
putMapping(params: IndicesPutMappingParams, callback: (error: any, response: any) => void): void;
putMapping(params: IndicesPutMappingParams): PromiseLike<any>;
refresh(params: IndicesRefreshParams, callback: (error: any, response: any) => void): void;
refresh(params: IndicesRefreshParams): PromiseLike<any>;
}
@ -125,10 +129,21 @@ declare module Elasticsearch {
body: string | any;
}
export interface IndicesPutMappingParams extends GenericParams {
timeout?: Date | number;
masterTimeout?: Date | number;
ignoreUnavailable?: boolean;
allowNoIndices?: boolean;
expandWildcards?: "open" | "closed" | "none" | "all";
updateAllTypes?: boolean;
index: string | string[] | boolean;
type: string;
}
export interface IndicesGetAliasParams extends GenericParams {
ignoreUnavailable?: boolean;
allowNoIndices?: boolean;
expandWildcards?: string;
expandWildcards?: "open" | "closed" | "none" | "all";
local?: boolean;
index?: string | string[] | boolean;
name: string | string[] | boolean;
@ -260,7 +275,7 @@ declare module Elasticsearch {
export interface SuggestParams extends GenericParams {
ignoreUnavailable?: boolean;
allowNoIndices?: boolean;
expandWildcards?: string;
expandWildcards?: "open" | "closed" | "none" | "all";
preference?: string;
routing?: string;
source?: string;

View File

@ -96,6 +96,7 @@ app.on('ready', () => {
mainWindow.webContents.executeJavaScript('return true;', true);
mainWindow.webContents.executeJavaScript('return true;', true, (result: boolean) => console.log(result));
mainWindow.webContents.insertText('blah, blah, blah');
mainWindow.webContents.startDrag({file: '/path/to/img.png', icon: nativeImage.createFromPath('/path/to/icon.png')});
mainWindow.webContents.findInPage('blah');
mainWindow.webContents.findInPage('blah', {
forward: true,
@ -133,6 +134,12 @@ app.on('ready', () => {
});
mainWindow.webContents.debugger.sendCommand("Network.enable");
mainWindow.webContents.capturePage(image => {
console.log(image.toDataURL());
});
mainWindow.webContents.capturePage({width: 100, height: 200}, image => {
console.log(image.toPNG());
});
});
app.commandLine.appendSwitch('enable-web-bluetooth');
@ -220,6 +227,7 @@ app.dock.setBadge('foo');
var id = app.dock.bounce('informational');
app.dock.cancelBounce(id);
app.dock.setIcon('/path/to/icon.png');
app.dock.setBadgeCount(app.dock.getBadgeCount() + 1);
app.setUserTasks([
<Electron.Task>{
@ -232,6 +240,12 @@ app.setUserTasks([
}
]);
app.setUserTasks([]);
if (app.isUnityRunning()) {
}
if (app.isAccessibilitySupportEnabled()) {
}
app.setLoginItemSettings({openAtLogin: true, openAsHidden: false});
console.log(app.getLoginItemSettings().wasOpenedAtLogin);
var window = new BrowserWindow();
window.setProgressBar(0.5);
@ -247,6 +261,7 @@ app.on('ready', () => {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`);
});
app.on('accessibility-support-changed', (_, enabled) => console.log('accessibility: ' + enabled));
ipcMain.on('online-status-changed', (event: any, status: any) => {
console.log(status);
@ -429,6 +444,14 @@ ipcMain.on('synchronous-message', (event: Electron.IpcMainEvent, arg: any) => {
event.returnValue = 'pong';
});
var winWindows = new BrowserWindow({
width: 800,
height: 600,
show: false,
thickFrame: false,
type: 'toolbar',
});
// menu-item
// https://github.com/atom/electron/blob/master/docs/api/menu-item.md
@ -700,8 +723,11 @@ app.on('ready', () => {
clipboard.writeText('Example String');
clipboard.writeText('Example String', 'selection');
clipboard.writeBookmark('foo', 'http://example.com');
clipboard.writeBookmark('foo', 'http://example.com', 'selection');
console.log(clipboard.readText('selection'));
console.log(clipboard.availableFormats());
console.log(clipboard.readBookmark().title);
clipboard.clear();
clipboard.write({

View File

@ -250,6 +250,7 @@ webview.addEventListener('ipc-message', function(event) {
console.log(event.channel); // Prints "pong"
});
webview.send('ping');
webview.capturePage((image) => { console.log(image); });
// In guest page.
ipcRenderer.on('ping', function() {

205
electron/index.d.ts vendored
View File

@ -1,4 +1,4 @@
// Type definitions for Electron v1.2.5
// Type definitions for Electron v1.2.7
// 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
@ -160,6 +160,12 @@ declare namespace Electron {
* Emitted when the gpu process crashes.
*/
on(event: 'gpu-process-crashed', listener: Function): this;
/**
* Emitted when Chrome's accessibility support changes.
*
* Note: This API is only available on macOS and Windows.
*/
on(event: 'accessibility-support-changed', listener: (event: Event, accessibilitySupportEnabled: boolean) => void): this;
on(event: string, listener: Function): this;
/**
* Try to close all windows. The before-quit event will first be emitted.
@ -341,6 +347,33 @@ declare namespace Electron {
* This method can only be called before app is ready.
*/
disableHardwareAcceleration(): void;
/**
* @returns whether current desktop environment is Unity launcher. (Linux)
*
* Note: This API is only available on Linux.
*/
isUnityRunning(): boolean;
/**
* Returns a Boolean, true if Chrome's accessibility support is enabled, false otherwise.
* This API will return true if the use of assistive technologies, such as screen readers,
* has been detected.
* See https://www.chromium.org/developers/design-documents/accessibility for more details.
*
* Note: This API is only available on macOS and Windows.
*/
isAccessibilitySupportEnabled(): boolean;
/**
* @returns an Object with the login item settings of the app.
*
* Note: This API is only available on macOS and Windows.
*/
getLoginItemSettings(): LoginItemSettings;
/**
* Set the app's login item settings.
*
* Note: This API is only available on macOS and Windows.
*/
setLoginItemSettings(settings: LoginItemSettings): void;
commandLine: CommandLine;
/**
* Note: This API is only available on macOS.
@ -414,6 +447,20 @@ declare namespace Electron {
* Note: This API is only available on macOS.
*/
getBadge(): string;
/**
* Sets the counter badge for current app. Setting the count to 0 will hide the badge.
*
* @returns True when the call succeeded, otherwise returns false.
*
* Note: This API is only available on macOS and Linux.
*/
setBadgeCount(count: number): boolean;
/**
* @returns The current value displayed in the counter badge.
*
* Note: This API is only available on macOS and Linux.
*/
getBadgeCount(): number;
/**
* Hides the dock icon.
*
@ -472,6 +519,32 @@ declare namespace Electron {
iconIndex?: number;
}
interface LoginItemSettings {
/**
* True if the app is set to open at login.
*/
openAtLogin: boolean;
/**
* True if the app is set to open as hidden at login. This setting is only supported on macOS.
*/
openAsHidden: boolean;
/**
* True if the app was opened at login automatically. This setting is only supported on macOS.
*/
wasOpenedAtLogin?: boolean;
/**
* True if the app was opened as a hidden login item. This indicates that the app should not
* open any windows at startup. This setting is only supported on macOS.
*/
wasOpenedAsHidden?: boolean;
/**
* True if the app was opened as a login item that should restore the state from the previous session.
* This indicates that the app should restore the windows that were open the last time the app was closed.
* This setting is only supported on macOS.
*/
restoreState?: boolean;
}
// https://github.com/electron/electron/blob/master/docs/api/auto-updater.md
/**
@ -968,6 +1041,13 @@ declare namespace Electron {
* @param callback Supplies the image that stores data of the snapshot.
*/
capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void;
/**
* Captures the snapshot of page within rect, upon completion the callback
* will be called. Omitting the rect would capture the whole visible page.
* Note: Be sure to read documents on remote buffer in remote if you are going
* to use this API in renderer process.
* @param callback Supplies the image that stores data of the snapshot.
*/
capturePage(callback: (image: NativeImage) => void): void;
/**
* Same as webContents.loadURL(url).
@ -1458,15 +1538,20 @@ declare namespace Electron {
* The style of window title bar.
*/
titleBarStyle?: 'default' | 'hidden' | 'hidden-inset';
/**
* Use WS_THICKFRAME style for frameless windows on Windows
*/
thickFrame?: boolean;
/**
* Settings of web pages features.
*/
webPreferences?: WebPreferences;
}
type BrowserWindowType = BrowserWindowTypeLinux | BrowserWindowTypeMac;
type BrowserWindowType = BrowserWindowTypeLinux | BrowserWindowTypeMac | BrowserWindowTypeWindows;
type BrowserWindowTypeLinux = 'desktop' | 'dock' | 'toolbar' | 'splash' | 'notification';
type BrowserWindowTypeMac = 'desktop' | 'textured';
type BrowserWindowTypeWindows = 'toolbar';
interface Rectangle {
x?: number;
@ -1541,10 +1626,27 @@ declare namespace Electron {
html?: string;
image?: NativeImage;
}, type?: ClipboardType): void;
/**
* @returns An Object containing title and url keys representing the bookmark in the clipboard.
*
* Note: This API is available on macOS and Windows.
*/
readBookmark(): Bookmark;
/**
* Writes the title and url into the clipboard as a bookmark.
*
* Note: This API is available on macOS and Windows.
*/
writeBookmark(title: string, url: string, type?: ClipboardType): void;
}
type ClipboardType = '' | 'selection';
interface Bookmark {
title: string;
url: string;
}
// https://github.com/electron/electron/blob/master/docs/api/content-tracing.md
/**
@ -1836,7 +1938,7 @@ declare namespace Electron {
/**
* Contains which features the dialog should use.
*/
properties?: ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory')[];
properties?: ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory' | 'showHiddenFiles')[];
}
interface SaveDialogOptions {
@ -3292,6 +3394,17 @@ declare namespace Electron {
metaKey: boolean;
}
interface DragItem {
/**
* The absolute path of the file to be dragged
*/
file: string;
/**
* The image showing under the cursor when dragging.
*/
icon: NativeImage;
}
// https://github.com/electron/electron/blob/master/docs/api/web-contents.md
/**
@ -3739,16 +3852,12 @@ declare namespace Electron {
* Begin subscribing for presentation events and captured frames,
* The callback will be called when there is a presentation event.
*/
beginFrameSubscription(callback: (
beginFrameSubscription(onlyDirty: boolean, callback: BeginFrameSubscriptionCallback): void;
/**
* The frameBuffer is a Buffer that contains raw pixel data.
* On most machines, the pixel data is effectively stored in 32bit BGRA format,
* but the actual representation depends on the endianness of the processor
* (most modern processors are little-endian, on machines with big-endian
* processors the data is in 32bit ARGB format).
* Begin subscribing for presentation events and captured frames,
* The callback will be called when there is a presentation event.
*/
frameBuffer: Buffer
) => void): void;
beginFrameSubscription(callback: BeginFrameSubscriptionCallback): void;
/**
* End subscribing for frame presentation events.
*/
@ -3762,6 +3871,18 @@ declare namespace Electron {
* Note: This API is available only on macOS.
*/
showDefinitionForSelection(): void;
/**
* Sets the item as dragging item for current drag-drop operation.
*/
startDrag(item: DragItem): void;
/**
* Captures a snapshot of the page within rect.
*/
capturePage(callback: (image: NativeImage) => void): void;
/**
* Captures a snapshot of the page within rect.
*/
capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void;
/**
* @returns The unique ID of this WebContents.
*/
@ -3786,6 +3907,24 @@ declare namespace Electron {
debugger: Debugger;
}
interface BeginFrameSubscriptionCallback {
(
/**
* The frameBuffer is a Buffer that contains raw pixel data.
* On most machines, the pixel data is effectively stored in 32bit BGRA format,
* but the actual representation depends on the endianness of the processor
* (most modern processors are little-endian, on machines with big-endian
* processors the data is in 32bit ARGB format).
*/
frameBuffer: Buffer,
/**
* The dirtyRect is an object with x, y, width, height properties that describes which part of the page was repainted.
* If onlyDirty is set to true, frameBuffer will only contain the repainted area. onlyDirty defaults to false.
*/
dirtyRect?: Bounds
): void
}
interface ContextMenuParams {
/**
* x coordinate
@ -3825,76 +3964,76 @@ declare namespace Electron {
*/
mediaFlags: {
/**
* Wether the media element has crashed.
* Whether the media element has crashed.
*/
inError: boolean;
/**
* Wether the media element is paused.
* Whether the media element is paused.
*/
isPaused: boolean;
/**
* Wether the media element is muted.
* Whether the media element is muted.
*/
isMuted: boolean;
/**
* Wether the media element has audio.
* Whether the media element has audio.
*/
hasAudio: boolean;
/**
* Wether the media element is looping.
* Whether the media element is looping.
*/
isLooping: boolean;
/**
* Wether the media element's controls are visible.
* Whether the media element's controls are visible.
*/
isControlsVisible: boolean;
/**
* Wether the media element's controls are toggleable.
* Whether the media element's controls are toggleable.
*/
canToggleControls: boolean;
/**
* Wether the media element can be rotated.
* Whether the media element can be rotated.
*/
canRotate: boolean;
}
/**
* Wether the context menu was invoked on an image which has non-empty contents.
* Whether the context menu was invoked on an image which has non-empty contents.
*/
hasImageContents: boolean;
/**
* Wether the context is editable.
* Whether the context is editable.
*/
isEditable: boolean;
/**
* These flags indicate wether the renderer believes it is able to perform the corresponding action.
* These flags indicate whether the renderer believes it is able to perform the corresponding action.
*/
editFlags: {
/**
* Wether the renderer believes it can undo.
* Whether the renderer believes it can undo.
*/
canUndo: boolean;
/**
* Wether the renderer believes it can redo.
* Whether the renderer believes it can redo.
*/
canRedo: boolean;
/**
* Wether the renderer believes it can cut.
* Whether the renderer believes it can cut.
*/
canCut: boolean;
/**
* Wether the renderer believes it can copy
* Whether the renderer believes it can copy
*/
canCopy: boolean;
/**
* Wether the renderer believes it can paste.
* Whether the renderer believes it can paste.
*/
canPaste: boolean;
/**
* Wether the renderer believes it can delete.
* Whether the renderer believes it can delete.
*/
canDelete: boolean;
/**
* Wether the renderer believes it can select all.
* Whether the renderer believes it can select all.
*/
canSelectAll: boolean;
}
@ -4556,6 +4695,14 @@ declare namespace Electron {
* @returns The WebContents associated with this webview.
*/
getWebContents(): WebContents;
/**
* Captures a snapshot of the webview's page. Same as webContents.capturePage([rect, ]callback).
*/
capturePage(callback: (image: NativeImage) => void): void;
/**
* Captures a snapshot of the webview's page. Same as webContents.capturePage([rect, ]callback).
*/
capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void;
/**
* Fired when a load has committed. This includes navigation within the current document
* as well as subframe document-level loads, but does not include asynchronous resource loads.

View File

@ -1,12 +1,9 @@
/// <reference types="react"/>
/*
import { shallow, mount, render, describeWithDOM, spyLifecycle } from "enzyme";
import * as React from "react";
import {Component, ReactElement, HTMLAttributes} from "react";
import {ShallowWrapper, ReactWrapper, CheerioWrapper} from "enzyme";
// Help classes/interfaces
interface MyComponentProps {
propsProperty: any;
@ -42,13 +39,23 @@ namespace ShallowWrapperTest {
objectVal: Object,
boolVal: Boolean,
stringVal: String,
elementWrapper: ShallowWrapper<HTMLAttributes<any>, {}>
elementWrapper: ShallowWrapper<HTMLAttributes, {}>
function test_shallow_options() {
shallow(<MyComponent propsProperty={1}/>, {
context: {
test: "a",
},
lifecycleExperimental: true
});
}
function test_find() {
elementWrapper = shallowWrapper.find('.selector');
shallowWrapper = shallowWrapper.find(MyComponent);
shallowWrapper.find(MyStatelessComponent).props().stateless;
shallowWrapper.find(MyStatelessComponent).shallow();
shallowWrapper.find({ prop: 'value' });
}
function test_findWhere() {
@ -59,6 +66,7 @@ namespace ShallowWrapperTest {
function test_filter() {
elementWrapper = shallowWrapper.filter('.selector');
shallowWrapper = shallowWrapper.filter(MyComponent).shallow();
shallowWrapper.filter({ prop: 'val' });
}
function test_filterWhere() {
@ -108,6 +116,7 @@ namespace ShallowWrapperTest {
function test_children() {
shallowWrapper = shallowWrapper.children();
shallowWrapper.children(MyStatelessComponent).props().stateless;
shallowWrapper.children({ prop: 'myprop' });
}
function test_childAt() {
@ -135,6 +144,7 @@ namespace ShallowWrapperTest {
function test_closest() {
elementWrapper = shallowWrapper.closest('.selector');
shallowWrapper = shallowWrapper.closest(MyComponent);
shallowWrapper = shallowWrapper.closest({ prop: 'myprop' });
}
function test_shallow() {
@ -277,6 +287,10 @@ namespace ShallowWrapperTest {
function test_everyWhere() {
boolVal = shallowWrapper.everyWhere((aShallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState>) => true);
}
function test_isEmptyRender() {
boolVal = shallowWrapper.isEmptyRender();
}
}
@ -289,7 +303,7 @@ namespace ReactWrapperTest {
objectVal: Object,
boolVal: Boolean,
stringVal: String,
elementWrapper: ReactWrapper<HTMLAttributes<any>, {}>
elementWrapper: ReactWrapper<HTMLAttributes, {}>
function test_unmount() {
reactWrapper = reactWrapper.unmount();
@ -297,30 +311,38 @@ namespace ReactWrapperTest {
function test_mount() {
reactWrapper = reactWrapper.mount();
mount(<MyComponent propsProperty={1}/>, {
attachTo: document.getElementById('test'),
context: {
a: "b"
}
});
}
function test_ref() {
reactWrapper = reactWrapper.ref('refName');
interface TmpType1 {
foo: string
}
interface TmpType2 {
bar: string
}
const tmp: ReactWrapper<TmpType1, TmpType2> = reactWrapper.ref<TmpType1, TmpType2>('refName');
}
function test_detach() {
reactWrapper.detach();
}
function test_find() {
elementWrapper = reactWrapper.find('.selector');
reactWrapper = reactWrapper.find(MyComponent);
reactWrapper.find(MyStatelessComponent).props().stateless;
reactWrapper.find({ prop: 'myprop' });
}
function test_findWhere() {
@ -331,6 +353,7 @@ namespace ReactWrapperTest {
function test_filter() {
elementWrapper = reactWrapper.filter('.selector');
reactWrapper = reactWrapper.filter(MyComponent);
reactWrapper = reactWrapper.filter({ prop: 'myprop' });
}
function test_filterWhere() {
@ -406,6 +429,7 @@ namespace ReactWrapperTest {
function test_closest() {
elementWrapper = reactWrapper.closest('.selector');
reactWrapper = reactWrapper.closest(MyComponent);
reactWrapper = reactWrapper.closest({ prop: 'myprop' });
}
function test_text() {
@ -535,6 +559,9 @@ namespace ReactWrapperTest {
function test_everyWhere() {
boolVal = reactWrapper.everyWhere((aReactWrapper: ReactWrapper<MyComponentProps, MyComponentState>) => true);
}
function test_isEmptyRender() {
boolVal = reactWrapper.isEmptyRender();
}
}
// CheerioWrapper
@ -546,12 +573,13 @@ namespace CheerioWrapperTest {
objectVal: Object,
boolVal: Boolean,
stringVal: String,
elementWrapper: CheerioWrapper<HTMLAttributes<{}>, {}>;
elementWrapper: CheerioWrapper<HTMLAttributes, {}>
function test_find() {
elementWrapper = cheerioWrapper.find('.selector');
cheerioWrapper = cheerioWrapper.find(MyComponent);
cheerioWrapper.find(MyStatelessComponent).props().stateless;
cheerioWrapper.find({ prop: 'myprop' });
}
function test_findWhere() {
@ -562,6 +590,7 @@ namespace CheerioWrapperTest {
function test_filter() {
elementWrapper = cheerioWrapper.filter('.selector');
cheerioWrapper = cheerioWrapper.filter(MyComponent);
cheerioWrapper = cheerioWrapper.filter({ prop: 'myprop' });
}
function test_filterWhere() {
@ -637,6 +666,7 @@ namespace CheerioWrapperTest {
function test_closest() {
elementWrapper = cheerioWrapper.closest('.selector');
cheerioWrapper = cheerioWrapper.closest(MyComponent);
cheerioWrapper = cheerioWrapper.closest({ prop: 'myprop' });
}
function test_text() {
@ -767,4 +797,4 @@ namespace CheerioWrapperTest {
function test_everyWhere() {
boolVal = cheerioWrapper.everyWhere((aCheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState>) => true);
}
}
}*/

388
enzyme/index.d.ts vendored
View File

@ -1,15 +1,11 @@
// Type definitions for Enzyme v2.3.0
// Type definitions for Enzyme v2.4.1
// Project: https://github.com/airbnb/enzyme
// Definitions by: Marian Palkus <https://github.com/MarianPalkus>, Cap3 <http://www.cap3.de>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
///<reference types="react" />
import { ReactElement, Component, StatelessComponent, ComponentClass, HTMLAttributes } from "react";
import {ReactElement, Component, StatelessComponent, ComponentClass, HTMLAttributes} from "react";
export declare class ElementClass extends Component<any, any> {
export class ElementClass extends Component<any, any> {
}
/**
@ -19,8 +15,11 @@ export declare class ElementClass extends Component<any, any> {
* 1. A Valid CSS Selector
* 2. A React Component Constructor
* 3. A React Component's displayName
* 4. A React Stateless component
* 5. A React component property map
*/
export type EnzymeSelector = String | typeof ElementClass;
export type EnzymeSelector = string | StatelessComponent<any> | ComponentClass<any> | { [key: string]: any };
export type EnzymePropSelector = { [key: string]: any };
interface CommonWrapper<P, S> {
/**
@ -29,13 +28,14 @@ interface CommonWrapper<P, S> {
*/
find<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
find<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
find(selector: string): CommonWrapper<HTMLAttributes<any>, any>;
find(props: EnzymePropSelector): CommonWrapper<any, any>;
find(selector: string): CommonWrapper<HTMLAttributes<{}>, any>;
/**
* Finds every node in the render tree that returns true for the provided predicate function.
* @param predicate
*/
findWhere(predicate: (wrapper: CommonWrapper<any, any>) => Boolean): CommonWrapper<any, any>;
findWhere(predicate: (wrapper: CommonWrapper<any, any>) => boolean): CommonWrapper<any, any>;
/**
* Removes nodes in the current wrapper that do not match the provided selector.
@ -43,59 +43,60 @@ interface CommonWrapper<P, S> {
*/
filter<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
filter<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
filter(selector: string): CommonWrapper<HTMLAttributes<any>, any>;
filter(props: EnzymePropSelector): CommonWrapper<any, any>;
filter(selector: string): CommonWrapper<HTMLAttributes<{}>, any>;
/**
* Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true.
* @param predicate
*/
filterWhere(predicate: (wrapper: this) => Boolean): this;
filterWhere(predicate: (wrapper: this) => boolean): this;
/**
* Returns whether or not the current wrapper has a node anywhere in it's render tree that looks like the one passed in.
* @param node
*/
contains(node: ReactElement<any>): Boolean;
contains(node: ReactElement<any>): boolean;
/**
* Returns whether or not a given react element exists in the shallow render tree.
* @param node
*/
containsMatchingElement(node: ReactElement<any>): Boolean;
* Returns whether or not a given react element exists in the shallow render tree.
* @param node
*/
containsMatchingElement(node: ReactElement<any>): boolean;
/**
* Returns whether or not all the given react elements exists in the shallow render tree
* @param nodes
*/
containsAllMatchingElements(nodes: ReactElement<any>[]): Boolean;
/**
* Returns whether or not all the given react elements exists in the shallow render tree
* @param nodes
*/
containsAllMatchingElements(nodes: ReactElement<any>[]): boolean;
/**
* Returns whether or not one of the given react elements exists in the shallow render tree.
* @param nodes
*/
containsAnyMatchingElements(nodes: ReactElement<any>[]): Boolean;
/**
* Returns whether or not one of the given react elements exists in the shallow render tree.
* @param nodes
*/
containsAnyMatchingElements(nodes: ReactElement<any>[]): boolean;
/**
* Returns whether or not the current render tree is equal to the given node, based on the expected value.
*/
equals(node: ReactElement<any>): Boolean;
/**
* Returns whether or not the current render tree is equal to the given node, based on the expected value.
*/
equals(node: ReactElement<any>): boolean;
/**
* Returns whether or not a given react element matches the shallow render tree.
*/
matchesElement(node: ReactElement<any>): Boolean;
/**
* Returns whether or not a given react element matches the shallow render tree.
*/
matchesElement(node: ReactElement<any>): boolean;
/**
/**
* Returns whether or not the current node has a className prop including the passed in class name.
* @param className
*/
hasClass(className: String): Boolean;
hasClass(className: string): boolean;
/**
* Returns whether or not the current node matches a provided selector.
* @param selector
*/
is(selector: EnzymeSelector): Boolean;
is(selector: EnzymeSelector): boolean;
/**
* Returns a new wrapper with only the nodes of the current wrapper that don't match the provided selector.
@ -111,17 +112,18 @@ interface CommonWrapper<P, S> {
*/
children<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
children(selector: string): CommonWrapper<HTMLAttributes<any>, any>;
children(props: EnzymePropSelector): CommonWrapper<any, any>;
children(selector: string): CommonWrapper<HTMLAttributes<{}>, any>;
children(): CommonWrapper<any, any>;
/**
* Returns a new wrapper with child at the specified index.
* @param index
*/
childAt(index: Number): CommonWrapper<any, any>;
childAt<P2, S2>(index: Number): CommonWrapper<P2, S2>;
* Returns a new wrapper with child at the specified index.
* @param index
*/
childAt(index: number): CommonWrapper<any, any>;
childAt<P2, S2>(index: number): CommonWrapper<P2, S2>;
/**
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the
* current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector.
*
@ -130,7 +132,8 @@ interface CommonWrapper<P, S> {
*/
parents<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
parents(selector: string): CommonWrapper<HTMLAttributes<any>, any>;
parents(props: EnzymePropSelector): CommonWrapper<any, any>;
parents(selector: string): CommonWrapper<HTMLAttributes<{}>, any>;
parents(): CommonWrapper<any, any>;
/**
@ -147,7 +150,8 @@ interface CommonWrapper<P, S> {
*/
closest<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
closest<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
closest(selector: string): CommonWrapper<HTMLAttributes<any>, any>;
closest(props: EnzymePropSelector): CommonWrapper<any, any>;
closest(selector: string): CommonWrapper<HTMLAttributes<{}>, any>;
/**
* Returns a string of the rendered text of the current render tree. This function should be looked at with
@ -156,14 +160,14 @@ interface CommonWrapper<P, S> {
*
* Note: can only be called on a wrapper of a single node.
*/
text(): String;
text(): string;
/**
* Returns a string of the rendered HTML markup of the current render tree.
*
* Note: can only be called on a wrapper of a single node.
*/
html(): String;
html(): string;
/**
* Returns the node at a given index of the current wrapper.
@ -191,14 +195,14 @@ interface CommonWrapper<P, S> {
* Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value.
* @param [key]
*/
state(key?: String): any;
state<T>(key?: String): T;
state(key?: string): any;
state<T>(key?: string): T;
/**
* Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value.
*/
context(key?: String): any;
context<T>(key?: String): T;
/**
* Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value.
*/
context(key?: string): any;
context<T>(key?: string): T;
/**
* Returns the props hash for the current node of the wrapper.
@ -213,14 +217,14 @@ interface CommonWrapper<P, S> {
* NOTE: can only be called on a wrapper of a single node.
* @param key
*/
prop(key: String): any;
prop<T>(key: String): T;
prop(key: string): any;
prop<T>(key: string): T;
/**
* Returns the key value for the node of the current wrapper.
* NOTE: can only be called on a wrapper of a single node.
*/
key(): String;
/**
* Returns the key value for the node of the current wrapper.
* NOTE: can only be called on a wrapper of a single node.
*/
key(): string;
/**
* Simulate events.
@ -286,7 +290,7 @@ interface CommonWrapper<P, S> {
* Returns an html-like string of the wrapper for debugging purposes. Useful to print out to the console when
* tests are not passing when you expect them to.
*/
debug(): String;
debug(): string;
/**
* Returns the type of the current node of this wrapper. If it's a composite component, this will be the
@ -294,14 +298,14 @@ interface CommonWrapper<P, S> {
*
* Note: can only be called on a wrapper of a single node.
*/
type(): String | Function;
type(): string | Function;
/**
* Returns the name of the current node of the wrapper.
*/
name(): String;
* Returns the name of the current node of the wrapper.
*/
name(): string;
/**
/**
* Iterates through each node of the current wrapper and executes the provided function with a wrapper around
* the corresponding node passed in as the first argument.
*
@ -341,25 +345,25 @@ interface CommonWrapper<P, S> {
* Returns whether or not any of the nodes in the wrapper match the provided selector.
* @param selector
*/
some(selector: EnzymeSelector): Boolean;
some(selector: EnzymeSelector): boolean;
/**
* Returns whether or not any of the nodes in the wrapper pass the provided predicate function.
* @param fn
*/
someWhere(fn: (wrapper: this) => Boolean): Boolean;
someWhere(fn: (wrapper: this) => boolean): boolean;
/**
* Returns whether or not all of the nodes in the wrapper match the provided selector.
* @param selector
*/
every(selector: EnzymeSelector): Boolean;
every(selector: EnzymeSelector): boolean;
/**
* Returns whether or not any of the nodes in the wrapper pass the provided predicate function.
* @param fn
*/
everyWhere(fn: (wrapper: this) => Boolean): Boolean;
everyWhere(fn: (wrapper: this) => boolean): boolean;
length: number;
}
@ -367,7 +371,7 @@ interface CommonWrapper<P, S> {
export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
shallow(): ShallowWrapper<P, S>;
render(): CheerioWrapper<P, S>;
unmount(): ShallowWrapper<any, any>;
unmount(): ShallowWrapper<any, any>;
/**
* Find every node in the render tree that matches the provided selector.
@ -375,7 +379,8 @@ export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
*/
find<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
find<P2>(statelessComponent: (props: P2) => JSX.Element): ShallowWrapper<P2, {}>;
find(selector: string): ShallowWrapper<HTMLAttributes<any>, any>;
find(props: EnzymePropSelector): ShallowWrapper<any, any>;
find(selector: string): ShallowWrapper<HTMLAttributes<{}>, any>;
/**
* Removes nodes in the current wrapper that do not match the provided selector.
@ -383,13 +388,14 @@ export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
*/
filter<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
filter<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, {}>;
filter(selector: string): ShallowWrapper<HTMLAttributes<any>, any>;
filter(props: EnzymePropSelector): ShallowWrapper<any, any>;
filter(selector: string): ShallowWrapper<HTMLAttributes<{}>, any>;
/**
* Finds every node in the render tree that returns true for the provided predicate function.
* @param predicate
*/
findWhere(predicate: (wrapper: CommonWrapper<any, any>) => Boolean): ShallowWrapper<any, any>;
findWhere(predicate: (wrapper: CommonWrapper<any, any>) => boolean): ShallowWrapper<any, any>;
/**
* Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector
@ -398,17 +404,18 @@ export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
*/
children<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, {}>;
children(selector: string): ShallowWrapper<HTMLAttributes<any>, any>;
children(props: EnzymePropSelector): ShallowWrapper<any, any>;
children(selector: string): ShallowWrapper<HTMLAttributes<{}>, any>;
children(): ShallowWrapper<any, any>;
/**
* Returns a new wrapper with child at the specified index.
* @param index
*/
childAt(index: Number): ShallowWrapper<any, any>;
childAt<P2, S2>(index: Number): ShallowWrapper<P2, S2>;
* Returns a new wrapper with child at the specified index.
* @param index
*/
childAt(index: number): ShallowWrapper<any, any>;
childAt<P2, S2>(index: number): ShallowWrapper<P2, S2>;
/**
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the
* current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector.
*
@ -417,7 +424,8 @@ export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
*/
parents<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, {}>;
parents(selector: string): ShallowWrapper<HTMLAttributes<any>, any>;
parents(props: EnzymePropSelector): ShallowWrapper<any, any>;
parents(selector: string): ShallowWrapper<HTMLAttributes<{}>, any>;
parents(): ShallowWrapper<any, any>;
/**
@ -429,131 +437,173 @@ export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
*/
closest<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
closest<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, {}>;
closest(selector: string): ShallowWrapper<HTMLAttributes<any>, any>;
closest(props: EnzymePropSelector): ShallowWrapper<any, any>;
closest(selector: string): ShallowWrapper<HTMLAttributes<{}>, any>;
/**
* Returns a wrapper with the direct parent of the node in the current wrapper.
*/
parent(): ShallowWrapper<any, any>;
/**
* Returns true if renderer returned null
*/
isEmptyRender(): boolean;
}
export interface ReactWrapper<P, S> extends CommonWrapper<P, S> {
unmount(): ReactWrapper<any, any>;
mount(): ReactWrapper<any, any>;
unmount(): ReactWrapper<any, any>;
mount(): ReactWrapper<any, any>;
/**
* Returns a wrapper of the node that matches the provided reference name.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*/
ref(refName: String): ReactWrapper<any, any>;
ref<P2, S2>(refName: String): ReactWrapper<P2, S2>;
/**
* Returns a wrapper of the node that matches the provided reference name.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*/
ref(refName: string): ReactWrapper<any, any>;
ref<P2, S2>(refName: string): ReactWrapper<P2, S2>;
/**
* Detaches the react tree from the DOM. Runs ReactDOM.unmountComponentAtNode() under the hood.
*
* This method will most commonly be used as a "cleanup" method if you decide to use the attachTo option in mount(node, options).
*
* The method is intentionally not "fluent" (in that it doesn't return this) because you should not be doing anything with this wrapper after this method is called.
*
* Using the attachTo is not generally recommended unless it is absolutely necessary to test something. It is your responsibility to clean up after yourself at the end of the test if you do decide to use it, though.
*/
detach() : void;
/**
* Detaches the react tree from the DOM. Runs ReactDOM.unmountComponentAtNode() under the hood.
*
* This method will most commonly be used as a "cleanup" method if you decide to use the attachTo option in mount(node, options).
*
* The method is intentionally not "fluent" (in that it doesn't return this) because you should not be doing anything with this wrapper after this method is called.
*
* Using the attachTo is not generally recommended unless it is absolutely necessary to test something. It is your responsibility to clean up after yourself at the end of the test if you do decide to use it, though.
*/
detach(): void;
/**
* Find every node in the render tree that matches the provided selector.
* @param selector The selector to match.
*/
find<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
find<P2>(statelessComponent: (props: P2) => JSX.Element): ReactWrapper<P2, {}>;
find(selector: string): ReactWrapper<HTMLAttributes<{}>, any>;
/**
* Find every node in the render tree that matches the provided selector.
* @param selector The selector to match.
*/
find<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
find<P2>(statelessComponent: (props: P2) => JSX.Element): ReactWrapper<P2, {}>;
find(props: EnzymePropSelector): ReactWrapper<any, any>;
find(selector: string): ReactWrapper<HTMLAttributes<{}>, any>;
/**
* Finds every node in the render tree that returns true for the provided predicate function.
* @param predicate
*/
findWhere(predicate: (wrapper: CommonWrapper<any, any>) => Boolean): ReactWrapper<any, any>;
/**
* Finds every node in the render tree that returns true for the provided predicate function.
* @param predicate
*/
findWhere(predicate: (wrapper: CommonWrapper<any, any>) => boolean): ReactWrapper<any, any>;
/**
* Removes nodes in the current wrapper that do not match the provided selector.
* @param selector The selector to match.
*/
filter<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
filter<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
filter(selector: string): ReactWrapper<HTMLAttributes<{}>, any>;
/**
* Removes nodes in the current wrapper that do not match the provided selector.
* @param selector The selector to match.
*/
filter<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
filter<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
filter(props: EnzymePropSelector): ReactWrapper<any, any>;
filter(selector: string): ReactWrapper<HTMLAttributes<{}>, any>;
/**
* Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector
* can be provided and it will filter the children by this selector.
* @param [selector]
*/
children<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
children(selector: string): ReactWrapper<HTMLAttributes<{}>, any>;
children(): ReactWrapper<any, any>;
/**
* Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector
* can be provided and it will filter the children by this selector.
* @param [selector]
*/
children<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
children(props: EnzymePropSelector): ReactWrapper<any, any>;
children(selector: string): ReactWrapper<HTMLAttributes<{}>, any>;
children(): ReactWrapper<any, any>;
/**
* Returns a new wrapper with child at the specified index.
* @param index
*/
childAt(index: Number): ReactWrapper<any, any>;
childAt<P2, S2>(index: Number): ReactWrapper<P2, S2>;
/**
* Returns a new wrapper with child at the specified index.
* @param index
*/
childAt(index: number): ReactWrapper<any, any>;
childAt<P2, S2>(index: number): ReactWrapper<P2, S2>;
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the
* current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector.
*
* Note: can only be called on a wrapper of a single node.
* @param [selector]
*/
parents<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
parents(selector: string): ReactWrapper<HTMLAttributes<{}>, any>;
parents(): ReactWrapper<any, any>;
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the
* current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector.
*
* Note: can only be called on a wrapper of a single node.
* @param [selector]
*/
parents<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
parents(props: EnzymePropSelector): ReactWrapper<any, any>;
parents(selector: string): ReactWrapper<HTMLAttributes<{}>, any>;
parents(): ReactWrapper<any, any>;
/**
* Returns a wrapper of the first element that matches the selector by traversing up through the current node's
* ancestors in the tree, starting with itself.
*
* Note: can only be called on a wrapper of a single node.
* @param selector
*/
closest<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
closest<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
closest(selector: string): ReactWrapper<HTMLAttributes<{}>, any>;
/**
* Returns a wrapper of the first element that matches the selector by traversing up through the current node's
* ancestors in the tree, starting with itself.
*
* Note: can only be called on a wrapper of a single node.
* @param selector
*/
closest<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
closest<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
closest(props: EnzymePropSelector): ReactWrapper<any, any>;
closest(selector: string): ReactWrapper<HTMLAttributes<{}>, any>;
/**
* Returns a wrapper with the direct parent of the node in the current wrapper.
*/
parent(): ReactWrapper<any, any>;
/**
* Returns a wrapper with the direct parent of the node in the current wrapper.
*/
parent(): ReactWrapper<any, any>;
/**
* Returns true if renderer returned null
*/
isEmptyRender(): boolean;
}
export interface CheerioWrapper<P, S> extends CommonWrapper<P, S> {
}
export interface ShallowRendererProps {
/**
* Enable experimental support for full react lifecycle methods
*/
lifecycleExperimental?: boolean;
/**
* Context to be passed into the component
*/
context?: {};
}
export interface MountRendererProps {
/**
* Context to be passed into the component
*/
context?: {};
/**
* DOM Element to attach the component to
*/
attachTo?: HTMLElement;
/**
* Merged contextTypes for all children of the wrapper
*/
childContextTypes?: {};
}
/**
* Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that
* your tests aren't indirectly asserting on behavior of child components.
* @param node
* @param [options]
*/
export declare function shallow<P, S>(node: ReactElement<P>, options?: any): ShallowWrapper<P, S>;
export function shallow<P, S>(node: ReactElement<P>, options?: ShallowRendererProps): ShallowWrapper<P, S>;
/**
* Mounts and renders a react component into the document and provides a testing wrapper around it.
* @param node
* @param [options]
*/
export declare function mount<P, S>(node: ReactElement<P>, options?: any): ReactWrapper<P, S>;
export function mount<P, S>(node: ReactElement<P>, options?: MountRendererProps): ReactWrapper<P, S>;
/**
* Render react components to static HTML and analyze the resulting HTML structure.
* @param node
* @param [options]
*/
export declare function render<P, S>(node: ReactElement<P>, options?: any): CheerioWrapper<P, S>;
export function render<P, S>(node: ReactElement<P>, options?: any): CheerioWrapper<P, S>;
export declare function describeWithDOM(description: String, fn: Function): void;
export function describeWithDOM(description: string, fn: Function): void;
export declare function spyLifecycle(component: typeof Component): void;
export function spyLifecycle(component: typeof Component): void;

View File

@ -3,32 +3,37 @@
// Definitions by: Wonshik Kim <https://github.com/wokim/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import express = require('express');
import unless = require('express-unless');
export = jwt;
declare function jwt(options: jwt.Options): jwt.RequestHandler;
interface IDoneCallback<T> {
(err: Error, result: T): void;
}
type ICallback = <T>(req: express.Request, payload: T, done: IDoneCallback<boolean>) => void;
declare namespace jwt {
export type secretType = string | Buffer
export interface SecretCallback {
(req: express.Request, header: any, payload: any, done: (err: any, secret?: boolean) => void): void;
(req: express.Request, payload: any, done: (err: any, secret?: secretType) => void): void;
}
export interface IsRevokedCallback {
(req: express.Request, payload: any, done: (err: any, revoked?: boolean) => void): void;
}
export interface GetTokenCallback {
(req: express.Request): any;
}
export interface Options {
secret: string | Buffer | ICallback;
secret: secretType | SecretCallback;
userProperty?: string;
skip?: string[];
credentialsRequired?: boolean;
isRevoked?: boolean;
isRevoked?: IsRevokedCallback;
requestProperty?: string;
getToken?: ICallback;
getToken?: GetTokenCallback;
[property: string]: any;
}
export interface RequestHandler extends express.RequestHandler {
unless?: typeof unless;
}
}
export = jwt;

View File

@ -1,4 +1,4 @@
// Type definitions for Express 4.x (core shared with serve-static)
// Type definitions for Express 4.x (core shared with serve-static)
// Project: http://expressjs.com
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@ -17,26 +17,33 @@ 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: 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 NextFunction {
(err?: any): void;
}
interface RequestHandler {
(req: Request, res: Response, next: NextFunction): any;
}
interface ErrorRequestHandler {
(err: any, req: Request, res: Response, next: NextFunction): any;
}
type PathParams = string | RegExp | (string | RegExp)[];
type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[];
interface IRouterMatcher<T> {
(name: string | RegExp, ...handlers: RequestHandlerParams[]): T;
(path: PathParams, ...handlers: RequestHandler[]): T;
(path: PathParams, ...handlers: RequestHandlerParams[]): T;
}
interface IRouter<T> extends RequestHandler {
interface IRouterHandler<T> {
(...handlers: RequestHandler[]): T;
(...handlers: RequestHandlerParams[]): T;
}
interface IRouter extends RequestHandler {
/**
* Map the given param placeholder `name`(s) to the given callback(s).
*
@ -66,11 +73,10 @@ declare module "express-serve-static-core" {
* @param name
* @param fn
*/
param(name: string, handler: RequestParamHandler): T;
param(name: string, matcher: RegExp): T;
param(name: string, mapper: (param: any) => any): T;
param(name: string, handler: RequestParamHandler): this;
// Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API
param(callback: (name: string, matcher: RegExp) => RequestParamHandler): T;
// deprecated since express 4.11.0
param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this;
/**
* Special-cased "all" method, applying the given route `path`,
@ -79,30 +85,34 @@ declare module "express-serve-static-core" {
* @param path
* @param fn
*/
all: IRouterMatcher<T>;
get: IRouterMatcher<T>;
post: IRouterMatcher<T>;
put: IRouterMatcher<T>;
delete: IRouterMatcher<T>;
patch: IRouterMatcher<T>;
options: IRouterMatcher<T>;
head: IRouterMatcher<T>;
all: IRouterMatcher<this>;
get: IRouterMatcher<this>;
post: IRouterMatcher<this>;
put: IRouterMatcher<this>;
delete: IRouterMatcher<this>;
patch: IRouterMatcher<this>;
options: IRouterMatcher<this>;
head: IRouterMatcher<this>;
route(path: string | RegExp): IRoute;
use: IRouterHandler<this> & IRouterMatcher<this>;
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: RequestHandlerParams[]): T;
use(path: RegExp, handler: ErrorRequestHandler): T;
use(path: string, router: Router): T;
route(prefix: PathParams): IRoute;
}
interface IRoute {
path: string;
stack: any;
all: IRouterHandler<this>;
get: IRouterHandler<this>;
post: IRouterHandler<this>;
put: IRouterHandler<this>;
delete: IRouterHandler<this>;
patch: IRouterHandler<this>;
options: IRouterHandler<this>;
head: IRouterHandler<this>;
}
export interface Router extends IRouter<Router> { }
export interface Router extends IRouter { }
interface CookieOptions {
maxAge?: number;
@ -243,6 +253,8 @@ declare module "express-serve-static-core" {
accepted: MediaType[];
/**
* @deprecated Use either req.params, req.body or req.query, as applicable.
*
* Return the value of param `name` when present or `defaultValue`.
*
* - Checks route placeholders, ex: _/user/:id_
@ -374,10 +386,6 @@ declare module "express-serve-static-core" {
params: any;
user: any;
authenticatedUser: any;
/**
* Clear cookie `name`.
*
@ -793,22 +801,13 @@ declare module "express-serve-static-core" {
vary(field: string): Response;
}
interface NextFunction {
(err?: any): void;
}
interface ErrorRequestHandler {
(err: any, req: Request, res: Response, next: NextFunction): any;
}
interface Handler extends RequestHandler { }
interface RequestParamHandler {
(req: Request, res: Response, next: NextFunction, param: any): any;
(req: Request, res: Response, next: NextFunction, value: any, name: string): any;
}
interface Application extends IRouter<Application>, Express.Application {
interface Application extends IRouter, Express.Application {
/**
* Initialize the server.
*
@ -869,10 +868,11 @@ declare module "express-serve-static-core" {
* @param val
*/
set(setting: string, val: any): Application;
get: {
(name: string): any; // Getter
(name: string | RegExp, ...handlers: RequestHandlerParams[]): Application;
};
get: {(name: string): any;} & IRouterMatcher<this>;
param(name: string | string[], handler: RequestParamHandler): this;
// Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API
param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this;
/**
* Return the app's absolute pathname
@ -1017,8 +1017,6 @@ declare module "express-serve-static-core" {
listen(path: string, callback?: Function): http.Server;
listen(handle: any, listeningListener?: Function): http.Server;
route(path: string | RegExp): IRoute;
router: string;
settings: any;
@ -1066,8 +1064,4 @@ declare module "express-serve-static-core" {
response: Response;
}
interface RequestHandler {
(req: Request, res: Response, next: NextFunction): any;
}
}

2
express/index.d.ts vendored
View File

@ -37,7 +37,7 @@ declare namespace e {
interface Express extends core.Express { }
interface Handler extends core.Handler { }
interface IRoute extends core.IRoute { }
interface IRouter<T> extends core.IRouter<T> { }
interface IRouter<T> extends core.IRouter { }
interface IRouterMatcher<T> extends core.IRouterMatcher<T> { }
interface MediaType extends core.MediaType { }
interface NextFunction extends core.NextFunction { }

View File

@ -0,0 +1,32 @@
/// <reference path="./fetch-mock.d.ts" />
import * as fetchMock from "fetch-mock";
fetchMock.mock("http://test.com", 200);
fetchMock.mock(/test\.com/, 200);
fetchMock.mock(() => true, 200);
fetchMock.mock((url, opts) => true, 200);
fetchMock.mock(/test/, "test").mock(/test/, { a: "b" });
fetchMock.mock(/test/, {
status: 200,
headers: {
"test": "test"
},
body: {
a: "b"
}
});
fetchMock.restore().reset();
(fetchMock.calls().matched[0][1] as RequestInit).body;
fetchMock.calls().unmatched[0][0].toUpperCase();
fetchMock.calls("http://test.com")[0][0].toUpperCase();
(fetchMock.calls("http://test.com")[0][1] as RequestInit).body;
fetchMock.called("http://test.com");
(fetchMock.lastCall()[1] as RequestInit).body;
fetchMock.lastUrl();
fetchMock.lastOptions();

207
fetch-mock/fetch-mock.d.ts vendored Normal file
View File

@ -0,0 +1,207 @@
// Type definitions for fetch-mock 5.0.0
// Project: https://github.com/wheresrhys/fetch-mock
// Definitions by: Alexey Svetliakov <https://github.com/asvetliakov>, Tamir Duberstein <https://github.com/tamird>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../whatwg-fetch/whatwg-fetch.d.ts" />
declare module "fetch-mock" {
type MockRequest = Request | RequestInit;
/**
* Mock matcher function
* @param url
* @param opts
*/
type MockMatcherFunction = (url: string, opts: MockRequest) => boolean
/**
* Mock matcher. Can be one of following:
* string: Either
* an exact url to match e.g. 'http://www.site.com/page.html'
* if the string begins with a `^`, the string following the `^` must
begin the url e.g. '^http://www.site.com' would match
'http://www.site.com' or 'http://www.site.com/page.html'
* '*' to match any url
* RegExp: A regular expression to test the url against
* Function(url, opts): A function (returning a Boolean) that is passed the
url and opts fetch() is called with (or, if fetch() was called with one,
the Request instance)
*/
type MockMatcher = string | RegExp | MockMatcherFunction;
/**
* Mock response object
*/
interface MockResponseObject {
/**
* Set the response body
*/
body?: string | {};
/**
* Set the response status
* @default 200
*/
status?: number;
/**
* Set the response headers.
*/
headers?: { [key: string]: string };
/**
* If this property is present then a Promise rejected with the value
of throws is returned
*/
throws?: boolean;
/**
* This property determines whether or not the request body should be
JSON.stringified before being sent
* @default true
*/
sendAsJson?: boolean;
}
/**
* Response: A Response instance - will be used unaltered
* number: Creates a response with this status
* string: Creates a 200 response with the string as the response body
* object: As long as the object is not a MockResponseObject it is
converted into a json string and returned as the body of a 200 response
* If MockResponseObject was given then it's used to configure response
* Function(url, opts): A function that is passed the url and opts fetch()
is called with and that returns any of the responses listed above
*/
type MockResponse = Response | Promise<Response>
| number | Promise<number>
| string | Promise<string>
| Object | Promise<Object>
| MockResponseObject | Promise<MockResponseObject>;
/**
* Mock response function
* @param url
* @param opts
*/
type MockResponseFunction = (url: string, opts: MockRequest) => MockResponse;
/**
* Mock options object
*/
interface MockOptions {
/**
* A unique string naming the route. Used to subsequently retrieve
references to the calls, grouped by name.
* @default matcher.toString()
*
* Note: If a non-unique name is provided no error will be thrown
(because names are optional, auto-generated ones may legitimately
clash)
*/
name?: string;
/**
* http method to match
*/
method?: string;
/**
* as specified above
*/
matcher?: MockMatcher;
/**
* as specified above
*/
response?: MockResponse | MockResponseFunction;
}
type MockCall = [string, MockRequest];
interface MatchedRoutes {
matched: Array<MockCall>;
unmatched: Array<MockCall>;
}
interface FetchMockStatic {
/**
* Replaces fetch() with a stub which records its calls, grouped by
route, and optionally returns a mocked Response object or passes the
call through to fetch(). Calls to .mock() can be chained.
* @param matcher Condition for selecting which requests to mock
* @param response Configures the http response returned by the mock
*/
mock(matcher: MockMatcher, response: MockResponse | MockResponseFunction): this;
/**
* Replaces fetch() with a stub which records its calls, grouped by
route, and optionally returns a mocked Response object or passes the
call through to fetch(). Calls to .mock() can be chained.
* @param matcher Condition for selecting which requests to mock
* @param response Configures the http response returned by the mock
* @param options Additional properties defining the route to mock
*/
mock(matcher: MockMatcher, response: MockResponse | MockResponseFunction, options: MockOptions): this;
/**
* Replaces fetch() with a stub which records its calls, grouped by
route, and optionally returns a mocked Response object or passes the
call through to fetch(). Calls to .mock() can be chained.
* @param options The route to mock
*/
mock(options: MockOptions): this;
/**
* Chainable method that restores fetch() to its unstubbed state and
clears all data recorded for its calls.
*/
restore(): this;
/**
* Chainable method that clears all data recorded for fetch()'s calls
*/
reset(): this;
/**
* Returns all calls to fetch, grouped by whether fetch-mock matched
them or not.
*/
calls(): MatchedRoutes;
/**
* Returns all calls to fetch matching matcherName.
*/
calls(matcherName?: string): Array<MockCall>;
/**
* Returns a Boolean indicating whether fetch was called and a route
was matched.
*/
called(): boolean;
/**
* Returns a Boolean indicating whether fetch was called and a route
named matcherName was matched.
*/
called(matcherName?: string): boolean;
/**
* Returns the arguments for the last matched call to fetch
*/
lastCall(): MockCall;
/**
* Returns the arguments for the last call to fetch matching
matcherName
*/
lastCall(matcherName?: string): MockCall;
/**
* Returns the url for the last matched call to fetch
*/
lastUrl(): string;
/**
* Returns the url for the last call to fetch matching matcherName
*/
lastUrl(matcherName?: string): string;
/**
* Returns the options for the last matched call to fetch
*/
lastOptions(): MockRequest;
/**
* Returns the options for the last call to fetch matching matcherName
*/
lastOptions(matcherName?: string): MockRequest;
/**
* Set some global config options, which include
* sendAsJson [default `true`] - by default fetchMock will
convert objects to JSON before sending. This is overrideable
for each call but for some scenarios, e.g. when dealing with a
lot of array buffers, it can be useful to default to `false`
*/
configure(opts: Object): void;
}
var fetchMock: FetchMockStatic;
export = fetchMock;
}

View File

@ -1,7 +1,134 @@
/// <reference types="node-fetch" />
import formData = require('form-data');
import FormData = require('form-data');
import fs = require('fs');
import http = require('http');
import request = require('request');
import fetch = require('node-fetch');
var value: any;
var fd = new formData.FormData();
var obj: Object = fd.getHeaders();
value = fd.pipe(value);
import * as ImportUsingES6Syntax from 'form-data';
() => {
var form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
}
() => {
var form = new FormData();
http.request('http://nodejs.org/images/logo.png', function (response) {
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_logo', response);
});
}
() => {
var form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_logo', request('http://nodejs.org/images/logo.png'));
}
() => {
var form = new FormData();
form.submit('http://example.org/', function (err, res) {
// res response object (http.IncomingMessage) //
res.resume();
});
}
() => {
var form = new FormData();
var request = http.request({
method: 'post',
host: 'example.org',
path: '/upload',
headers: form.getHeaders()
});
form.pipe(request);
request.on('response', function (res: any) {
console.log(res.statusCode);
});
}
() => {
var form = new FormData();
form.submit('example.org/upload', function (err, res) {
console.log(res.statusCode);
});
}
() => {
var CRLF = '\r\n';
var form = new FormData();
var buffer = new Buffer('');
var options = {
header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF,
knownLength: 1
};
form.append('my_buffer', buffer, options);
form.submit('http://example.com/', function (err, res) {
if (err) throw err;
console.log('Done');
});
}
() => {
var form = new FormData();
form.submit({
host: 'example.com',
path: '/probably.php?extra=params',
auth: 'username:password'
}, function (err, res) {
console.log(res.statusCode);
});
}
() => {
var form = new FormData();
form.submit({
host: 'example.com',
path: '/surelynot.php',
headers: { 'x-test-header': 'test-header-value' }
}, function (err, res) {
console.log(res.statusCode);
});
}
() => {
var formData = {
my_field: 'my_value',
my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
};
request.post({ url: 'http://service.com/upload', formData: formData }, function (err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
}
() => {
var form = new FormData();
form.append('a', 1);
fetch('http://example.com', { method: 'POST', body: form })
.then(function (res) {
return res.json();
}).then(function (json) {
console.log(json);
});
}

16
form-data/index.d.ts vendored
View File

@ -1,15 +1,23 @@
// Type definitions for form-data
// Project: https://github.com/felixge/node-form-data
// Definitions by: Carlos Ballesteros Velasco <https://github.com/soywiz>
// Definitions by: Carlos Ballesteros Velasco <https://github.com/soywiz>, Leon Yu <https://github.com/leonyu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Imported from: https://github.com/soywiz/typescript-node-definitions/form-data.d.ts
export = FormData;
export declare class FormData {
append(key: string, value: any, options?: any): FormData;
getHeaders(): Object;
declare class FormData {
append(key: string, value: any, options?: any): void;
getHeaders(): FormData.Dictionary<string>;
// TODO expand pipe
pipe(to: any): any;
submit(params: string | Object, callback: (error: any, response: any) => void): any;
getBoundary(): string;
}
declare namespace FormData {
interface Dictionary<T> {
[key: string]: T;
}
}

View File

@ -488,3 +488,25 @@ function test_formatter_PatternFormat() {
table.draw(view, { allowHtml: true, showRowNumber: true, width: '100%', height: '100%' });
}
function test_ChartsLoad() {
google.charts.load('current', {packages: ['corechart', 'table', 'sankey']});
function drawChart() {
// Define the chart to be drawn.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Element');
data.addColumn('number', 'Percentage');
data.addRows([
['Nitrogen', 0.78],
['Oxygen', 0.21],
['Other', 0.01]
]);
// Instantiate and draw the chart.
var chart = new google.visualization.PieChart(document.getElementById('myPieChart'));
chart.draw(data, null);
}
google.charts.setOnLoadCallback(drawChart);
}

View File

@ -1,6 +1,6 @@
// Type definitions for Google Visualisation Apis
// Project: https://developers.google.com/chart/
// Definitions by: Dan Ludwig <https://github.com/danludwig>
// Definitions by: Dan Ludwig <https://github.com/danludwig>, Gregory Moore <https://github.com/gmoore-sjcorg>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace google {
@ -9,6 +9,12 @@ declare namespace google {
function setOnLoadCallback(handler: Function): void;
function setOnLoadCallback(handler: () => void): void;
// https://developers.google.com/chart/interactive/docs/basic_load_libs
namespace charts {
function load(version: string, packages: Object): void;
function setOnLoadCallback(handler: Function): void;
}
//https://developers.google.com/chart/interactive/docs/reference
namespace visualization {
@ -141,6 +147,7 @@ declare namespace google {
id?: string;
role?: string;
pattern?: string;
p?: any;
}
export interface DataObject {
@ -186,6 +193,42 @@ declare namespace google {
function arrayToDataTable(data: any[], firstRowIsData?: boolean): DataTable;
//#endregion
//#region Query
// https://developers.google.com/chart/interactive/docs/reference#query
export class Query {
constructor(dataSourceUrl: string, options?: QueryOptions);
abort(): void;
setRefreshInterval(intervalSeconds: number): void;
setTimeout(timeoutSeconds: number): void;
setQuery(queryString:string): void;
send(callback: (response: QueryResponse) => void): void;
}
export interface QueryOptions {
sendMethod?: string,
makeRequestParams?: Object
}
//#endregion
//#region QueryResponse
// https://developers.google.com/chart/interactive/docs/reference#queryresponse
export class QueryResponse {
constructor(responseObject: Object);
getDataTable(): DataTable;
getDetailedMessage(): string;
getMessage(): string;
getReasons(): string[];
hasWarning(): boolean;
isError(): boolean;
}
//#endregion
//#region DataView

View File

@ -0,0 +1,21 @@
///<reference path="gulp-insert.d.ts" />
///<reference path="../gulp/gulp.d.ts" />
import * as gulp from 'gulp';
import * as insert from 'gulp-insert';
gulp.task('gulp-insert-tests', () => {
return gulp.src('*.js')
.pipe(insert.prepend('/* Inserted using gulp-insert prepend method */\n'))
.pipe(insert.prepend('\n/* Inserted using gulp-insert append method */'))
.pipe(insert.wrap(
'/* Inserted using gulp-insert wrap method */\n',
'\n/* Inserted using gulp-insert wrap method */'
))
.pipe(insert.transform((contents, file) => {
var comment = '/* Local file: ' + file.path + ' */\n';
return comment + contents;
}))
.pipe(gulp.dest('gulp-insert'));
});

52
gulp-insert/gulp-insert.d.ts vendored Normal file
View File

@ -0,0 +1,52 @@
// Type definitions for gulp-insert 0.5.0
// Project: https://github.com/rschmukler/gulp-insert
// Definitions by: Shant Marouti <https://github.com/shantmarouti>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts"/>
/// <reference path="../vinyl/vinyl.d.ts"/>
declare module 'gulp-insert' {
import File = require('vinyl');
interface Transformer {
(contents: string, file: File): string
}
namespace Insert {
/**
* Prepends a string onto the contents
* @param {string} content
* @returns {NodeJS.ReadWriteStream}
*/
function prepend(content: string): NodeJS.ReadWriteStream;
/**
* Appends a string onto the contents
* @param {string} content
* @returns {NodeJS.ReadWriteStream}
*/
function append(content: string): NodeJS.ReadWriteStream;
/**
* Wraps the contents with two strings
* @param {string} prepend
* @param {string} append
* @returns {NodeJS.ReadWriteStream}
*/
function wrap(prepend: string, append: string): NodeJS.ReadWriteStream;
/**
* Calls a function with the contents of the file
* @param {Transformer} transformer
* @returns {NodeJS.ReadWriteStream}
*/
function transform(transformer: Transformer): NodeJS.ReadWriteStream;
}
module Insert { }
export = Insert;
}

11
gulp/index.d.ts vendored
View File

@ -151,9 +151,14 @@ declare namespace gulp {
dot?: boolean;
/**
* By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid
* filesystem path is returned. Set this flag to disable that behavior.
*/
* Set to match only fles, not directories. Set this flag to prevent copying empty directories
*/
nodir?: boolean;
/**
* By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid
* filesystem path is returned. Set this flag to disable that behavior.
*/
nomount?: boolean;
/**

73
hammerjs/index.d.ts vendored
View File

@ -1,4 +1,4 @@
// Type definitions for Hammer.js 2.0.4
// Type definitions for Hammer.js 2.0.8
// Project: http://hammerjs.github.io/
// Definitions by: Philip Bulley <https://github.com/milkisevil/>, Han Lin Yap <https://github.com/codler>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@ -11,7 +11,7 @@ declare module "hammerjs" {
interface HammerStatic
{
new( element:HTMLElement | SVGElement, options?:any ): HammerManager;
new( element:HTMLElement | SVGElement, options?:HammerOptions ): HammerManager;
defaults:HammerDefaults;
@ -68,16 +68,22 @@ interface HammerStatic
prefixed( obj:any, property:string ):string;
}
interface HammerDefaults
type RecognizerTuple =
[RecognizerStatic]
| [RecognizerStatic, RecognizerOptions]
| [RecognizerStatic, RecognizerOptions, string | string[]]
| [RecognizerStatic, RecognizerOptions, string | string[], (string | Recognizer) | (string | Recognizer)[]];
interface HammerDefaults extends HammerOptions
{
domEvents:boolean;
enable:boolean;
preset:any[];
preset:RecognizerTuple[];
touchAction:string;
cssProps:CssProps;
inputClass():void;
inputTarget():void;
inputClass:() => void;
inputTarget:EventTarget;
}
interface CssProps
@ -90,13 +96,25 @@ interface CssProps
userSelect:string;
}
interface HammerOptions extends HammerDefaults
interface HammerOptions
{
cssProps?:CssProps;
domEvents?:boolean;
enable?:boolean | ((manager: HammerManager) => boolean);
preset?:RecognizerTuple[];
touchAction?:string;
recognizers?:RecognizerTuple[];
inputClass?:() => void;
inputTarget?:EventTarget;
}
interface HammerManagerConstructor {
new( element:HTMLElement, options?:any ):HammerManager;
new( element:EventTarget, options?:HammerOptions ):HammerManager;
}
interface HammerListener {
(event:HammerInput): void
}
interface HammerManager
@ -109,8 +127,8 @@ interface HammerManager
emit( event:string, data:any ):void;
get( recogniser:Recognizer ):Recognizer;
get( recogniser:string ):Recognizer;
off( events:string, handler?:( event:HammerInput ) => void ):void;
on( events:string, handler:( event:HammerInput ) => void ):void;
off( events:string, handler?:HammerListener ):void;
on( events:string, handler:HammerListener ):void;
recognize( inputData:any ):void;
remove( recogniser:Recognizer ):HammerManager;
remove( recogniser:string ):HammerManager;
@ -157,7 +175,7 @@ declare class HammerInput
direction:number;
/** Direction moved from it's starting point. Matches the DIRECTION constants. */
offsetDirection:string;
offsetDirection:number;
/** Scaling that has been done when multi-touch. 1 on a single touch. */
scale:number;
@ -178,7 +196,7 @@ declare class HammerInput
pointerType:string;
/** Event type, matches the INPUT constants. */
eventType:string;
eventType:number;
/** true when the first input. */
isFirst:boolean;
@ -221,9 +239,22 @@ declare class TouchMouseInput extends HammerInput
constructor( manager:HammerManager, callback:Function );
}
interface RecognizerOptions {
direction?: number;
enable?: boolean | ((recognizer: Recognizer, inputData: HammerInput) => boolean);
event?: string;
interval?: number;
pointers?: number;
posThreshold?: number;
taps?: number
threshold?: number;
time?: number;
velocity?: number;
}
interface RecognizerStatic
{
new( options?:any ):Recognizer;
new( options?:RecognizerOptions ):Recognizer;
}
interface Recognizer
@ -246,7 +277,7 @@ interface Recognizer
requireFailure( otherRecognizer:Recognizer ):Recognizer;
requireFailure( otherRecognizer:string ):Recognizer;
reset():void;
set( options?:any ):Recognizer;
set( options?:RecognizerOptions ):Recognizer;
tryEmit( input:HammerInput ):void;
}
@ -258,12 +289,12 @@ interface AttrRecognizerStatic
interface AttrRecognizer extends Recognizer
{
new( options?:any ):AttrRecognizer;
new( options?:RecognizerOptions ):AttrRecognizer;
}
interface PanRecognizerStatic
{
new( options?:any ):PanRecognizer;
new( options?:RecognizerOptions ):PanRecognizer;
}
interface PanRecognizer extends AttrRecognizer
@ -272,7 +303,7 @@ interface PanRecognizer extends AttrRecognizer
interface PinchRecognizerStatic
{
new( options?:any ):PinchRecognizer;
new( options?:RecognizerOptions ):PinchRecognizer;
}
interface PinchRecognizer extends AttrRecognizer
@ -281,7 +312,7 @@ interface PinchRecognizer extends AttrRecognizer
interface PressRecognizerStatic
{
new( options?:any ):PressRecognizer;
new( options?:RecognizerOptions ):PressRecognizer;
}
interface PressRecognizer extends AttrRecognizer
@ -290,7 +321,7 @@ interface PressRecognizer extends AttrRecognizer
interface RotateRecognizerStatic
{
new( options?:any ):RotateRecognizer;
new( options?:RecognizerOptions ):RotateRecognizer;
}
interface RotateRecognizer extends AttrRecognizer
@ -299,7 +330,7 @@ interface RotateRecognizer extends AttrRecognizer
interface SwipeRecognizerStatic
{
new( options?:any ):SwipeRecognizer;
new( options?:RecognizerOptions ):SwipeRecognizer;
}
interface SwipeRecognizer extends AttrRecognizer
@ -308,7 +339,7 @@ interface SwipeRecognizer extends AttrRecognizer
interface TapRecognizerStatic
{
new( options?:any ):TapRecognizer;
new( options?:RecognizerOptions ):TapRecognizer;
}
interface TapRecognizer extends AttrRecognizer

View File

@ -232,7 +232,7 @@ declare namespace ht {
getCellMeta(row: number, col: number): Object;
getCellRenderer(row: number, col: number): Function;
getCellValidator(row: number, col: number): any;
getColHeader(col: number): any[]|string;
getColHeader(col?: number): any[]|string;
getColWidth(col: number): number;
getCoords(elem: Element): Object;
getCopyableData(row: number, column: number): string;

4
hapi/index.d.ts vendored
View File

@ -963,7 +963,7 @@ export interface IServerInjectResponse {
payload: string;
rawPayload: Buffer;
raw: {
req: http.ClientRequest;
req: http.IncomingMessage;
res: http.ServerResponse
};
result: string;
@ -1198,7 +1198,7 @@ export class Request extends Events.EventEmitter {
query: any;
/** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/
raw: {
req: http.ClientRequest;
req: http.IncomingMessage;
res: http.ServerResponse;
};
/** the route public interface.*/

20
howler/index.d.ts vendored
View File

@ -52,20 +52,20 @@ interface Howl {
onpause: Function;
onplay: Function;
load(): Howl;
play(sprite?: string, callback?: (soundId: number) => void): Howl;
play(callback?: (soundId: number) => void): Howl;
pause(soundId?: number): Howl;
stop(soundId?: number): Howl;
mute(soundId?: number): Howl;
unmute(soundId?: number): Howl;
fade(from: number, to: number, duration: number, callback?: Function, soundId?: number): Howl;
play(sprite?: string, callback?: (soundId: string) => void): Howl;
play(callback?: (soundId: string) => void): Howl;
pause(soundId?: string): Howl;
stop(soundId?: string): Howl;
mute(soundId?: string): Howl;
unmute(soundId?: string): Howl;
fade(from: number, to: number, duration: number, callback?: Function, soundId?: string): Howl;
loop(): boolean;
loop(loop: boolean): Howl;
pos(position?: number, soundId?: number): number;
pos3d(x: number, y: number, z: number, soundId?: number): any;
pos(position?: number, soundId?: string): number;
pos3d(x: number, y: number, z: number, soundId?: string): any;
sprite(definition?: IHowlSoundSpriteDefinition): IHowlSoundSpriteDefinition;
volume(): number;
volume(volume?: number, soundId?: number): Howl;
volume(volume?: number, soundId?: string): Howl;
urls(): string[];
urls(urls: string[]): Howl;
on(event: string, listener?: Function): Howl;

View File

@ -4,12 +4,19 @@ import * as express from 'express';
var app = express();
declare global {
namespace Express {
export interface Request {
user?: any
}
}
}
app.use(function (req, res, next) {
if (!req.user) return next(createError(401, 'Please login to view this page.'));
next();
});
/* Examples taken from https://github.com/jshttp/http-errors/blob/1.3.1/test/test.js */
// createError(status)

12
ioredis/index.d.ts vendored
View File

@ -38,7 +38,8 @@ declare module IORedis {
}
interface Redis extends NodeJS.EventEmitter, Commander {
connect(callback: Function): Promise<any>;
status: string;
connect(callback?: Function): Promise<any>;
disconnect(): void;
duplicate(): Redis;
monitor(calback: (error: Error, monitor: NodeJS.EventEmitter) => void): Promise<NodeJS.EventEmitter>;
@ -56,6 +57,7 @@ declare module IORedis {
subscribe(channel: string): any;
get(args: any[], callback?: ResCallbackT<string>): any;
get(...args: any[]): any;
getBuffer(key: string, callback?: ResCallbackT<Buffer>): any;
set(args: any[], callback?: ResCallbackT<string>): any;
set(...args: any[]): any;
setnx(args: any[], callback?: ResCallbackT<any>): any;
@ -227,8 +229,12 @@ declare module IORedis {
renamenx(...args: any[]): any;
expire(args: any[], callback?: ResCallbackT<any>): any;
expire(...args: any[]): any;
pexpire(args: any[], callback?: ResCallbackT<any>): any;
pexpire(...args: any[]): any;
expireat(args: any[], callback?: ResCallbackT<any>): any;
expireat(...args: any[]): any;
pexpireat(args: any[], callback?: ResCallbackT<any>): any;
pexpireat(...args: any[]): any;
keys(args: any[], callback?: ResCallbackT<any>): any;
keys(...args: any[]): any;
dbsize(args: any[], callback?: ResCallbackT<any>): any;
@ -504,8 +510,12 @@ declare module IORedis {
renamenx(...args: any[]): Pipeline;
expire(args: any[], callback?: ResCallbackT<any>): Pipeline;
expire(...args: any[]): Pipeline;
pexpire(args: any[], callback?: ResCallbackT<any>): Pipeline;
pexpire(...args: any[]): Pipeline;
expireat(args: any[], callback?: ResCallbackT<any>): Pipeline;
expireat(...args: any[]): Pipeline;
pexpireat(args: any[], callback?: ResCallbackT<any>): Pipeline;
pexpireat(...args: any[]): Pipeline;
keys(args: any[], callback?: ResCallbackT<any>): Pipeline;
keys(...args: any[]): Pipeline;
dbsize(args: any[], callback?: ResCallbackT<any>): Pipeline;

View File

@ -33,4 +33,9 @@ myScroll1.scrollToElement(document.getElementById('selectedElement'), 250);
myScroll2.on('scrollStart', function () { console.log('scroll started'); });
var myScroll9 = new IScroll(document.getElementById('wrapper'));
var myScroll10 = new IScroll(document.getElementById('wrapper'), { scrollbarClass: 'myScrollbar' });
var myScroll10 = new IScroll(document.getElementById('wrapper'), { scrollbarClass: 'myScrollbar' });
var myScroll11 = new IScroll(document.getElementById('wrapper'), { preventDefaultException: [ /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ ] });
var myScroll12 = new IScroll(document.getElementById('wrapper'), { preventDefaultException: { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ } });
var myScroll13 = new IScroll(document.getElementById('wrapper'), { bounceEasing: 'circular' });
var myScroll14 = new IScroll(document.getElementById('wrapper'), { bounceEasing: { style: 'cubic-bezier(0,0,1,1)', fn: function (k) { return k; } } });

View File

@ -51,10 +51,10 @@ interface IScrollOptions {
bounceTime?: number;
///String or function
bounceEasing?: any;
bounceEasing?: string|{ style: string, fn: (k: any) => any };
preventDefault?: boolean;
preventDefaultException?: boolean;
preventDefaultException?: Array<RegExp>|Object;
HWCompositing?: boolean;

1
jest/index.d.ts vendored
View File

@ -26,6 +26,7 @@ declare namespace jest {
function autoMockOn(): void;
function clearAllTimers(): void;
function currentTestPath(): string;
function disableAutomock(): void;
function fn<T>(implementation?: Function): Mock<T>;
function dontMock(moduleName: string): void;
function genMockFromModule<T>(moduleName: string): Mock<T>;

View File

@ -28,6 +28,7 @@ interface JQueryContextMenuOptions {
items: any;
reposition?: boolean;
className?: string;
itemClickEvent?: string;
}
interface JQueryStatic {

View File

@ -17,13 +17,13 @@ interface JQueryFileInputOptions {
* The drop target element(s), by the default the complete document.
* Set to null to disable drag & drop support:
*/
dropZone?: HTMLElement;
dropZone?: Element | Element[] | JQuery | string;
/**
* The paste target element(s), by the default the complete document.
* Set to null to disable paste support:
*/
pasteZone?: HTMLElement;
pasteZone?: Element | Element[] | JQuery | string;
/**
* The file input field(s), that are listened to for change events.
@ -31,7 +31,7 @@ interface JQueryFileInputOptions {
* of the widget element on plugin initialization.
* Set to null to disable the change listener.
*/
fileInput?: HTMLElement;
fileInput?: Element | Element[] | JQuery | string;
/**
* By default, the file input field is replaced with a clone after

View File

@ -77,33 +77,38 @@ declare namespace JQueryPayment {
/**
* Card type
*/
type: string;
type?: string;
/*
/**
* Regex used to identify the card type. For the best experience, this should be
* the shortest pattern that can guarantee the card is of a particular type.
*/
pattern: RegExp;
pattern?: RegExp;
/**
* Array of prefixes used to identify the card type.
*/
patterns?: number[];
/**
* Array of valid card number lengths.
*/
length: number[];
length?: number[];
/**
* Array of valid card CVC lengths.
*/
cvcLength: number[];
cvcLength?: number[];
/**
* Boolean indicating whether a valid card number should satisfy the Luhn check.
*/
luhn: boolean;
luhn?: boolean;
/**
* Regex used to format the card number. Each match is joined with a space.
*/
format: RegExp;
format?: RegExp;
}
}

View File

@ -0,0 +1,45 @@
/// <reference path="jquery.payment.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
$.payment.cards.push({
// Card type, as returned by $.payment.cardType.
type: 'mastercard',
// Array of prefixes used to identify the card type.
patterns: [
51, 52, 53, 54, 55,
22, 23, 24, 25, 26, 27
],
// Array of valid card number lengths.
length: [16],
// Array of valid card CVC lengths.
cvcLength: [3],
// Boolean indicating whether a valid card number should satisfy the Luhn check.
luhn: true,
// Regex used to format the card number. Each match is joined with a space.
format: /(\d{1,4})/g
})
$('[data-numeric]').payment('restrictNumeric');
$.payment.validateCardNumber('4242 4242 4242 4242') === true; //=> true
$.payment.validateCardExpiry('05', '20') === true; //=> true
$.payment.validateCardExpiry('05', '2015') === true; //=> true
$.payment.validateCardExpiry('05', '05') === true; //=> false
$.payment.validateCardCVC('123') === true; //=> true
$.payment.validateCardCVC('123', 'amex') === true; //=> true
$.payment.validateCardCVC('1234', 'amex') === true; //=> true
$.payment.validateCardCVC('12344') === false; //=> false
$.payment.cardType('4242 4242 4242 4242') === 'visa'; //=> 'visa'
$.payment.cardExpiryVal('03 / 2025') === {month: 3, year: 2025}; //=> {month: 3, year: 2025}
$.payment.cardExpiryVal('05 / 04') === {month: 3, year: 2025}; //=> {month: 5, year: 2004}
$('input.cc-exp').payment('cardExpiryVal') //=> {month: 4, year: 2020}
var valid = $.payment.validateCardNumber($('input.cc-num').val());
if (!valid) {
alert('Your card is not valid!');
}

View File

@ -28,4 +28,8 @@ interface JQueryTimer {
interface JQuery {
timer: JQueryTimer;
}
}
interface JQueryStatic {
timer: JQueryTimer;
}

1
jquery/index.d.ts vendored
View File

@ -442,6 +442,7 @@ interface JQueryDeferred<T> extends JQueryGenericPromise<T> {
* Interface of the JQuery extension of the W3C event object
*/
interface BaseJQueryEventObject extends Event {
currentTarget: Element;
data: any;
delegateTarget: Element;
isDefaultPrevented(): boolean;

View File

@ -1524,6 +1524,9 @@ function test_eventParams() {
$(window).on('mousewheel', (e) => {
var delta = (<WheelEvent>e.originalEvent).deltaY;
});
$( "p" ).click(function( event ) {
alert( event.currentTarget === this ); // true
});
}
function test_extend() {

48
jqueryui/index.d.ts vendored
View File

@ -1,4 +1,4 @@
// Type definitions for jQueryUI 1.9
// Type definitions for jQueryUI 1.11
// Project: http://jqueryui.com/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, John Reilly <https://github.com/johnnyreilly>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@ -626,6 +626,36 @@ declare namespace JQueryUI {
interface Selectable extends Widget, SelectableOptions {
}
// SelectMenu //////////////////////////////////////////////////
interface SelectMenuOptions extends SelectMenuEvents {
appendTo?: string;
disabled?: boolean;
icons?: any;
position?: JQueryPositionOptions;
width?: number;
}
interface SelectMenuUIParams {
item?: JQuery;
}
interface SelectMenuEvent {
(event: Event, ui: SelectMenuUIParams): void;
}
interface SelectMenuEvents {
change?: SelectMenuEvent;
close?: SelectMenuEvent;
create?: SelectMenuEvent;
focus?: SelectMenuEvent;
open?: SelectMenuEvent;
select?: SelectMenuEvent;
}
interface SelectMenu extends Widget, SelectMenuOptions {
}
// Slider //////////////////////////////////////////////////
interface SliderOptions extends SliderEvents {
@ -1676,6 +1706,22 @@ interface JQuery {
selectable(optionLiteral: string, options: JQueryUI.SelectableOptions): any;
selectable(optionLiteral: string, optionName: string, optionValue: any): JQuery;
selectmenu(): JQuery;
selectmenu(methodName: 'close'): JQuery;
selectmenu(methodName: 'destroy'): JQuery;
selectmenu(methodName: 'disable'): JQuery;
selectmenu(methodName: 'enable'): JQuery;
selectmenu(methodName: 'instance'): any;
selectmenu(methodName: 'menuWidget'): JQuery;
selectmenu(methodName: 'open'): JQuery;
selectmenu(methodName: 'refresh'): JQuery;
selectmenu(methodName: 'widget'): JQuery;
selectmenu(methodName: string): JQuery;
selectmenu(options: JQueryUI.SelectMenuOptions): JQuery;
selectmenu(optionLiteral: string, optionName: string): any;
selectmenu(optionLiteral: string, options: JQueryUI.SelectMenuOptions): any;
selectmenu(optionLiteral: string, optionName: string, optionValue: any): JQuery;
slider(): JQuery;
slider(methodName: 'destroy'): void;
slider(methodName: 'disable'): void;

View File

@ -1475,6 +1475,59 @@ function test_menu() {
$(".selector").menu({ select: (e, ui) => { } });
}
function test_selectmenu() {
// Options
$("#selectmenu").selectmenu();
$(".selector").selectmenu({ appendTo: ".selector" });
$(".selector").selectmenu({ disabled: true });
$(".selector").selectmenu({ icons: { submenu: "ui-icon-circle-triangle-e" } });
$(".selector").selectmenu({ position: { my: "left top", at: "right-5 top+5" } });
$(".selector").selectmenu({ width: 47 });
// Events
$("#selectmenu").selectmenu({ change: (event, ui) => {}});
$("#selectmenu").selectmenu({ close: (event, ui) => {}});
$("#selectmenu").selectmenu({ create: (event, ui) => {}});
$("#selectmenu").selectmenu({ focus: (event, ui) => {}});
$("#selectmenu").selectmenu({ open: (event, ui) => {}});
$("#selectmenu").selectmenu({ select: (event, ui) => {}});
// Events and options
$("#selectmenu").selectmenu({
appendTo: ".selector",
disabled: true,
icons: { submenu: "ui-icon-circle-triangle-e" },
position: { my: "left top", at: "right-5 top+5" },
width: 47,
change: (event, ui) => {},
close: (event, ui) => {},
create: (event, ui) => {},
focus: (event, ui) => {},
open: (event, ui) => {},
select: (event, ui) => {}
});
// passing in option
$(".selector").selectmenu("option", { disabled: true });
// Fetching option value
var disabled = $(".selector").selectmenu("option", "disabled");
// Setting option value
$(".selector").selectmenu("option", "disabled", true);
$(".selector").selectmenu("option", "position", { my: "left top", at: "right-5 top+5" } );
// Methods
$(".selector").selectmenu("close");
$(".selector").selectmenu("destroy");
// Chaining
$("#number")
.selectmenu()
.selectmenu("menuWidget")
.addClass("overflow");
}
function test_progressbar() {
$("#progressbar").progressbar({

View File

@ -1,4 +1,4 @@
// Type definitions for jsonwebtoken 6.2.0
// Type definitions for jsonwebtoken 7.1.6
// Project: https://github.com/auth0/node-jsonwebtoken
// Definitions by: Maxime LUCE <https://github.com/SomaticIT>, Daniel Heim <https://github.com/danielheim>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@ -47,14 +47,17 @@ export interface SignOptions {
jwtid?: string;
noTimestamp?: boolean;
headers?: Object;
encoding?: string;
}
export interface VerifyOptions {
algorithms?: string[];
audience?: string;
issuer?: string;
audience?: string | string[];
clockTolerance?: number;
issuer?: string | string[];
ignoreExpiration?: boolean;
ignoreNotBefore?: boolean;
jwtId?: string;
subject?: string;
/**
*@deprecated

85
jszip/index.d.ts vendored
View File

@ -4,6 +4,8 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface JSZip {
files: {[key: string]: JSZipObject};
/**
* Get a file from the archive
*
@ -46,6 +48,13 @@ interface JSZip {
*/
folder(name: RegExp): JSZipObject[];
/**
* Call a callback function for each entry at this folder level.
*
* @param callback function
*/
forEach(callback: (relativePath: string, file: JSZipObject) => void): void;
/**
* Get all files wchich match the given filter function
*
@ -63,23 +72,40 @@ interface JSZip {
remove(path: string): JSZip;
/**
* Generates a new archive
*
* @param options Optional options for the generator
* @return The serialized archive
* @deprecated since version 3.0
* @see {@link generateAsync}
* http://stuk.github.io/jszip/documentation/upgrade_guide.html
*/
generate(options?: JSZipGeneratorOptions): any;
/**
* Deserialize zip file
* Generates a new archive asynchronously
*
* @param options Optional options for the generator
* @return The serialized archive
*/
generateAsync(options?: JSZipGeneratorOptions, onUpdate?: Function): Promise<any>;
/**
* @deprecated since version 3.0
* @see {@link loadAsync}
* http://stuk.github.io/jszip/documentation/upgrade_guide.html
*/
load(): void;
/**
* Deserialize zip file asynchronously
*
* @param data Serialized zip file
* @param options Options for deserializing
* @return Returns the JSZip instance
* @return Returns promise
*/
load(data: any, options: JSZipLoadOptions): JSZip;
loadAsync(data: any, options?: JSZipLoadOptions): Promise<JSZip>;
}
type Serialization = ("string" | "text" | "base64" | "binarystring" | "uint8array" |
"arraybuffer" | "blob" | "nodebuffer");
interface JSZipObject {
name: string;
dir: boolean;
@ -87,11 +113,31 @@ interface JSZipObject {
comment: string;
options: JSZipObjectOptions;
asText(): string;
asBinary(): string;
asArrayBuffer(): ArrayBuffer;
asUint8Array(): Uint8Array;
//asNodeBuffer(): Buffer;
/**
* Prepare the content in the asked type.
* @param {String} type the type of the result.
* @param {Function} onUpdate a function to call on each internal update.
* @return Promise the promise of the result.
*/
async(type: Serialization, onUpdate?: Function): Promise<any>;
/**
* @deprecated since version 3.0
*/
asText(): void;
/**
* @deprecated since version 3.0
*/
asBinary(): void;
/**
* @deprecated since version 3.0
*/
asArrayBuffer(): void;
/**
* @deprecated since version 3.0
*/
asUint8Array(): void;
//asNodeBuffer(): void;
}
interface JSZipFileOptions {
@ -140,18 +186,6 @@ interface JSZipSupport {
nodebuffer: boolean;
}
interface DEFLATE {
/** pako.deflateRaw, level:0-9 */
compress(input: string, compressionOptions: {level:number}): Uint8Array;
compress(input: number[], compressionOptions: {level:number}): Uint8Array;
compress(input: Uint8Array, compressionOptions: {level:number}): Uint8Array;
/** pako.inflateRaw */
uncompress(input: string): Uint8Array;
uncompress(input: number[]): Uint8Array;
uncompress(input: Uint8Array): Uint8Array;
}
declare var JSZip: {
/**
* Create JSZip instance
@ -181,9 +215,6 @@ declare var JSZip: {
prototype: JSZip;
support: JSZipSupport;
compressions: {
DEFLATE: DEFLATE;
}
}
declare module "jszip" {

View File

@ -6,44 +6,70 @@ var SEVERITY = {
FATAL: 4
}
function createTestZip(): JSZip {
var zip = new JSZip();
zip.file("test.txt", "test string");
zip.file("test/test.txt", "test string");
return zip
}
function filterWithFileAsync(zip: JSZip, as: Serialization,
cb: (relativePath: string, file: JSZipObject, value: any) => boolean)
: Promise<JSZipObject[]> {
var promises: Promise<any>[] = [];
var promiseIndices: {[key: string]: number} = {};
zip.forEach((relativePath: string, file: JSZipObject) => {
var promise = file.async(as);
promiseIndices[file.name] = promises.length;
promises.push(promise);
});
return Promise.all(promises).then(function(values: any[]) {
var filtered = zip.filter((relativePath: string, file: JSZipObject) => {
var index = promiseIndices[file.name];
return cb(relativePath, file, values[index]);
});
return Promise.resolve(filtered);
});
}
function testJSZip() {
var newJszip = new JSZip();
newJszip.file("test.txt", "test string");
newJszip.file("test/test.txt", "test string");
var serializedZip = newJszip.generate({compression: "DEFLATE", type: "base64"});
newJszip = new JSZip();
newJszip.load(serializedZip, {base64: true, checkCRC32: true});
if (newJszip.file("test.txt").asText() === "test string") {
var zip = createTestZip();
zip.generateAsync({compression: "DEFLATE", type: "base64"}).then(function(serializedZip: any) {
var newJszip = new JSZip();
return newJszip.loadAsync(serializedZip, {base64: true/*, checkCRC32: true*/});
}).then(function(newJszip: JSZip) {
newJszip.file("test.txt").async('text').then(function(text: string) {
if (text === "test string") {
log(SEVERITY.INFO, "all ok");
} else {
log(SEVERITY.ERROR, "no matching file found");
}
if (newJszip.file("test/test.txt").asText() === "test string") {
}).catch((e: any) => log(SEVERITY.ERROR, e));
newJszip.file("test/test.txt").async('text').then(function(text: string) {
if (text === "test string") {
log(SEVERITY.INFO, "all ok");
} else {
log(SEVERITY.ERROR, "no matching file found");
}
}).catch((e: any) => log(SEVERITY.ERROR, e));
var folder = newJszip.folder("test");
if(folder.file("test.txt").asText() == "test string") {
folder.file("test.txt").async('text').then(function(text: string) {
if (text == "test string") {
log(SEVERITY.INFO, "all ok");
}
else {
} else {
log(SEVERITY.ERROR, "wrong file");
}
}).catch((e: any) => log(SEVERITY.ERROR, e));
var folders = newJszip.folder(new RegExp("^test"));
if(folders.length == 1) {
if (folders.length == 1) {
log(SEVERITY.INFO, "all ok");
if(folders[0].dir == true) {
if (folders[0].dir == true) {
log(SEVERITY.INFO, "all ok");
}
else {
} else {
log(SEVERITY.ERROR, "wrong file");
}
} else {
@ -51,67 +77,50 @@ function testJSZip() {
}
var files = newJszip.file(new RegExp("^test"));
if(files.length == 2) {
if (files.length == 2) {
log(SEVERITY.INFO, "all ok");
if (files[0].asText() == "test string" && files[1].asText() == "test string") {
Promise.all([files[0].async('text'), files[1].async('text')]).then(function(texts: string[]) {
if (texts[0] == "test string" && texts[1] == 'test string') {
log(SEVERITY.INFO, "all ok");
}
else {
} else {
log(SEVERITY.ERROR, "wrong data in files");
}
}
else {
});
} else {
log(SEVERITY.ERROR, "wrong number of files");
}
var filterFiles = newJszip.filter((relativePath: string, file: JSZipObject) => {
if (file.asText() == "test string") {
filterWithFileAsync(newJszip, 'text', (relativePath: string, file: JSZipObject, text: string) => {
if (text == "test string") {
return true;
}
return false;
});
if(filterFiles.length == 2) {
}).then(function(filterFiles: JSZipObject[]) {
if (filterFiles.length == 2) {
log(SEVERITY.INFO, "all ok");
}
else {
} else {
log(SEVERITY.ERROR, "wrong number of files");
}
}).catch((e: any) => log(SEVERITY.ERROR, e));
}).catch((e: any)=> { console.error(e) });
}
function testJSZipRemove() {
var newJszip = createTestZip();
newJszip.remove("test/test.txt");
filterFiles = newJszip.filter((relativePath: string, file: JSZipObject) => {
if (file.asText() == "test string") {
filterWithFileAsync(newJszip, 'text', (relativePath: string, file: JSZipObject, text: string) => {
if (text == "test string") {
return true;
}
return false;
});
if(filterFiles.length == 1) {
}).then(function(filterFiles: JSZipObject[]) {
if (filterFiles.length == 1) {
log(SEVERITY.INFO, "all ok");
}
else {
} else {
log(SEVERITY.ERROR, "wrong number of files");
}
var uncompressedStr = JSZip.compressions.DEFLATE.uncompress(
JSZip.compressions.DEFLATE.compress("\0\1\2\3\4\5\6\7",{level:9}));
var uncompressedArr = JSZip.compressions.DEFLATE.uncompress(
JSZip.compressions.DEFLATE.compress([0,1,2,3,4,5,6,7],{level:9}));
var uncompressedUint8Arr = JSZip.compressions.DEFLATE.uncompress(
JSZip.compressions.DEFLATE.compress(new Uint8Array([0,1,2,3,4,5,6,7]),{level:9}));
var every_match = [0,1,2,3,4,5,6,7].every(function(val, i){
return uncompressedStr[i] === val &&
uncompressedArr[i] === val &&
uncompressedUint8Arr[i] === val;
});
if(every_match) {
log(SEVERITY.INFO, "compress and uncompress ok.");
}else{
log(SEVERITY.ERROR, "compress or uncompress failed.");
}
}).catch((e: any) => log(SEVERITY.ERROR, e));
}
function log(severity:number, message: any) {
@ -140,3 +149,4 @@ function log(severity:number, message: any) {
}
testJSZip();
testJSZipRemove();

View File

@ -28,7 +28,7 @@ export declare class HighLevelProducer {
}
export declare class Consumer {
constructor(client: Client, fetchRequests: Array<Topic>, options: ConsumerOptions);
constructor(client: Client, fetchRequests: Array<OffsetFetchRequest>, options: ConsumerOptions);
on(eventName: string, cb: (message: string) => any): void;
on(eventName: string, cb: (error: any) => any): void;
addTopics(topics: Array<string>, cb: (error: any, added: boolean) => any): void;

10
karma/index.d.ts vendored
View File

@ -25,6 +25,7 @@ declare namespace karma {
server: DeprecatedServer;
Server: Server;
runner: Runner;
stopper: Stopper;
launcher: Launcher;
VERSION: string;
}
@ -54,6 +55,15 @@ declare namespace karma {
run(options?: ConfigOptions | ConfigFile, callback?: ServerCallback): void;
}
interface Stopper {
/**
* This function will signal a running server to stop. The equivalent of karma stop.
*/
stop(options?: ConfigOptions, callback?: ServerCallback): void;
}
interface TestResults {
disconnected: boolean;
error: boolean;

View File

@ -28,6 +28,12 @@ karma.runner.run({port: 9876}, (exitCode: number) => {
process.exit(exitCode);
});
karma.stopper.stop({port: 9876}, function(exitCode) {
if (exitCode === 0) {
console.log('Server stop as initiated')
}
process.exit(exitCode)
});
//var Server = require('karma').Server; => cannot use this syntax otherwise Server is of type any
var server = new karma.Server({logLevel: 'debug', port: 9876}, function(exitCode: number) {

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