Merge pull request #1 from DefinitelyTyped/master

Merge with head fork.
This commit is contained in:
Steve
2015-12-11 09:01:59 +01:00
95 changed files with 15858 additions and 1412 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/borisyankov/DefinitelyTyped.png?branch=master)](https://travis-ci.org/borisyankov/DefinitelyTyped)
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.png?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
[![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+1 -1
View File
@@ -59,7 +59,7 @@ declare module angular.material {
show(dialog: MDDialogOptions|MDPresetDialog<any>): angular.IPromise<any>;
confirm(): MDConfirmDialog;
alert(): MDAlertDialog;
hide(response?: any): void;
hide(response?: any): angular.IPromise<any>;
cancel(response?: any): void;
}
+1 -1
View File
@@ -64,7 +64,7 @@ declare module angular.material {
show(dialog: MDDialogOptions|MDAlertDialog|MDConfirmDialog): angular.IPromise<any>;
confirm(): MDConfirmDialog;
alert(): MDAlertDialog;
hide(response?: any): void;
hide(response?: any): angular.IPromise<any>;
cancel(response?: any): void;
}
+1 -1
View File
@@ -83,7 +83,7 @@ declare module angular.material {
show(dialog: IDialogOptions|IAlertDialog|IConfirmDialog): angular.IPromise<any>;
confirm(): IConfirmDialog;
alert(): IAlertDialog;
hide(response?: any): void;
hide(response?: any): angular.IPromise<any>;
cancel(response?: any): void;
}
+378
View File
@@ -0,0 +1,378 @@
/// <reference path="../angularjs/angular.d.ts"/>
/// <reference path="./angular-strap.d.ts"/>
module angularStrapTests {
import ngStrap = mgcrea.ngStrap;
///////////////////////////////////////////////////////////////////////////
// Modal
///////////////////////////////////////////////////////////////////////////
module modalTests {
interface IDemoCtrlScope extends ngStrap.modal.IModalScope {
showModal: () => void;
}
angular.module('demoApp')
.config($modalConfig)
.controller('demoCtrl', demoCtrl);
function demoCtrl($scope: IDemoCtrlScope,
$modal: ngStrap.modal.IModalService): void {
var myModalOptions: ngStrap.modal.IModalOptions = {};
myModalOptions.title = 'My Title';
myModalOptions.content = 'Hello Modal<br />This is a multiline message!';
myModalOptions.show = true;
var myModal = $modal(myModalOptions);
var myOtherModalOptions: ngStrap.modal.IModalOptions = {};
myOtherModalOptions.scope = $scope;
myOtherModalOptions.template = 'modal/docs/modal.demo.tpl.html';
myOtherModalOptions.show = false;
var myOtherModal = $modal(myOtherModalOptions);
$scope.showModal = (): void => {
myOtherModal.$promise.then(myOtherModal.show);
};
}
function $modalConfig($modalProvider: ngStrap.modal.IModalProvider): void {
var defaults: ngStrap.modal.IModalOptions = {
animation: 'am-flip-x'
}
angular.extend($modalProvider.defaults, defaults);
}
}
///////////////////////////////////////////////////////////////////////////
// Aside
///////////////////////////////////////////////////////////////////////////
module asideTests {
angular.module('demoApp')
.config($asideConfig)
.controller('demoCtrl', demoCtrl);
function demoCtrl($scope: ngStrap.aside.IAsideScope,
$aside: ngStrap.aside.IAsideService): void {
var myAsideOptions: ngStrap.aside.IAsideOptions = {};
myAsideOptions.title = 'My Title';
myAsideOptions.content = 'My content';
myAsideOptions.show = true;
var myAside = $aside(myAsideOptions);
var myOtherAsideOptions: ngStrap.aside.IAsideOptions = {};
myOtherAsideOptions.scope = $scope;
myOtherAsideOptions.template = 'aside/docs/aside.demo.tpl.html';
var myOtherAside = $aside();
myOtherAside.$promise.then(() => {
myOtherAside.show();
});
}
function $asideConfig($asideProvider: ngStrap.aside.IAsideProvider): void {
var defaults: ngStrap.aside.IAsideOptions = {};
defaults.animation = 'am-fadeAndSlideLeft';
defaults.placement = 'left';
angular.extend($asideProvider.defaults, defaults);
}
}
///////////////////////////////////////////////////////////////////////////
// Alert
///////////////////////////////////////////////////////////////////////////
module alertTests {
angular.module('demoApp')
.config($alertConfig)
.controller('demoCtrl', demoCtrl);
function demoCtrl($scope: ngStrap.alert.IAlertScope,
$alert: ngStrap.alert.IAlertService): void {
var options: ngStrap.alert.IAlertOptions = {};
options.title = 'Holy guacamole!';
options.content = 'Best check yo self, you\'re not looking too good.';
options.placement = 'top';
options.type = 'info';
options.show = true;
var myAlert = $alert();
}
function $alertConfig($alertProvider: ngStrap.alert.IAlertProvider): void {
var defaults: ngStrap.alert.IAlertOptions = {};
defaults.animation = 'am-fade-and-slide-top';
defaults.placement = 'top';
angular.extend($alertProvider.defaults, defaults);
};
}
///////////////////////////////////////////////////////////////////////////
// Tooltip
///////////////////////////////////////////////////////////////////////////
module tooltipTests {
angular.module('demoApp')
.config($tooltipConfig)
.controller('demoDrct', demoDrct);
function demoDrct($tooltip: ngStrap.tooltip.ITooltipService): ng.IDirective {
var drct: ng.IDirective = {};
drct.restrict = 'EA';
drct.link = link;
return drct;
function link(scope: ng.IScope, elem: ng.IAugmentedJQuery, attrs: ng.IAttributes): void {
var options: ngStrap.tooltip.ITooltipOptions = {};
options.title = 'My Title';
$tooltip(elem, options);
}
}
function $tooltipConfig($tooltipProvider: ngStrap.tooltip.ITooltipProvider): void {
var defaults: ngStrap.tooltip.ITooltipOptions = {};
defaults.animation = 'am-flip-x';
defaults.trigger = 'hover';
angular.extend($tooltipProvider.defaults, defaults);
};
}
///////////////////////////////////////////////////////////////////////////
// Popover
///////////////////////////////////////////////////////////////////////////
module popoverTests {
angular.module('demoApp')
.config($popoverConfig)
.controller('demoDrct', demoDrct);
function demoDrct($popover: ngStrap.popover.IPopoverService): ng.IDirective {
var drct: ng.IDirective = {};
drct.restrict = 'EA';
drct.link = link;
return drct;
function link(scope: ng.IScope, elem: ng.IAugmentedJQuery, attrs: ng.IAttributes): void {
var options: ngStrap.tooltip.ITooltipOptions = {};
options.title = 'My Title';
$popover(elem, options);
}
}
function $popoverConfig($popoverProvider: ngStrap.popover.IPopoverProvider): void {
var defaults: ngStrap.tooltip.ITooltipOptions = {}
defaults.animation = 'am-flip-x';
defaults.trigger = 'hover';
angular.extend($popoverProvider.defaults, defaults);
};
}
///////////////////////////////////////////////////////////////////////////
// Typeahead
///////////////////////////////////////////////////////////////////////////
module typeaheadTests {
angular.module('myApp')
.config($typeaheadConfig);
function $typeaheadConfig($typeaheadProvider: ngStrap.typeahead.ITypeaheadProvider) {
var defaults: ngStrap.typeahead.ITypeaheadOptions = {}
defaults.animation = 'am-flip-x';
defaults.minLength = 2;
defaults.limit = 8;
angular.extend($typeaheadProvider.defaults, defaults);
}
}
///////////////////////////////////////////////////////////////////////////
// Datepicker
///////////////////////////////////////////////////////////////////////////
module datepickerTests {
angular.module('myApp')
.config($datepickerConfig);
function $datepickerConfig($datepickerProvider: ngStrap.datepicker.IDatepickerProvider): void {
var defaults: ngStrap.datepicker.IDatepickerOptions = {};
defaults.dateFormat = 'dd/MM/yyyy';
defaults.startWeek = 1;
angular.extend($datepickerProvider.defaults, defaults);
};
}
///////////////////////////////////////////////////////////////////////////
// Timepicker
///////////////////////////////////////////////////////////////////////////
module timepickerTests {
angular.module('myApp')
.config($timepickerConfig);
function $timepickerConfig($timepickerProvider: ngStrap.timepicker.ITimepickerProvider): void {
var defaults: ngStrap.timepicker.ITimepickerOptions = {};
defaults.timeFormat = 'HH:mm';
defaults.length = 7;
angular.extend($timepickerProvider.defaults, defaults);
};
}
///////////////////////////////////////////////////////////////////////////
// Select
///////////////////////////////////////////////////////////////////////////
module selectTests {
angular.module('myApp')
.config($selectConfig);
function $selectConfig($selectProvider: ngStrap.select.ISelectProvider): void {
var defaults: ngStrap.select.ISelectOptions = {};
defaults.animation = 'am-flip-x';
defaults.sort = false;
angular.extend($selectProvider.defaults, defaults);
}
}
///////////////////////////////////////////////////////////////////////////
// Tabs
///////////////////////////////////////////////////////////////////////////
module tabTests {
angular.module('myApp')
.config($tabConfig);
function $tabConfig($tabProvider: ngStrap.tab.ITabProvider) {
var defaults: ngStrap.tab.ITabOptions = {};
defaults.animation = 'am-flip-x';
angular.extend($tabProvider.defaults, defaults);
}
}
///////////////////////////////////////////////////////////////////////////
// Collapse
///////////////////////////////////////////////////////////////////////////
module collapseTests {
angular.module('myApp')
.config($collapseConfig);
function $collapseConfig($collapseProvider: ngStrap.collapse.ICollapseProvider):void {
var defaults: ngStrap.collapse.ICollapseOptions = {};
defaults.animation = 'am-flip-x';
angular.extend($collapseProvider.defaults, defaults);
}
}
///////////////////////////////////////////////////////////////////////////
// Dropdown
///////////////////////////////////////////////////////////////////////////
module dropdownTests {
angular.module('myApp')
.config($dropdownConfig);
function $dropdownConfig($dropdownProvider: ngStrap.dropdown.IDropdownProvider):void {
var defaults: ngStrap.dropdown.IDropdownOptions = {};
defaults.animation = 'am-flip-x';
defaults.trigger = 'hover';
angular.extend($dropdownProvider.defaults, defaults);
}
}
///////////////////////////////////////////////////////////////////////////
// Navbar
///////////////////////////////////////////////////////////////////////////
module navbarTests {
angular.module('myApp')
.config($navbarConfig);
function $navbarConfig($navbarProvider: ngStrap.navbar.INavbarProvider):void {
var defaults: ngStrap.navbar.INavbarOptions = {};
defaults.activeClass = 'in';
angular.extend($navbarProvider.defaults, defaults);
}
}
///////////////////////////////////////////////////////////////////////////
// Scrollspy
///////////////////////////////////////////////////////////////////////////
module scrollspyTests {
angular.module('myApp')
.config($scrollspyConfig);
function $scrollspyConfig($scrollspyProvider: ngStrap.scrollspy.IScrollspyProvider):void {
var defaults: ngStrap.scrollspy.IScrollspyOptions = {};
defaults.offset = 0;
defaults.target = 'my-selector';
angular.extend($scrollspyProvider.defaults, defaults);
}
}
///////////////////////////////////////////////////////////////////////////
// Affix
///////////////////////////////////////////////////////////////////////////
module affixTests {
angular.module('myApp')
.config($affixConfig);
function $affixConfig($affixProvider: ngStrap.affix.IAffixProvider):void {
var defaults: ngStrap.affix.IAffixOptions = {};
defaults.offsetTop = 100;
angular.extend($affixProvider.defaults, defaults);
}
}
}
+600
View File
@@ -0,0 +1,600 @@
// Type definitions for angular-strap v2.2.x
// Project: http://mgcrea.github.io/angular-strap/
// Definitions by: Sam Herrmann <https://github.com/samherrmann>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module mgcrea.ngStrap {
///////////////////////////////////////////////////////////////////////////
// Modal
// see http://mgcrea.github.io/angular-strap/#/modals
///////////////////////////////////////////////////////////////////////////
module modal {
interface IModalService {
(config?: IModalOptions): IModal;
}
interface IModalProvider {
defaults: IModalOptions;
}
interface IModal {
$promise: ng.IPromise<void>;
show: () => void;
hide: () => void;
toggle: () => void;
}
interface IModalOptions {
animation?: string;
backdropAnimation?: string;
placement?: string;
title?: string;
content?: string;
html?: boolean;
backdrop?: boolean | string;
keyboard?: boolean;
show?: boolean;
container?: string | boolean;
template?: string;
contentTemplate?: string;
prefixEvent?: string;
id?: string;
scope?: ng.IScope;
}
interface IModalScope extends ng.IScope {
$show: () => void;
$hide: () => void;
$toggle: () => void;
}
}
///////////////////////////////////////////////////////////////////////////
// Aside
// see http://mgcrea.github.io/angular-strap/#/asides
///////////////////////////////////////////////////////////////////////////
module aside {
interface IAsideService {
(config?: IAsideOptions): IAside;
}
interface IAsideProvider {
defaults: IAsideOptions;
}
interface IAside {
$promise: ng.IPromise<void>;
show: () => void;
hide: () => void;
toggle: () => void;
}
interface IAsideOptions {
animation?: string;
placement?: string;
title?: string;
content?: string;
html?: boolean;
backdrop?: boolean | string;
keyboard?: boolean;
show?: boolean;
container?: string | boolean;
template?: string;
contentTemplate?: string;
scope?: ng.IScope;
}
interface IAsideScope extends ng.IScope {
$show: () => void;
$hide: () => void;
$toggle: () => void;
}
}
///////////////////////////////////////////////////////////////////////////
// Alert
// see http://mgcrea.github.io/angular-strap/#/alerts
///////////////////////////////////////////////////////////////////////////
module alert {
interface IAlertService {
(config?: IAlertOptions): IAlert;
}
interface IAlertProvider {
defaults: IAlertOptions;
}
interface IAlert {
$promise: ng.IPromise<void>;
show: () => void;
hide: () => void;
toggle: () => void;
}
interface IAlertOptions {
animation?: string;
placement?: string;
title?: string;
content?: string;
type?: string;
keyboard?: boolean;
show?: boolean;
container?: string | boolean;
template?: string;
duration?: number | boolean;
dismissable?: boolean;
}
interface IAlertScope extends ng.IScope {
$show: () => void;
$hide: () => void;
$toggle: () => void;
}
}
///////////////////////////////////////////////////////////////////////////
// Tooltip
// see http://mgcrea.github.io/angular-strap/#/tooltips
///////////////////////////////////////////////////////////////////////////
module tooltip {
interface ITooltipService {
(element: ng.IAugmentedJQuery, config?: ITooltipOptions): ITooltip;
}
interface ITooltipProvider {
defaults: ITooltipOptions;
}
interface ITooltip {
$promise: ng.IPromise<void>;
show: () => void;
hide: () => void;
toggle: () => void;
}
interface ITooltipOptions {
animation?: string;
placement?: string;
trigger?: string;
title?: string;
html?: boolean;
delay?: number | { show: number; hide: number};
container?: string | boolean;
target?: string | ng.IAugmentedJQuery | boolean;
template?: string;
contentTemplate?: string;
prefixEvent?: string;
id?: string;
viewport?: string | { selector: string; padding: string | number };
}
interface ITooltipScope extends ng.IScope {
$show: () => void;
$hide: () => void;
$toggle: () => void;
$setEnabled: (isEnabled: boolean) => void;
}
}
///////////////////////////////////////////////////////////////////////////
// Popover
// see http://mgcrea.github.io/angular-strap/#/popovers
///////////////////////////////////////////////////////////////////////////
module popover {
interface IPopoverService {
(element: ng.IAugmentedJQuery, config?: IPopoverOptions): IPopover;
}
interface IPopoverProvider {
defaults: IPopoverOptions;
}
interface IPopover {
$promise: ng.IPromise<void>;
show: () => void;
hide: () => void;
toggle: () => void;
}
interface IPopoverOptions {
animation?: string;
placement?: string;
trigger?: string;
title?: string;
content?: string;
html?: boolean;
delay?: number | { show: number; hide: number };
container?: string | boolean;
target?: string | ng.IAugmentedJQuery | boolean;
template?: string;
contentTemplate?: string;
autoClose?: boolean;
id?: string;
viewport?: string | { selector: string; padding: string | number };
}
interface IPopoverScope extends ng.IScope {
$show: () => void;
$hide: () => void;
$toggle: () => void;
}
}
///////////////////////////////////////////////////////////////////////////
// Typeahead
// see http://mgcrea.github.io/angular-strap/#/typeaheads
///////////////////////////////////////////////////////////////////////////
module typeahead {
interface ITypeaheadService {
(element: ng.IAugmentedJQuery, controller: any, config?: ITypeaheadOptions): ITypeahead;
}
interface ITypeaheadProvider {
defaults: ITypeaheadOptions;
}
interface ITypeahead {
$promise: ng.IPromise<void>;
show: () => void;
hide: () => void;
toggle: () => void;
}
interface ITypeaheadOptions {
animation?: string;
placement?: string;
trigger?: string;
html?: boolean;
delay?: number | { show: number; hide: number };
container?: string | boolean;
template?: string;
limit?: number;
minLength?: number;
autoSelect?: boolean;
comparator?: string;
id?: string;
watchOptions?: boolean;
}
}
///////////////////////////////////////////////////////////////////////////
// Datepicker
// see http://mgcrea.github.io/angular-strap/#/datepickers
///////////////////////////////////////////////////////////////////////////
module datepicker {
interface IDatepickerService {
(element: ng.IAugmentedJQuery, controller: any, config?: IDatepickerOptions): IDatepicker;
}
interface IDatepickerProvider {
defaults: IDatepickerOptions;
}
interface IDatepicker {
update: (date: Date) => void;
updateDisabledDates: (dateRanges: IDatepickerDateRange[]) => void;
select: (dateConstructorArg: string | number | number[], keep: boolean) => void;
setMode: (mode: any) => void;
int: () => void;
destroy: () => void;
show: () => void;
hide: () => void;
}
interface IDatepickerDateRange {
start: Date;
end: Date;
}
interface IDatepickerOptions {
animation?: string;
placement?: string;
trigger?: string;
html?: boolean;
delay?: number | { show: number; hide: number };
container?: string | boolean;
template?: string;
dateFormat?: string;
modelDateFormat?: string;
dateType?: string;
timezone?: string;
autoclose?: boolean;
useNative?: boolean;
minDate?: Date;
maxDate?: Date;
startView?: number;
minView?: number;
startWeek?: number;
startDate?: Date;
iconLeft?: string;
iconRight?: string;
daysOfWeekDisabled?: string;
disabledDates?: IDatepickerDateRange[];
}
}
///////////////////////////////////////////////////////////////////////////
// Timepicker
// see http://mgcrea.github.io/angular-strap/#/timepickers
///////////////////////////////////////////////////////////////////////////
module timepicker {
interface ITimepickerService {
(element: ng.IAugmentedJQuery, controller: any, config?: ITimepickerOptions): ITimepicker;
}
interface ITimepickerProvider {
defaults: ITimepickerOptions;
}
interface ITimepicker {
}
interface ITimepickerOptions {
animation?: string;
placement?: string;
trigger?: string;
html?: boolean;
delay?: number | { show: number; hide: number; };
container?: string | boolean;
template?: string;
timeFormat?: string;
modelTimeFormat?: string;
timeType?: string;
autoclose?: boolean;
useNative?: boolean;
minTime?: Date; // TODO
maxTime?: Date; // TODO
length?: number;
hourStep?: number;
minuteStep?: number;
secondStep?: number;
roundDisplay?: boolean;
iconUp?: string;
iconDown?: string;
arrowBehaviour?: string;
}
}
///////////////////////////////////////////////////////////////////////////
// Button
// see http://mgcrea.github.io/angular-strap/#/buttons
///////////////////////////////////////////////////////////////////////////
// No definitions for this module
///////////////////////////////////////////////////////////////////////////
// Select
// see http://mgcrea.github.io/angular-strap/#/selects
///////////////////////////////////////////////////////////////////////////
module select {
interface ISelectService {
(element: ng.IAugmentedJQuery, controller: any, config: ISelectOptions): ISelect;
}
interface ISelectProvider {
defaults: ISelectOptions;
}
interface ISelect {
update: (matches: any) => void;
active: (index: number) => number;
select: (index: number) => void;
show: () => void;
hide: () => void;
}
interface ISelectOptions {
animation?: string;
placement?: string;
trigger?: string;
html?: boolean;
delay?: number | { show: number; hide: number; };
container?: string | boolean;
template?: string;
multiple?: boolean;
allNoneButtons?: boolean;
allText?: string;
noneText?: string;
maxLength?: number;
maxLengthHtml?: string;
sort?: boolean;
placeholder?: string;
iconCheckmark?: string;
id?: string;
}
}
///////////////////////////////////////////////////////////////////////////
// Tabs
// see http://mgcrea.github.io/angular-strap/#/tabs
///////////////////////////////////////////////////////////////////////////
module tab {
interface ITabProvider {
defaults: ITabOptions;
}
interface ITabService {
defaults: ITabOptions;
controller: any;
}
interface ITabOptions {
animation?: string;
template?: string;
navClass?: string;
activeClass?: string;
}
}
///////////////////////////////////////////////////////////////////////////
// Collapses
// see http://mgcrea.github.io/angular-strap/#/collapses
///////////////////////////////////////////////////////////////////////////
module collapse {
interface ICollapseProvider {
defaults: ICollapseOptions;
}
interface ICollapseOptions {
animation?: string;
activeClass?: string;
disallowToggle?: boolean;
startCollapsed?: boolean;
allowMultiple?: boolean;
}
}
///////////////////////////////////////////////////////////////////////////
// Dropdowsn
// see http://mgcrea.github.io/angular-strap/#/dropdowns
///////////////////////////////////////////////////////////////////////////
module dropdown {
interface IDropdownProvider {
defaults: IDropdownOptions;
}
interface IDropdownService {
(element: ng.IAugmentedJQuery, config: IDropdownOptions): IDropdown;
}
interface IDropdown {
show: () => void;
hide: () => void;
destroy: () => void;
}
interface IDropdownOptions {
animation?: string;
placement?: string;
trigger?: string;
html?: boolean;
delay?: number | { show: number; hide: number; };
container?: string | boolean;
template?: string;
}
}
///////////////////////////////////////////////////////////////////////////
// Navbar
// see http://mgcrea.github.io/angular-strap/#/navbars
///////////////////////////////////////////////////////////////////////////
module navbar {
interface INavbarProvider {
defaults: INavbarOptions;
}
interface INavbarOptions {
activeClass?: string;
routeAttr?: string;
}
interface INavbarService {
defaults: INavbarOptions;
}
}
///////////////////////////////////////////////////////////////////////////
// Scrollspy
// see http://mgcrea.github.io/angular-strap/#/scrollspy
///////////////////////////////////////////////////////////////////////////
module scrollspy {
interface IScrollspyProvider {
defaults: IScrollspyOptions;
}
interface IScrollspyService {
(element: ng.IAugmentedJQuery, options: IScrollspyOptions): IScrollspy;
}
interface IScrollspy {
checkOffsets: () => void;
trackElement: (target: any, source: any) => void;
untrackElement: (target: any, source: any) => void;
activate: (index: number) => void;
}
interface IScrollspyOptions {
target?: string;
offset?: number;
}
}
///////////////////////////////////////////////////////////////////////////
// Affix
// see http://mgcrea.github.io/angular-strap/#/affix
///////////////////////////////////////////////////////////////////////////
module affix {
interface IAffixProvider {
defaults: IAffixOptions;
}
interface IAffixService {
(element: ng.IAugmentedJQuery, options: IAffixOptions): IAffix;
}
interface IAffix {
init: () => void;
destroy: () => void;
checkPositionWithEventLoop: () => void;
checkPosition: () => void;
}
interface IAffixOptions {
offsetTop?: number;
offsetBottom?: number;
offsetParent?: number;
offsetUnpin?: number;
}
}
}
@@ -36,4 +36,9 @@ app.controller('Ctrl', ($scope: Scope, $translate: angular.translate.ITranslateS
$scope['changeLanguage'] = function (key: any) {
$translate.use(key);
};
}).run(($filter: ng.IFilterService) => {
var x: string;
x = $filter('translate')('something');
x = $filter('translate')('something', {});
x = $filter('translate')('something', {}, '');
});
+8
View File
@@ -108,3 +108,11 @@ declare module angular.translate {
useLoaderCache(cache?: any): ITranslateProvider;
}
}
declare module angular {
interface IFilterService {
(name:'translate'): {
(translationId: string, interpolateParams?: any, interpolation?: string): string;
};
}
}
+20 -3
View File
@@ -5,10 +5,27 @@
/// <reference path="../angularjs/angular.d.ts" />
// Support for AMD require
// Support for AMD require and CommonJS
declare module 'angular-ui-router' {
var _: string;
export = _;
// Since angular-ui-router adds providers for a bunch of
// injectable dependencies, it doesn't really return any
// actual data except the plain string 'ui.router'.
//
// As such, I don't think anybody will ever use the actual
// default value of the module. So I've only included the
// the types. (@xogeny)
export type IState = angular.ui.IState;
export type IStateProvider = angular.ui.IStateProvider;
export type IUrlMatcher = angular.ui.IUrlMatcher;
export type IUrlRouterProvider = angular.ui.IUrlRouterProvider;
export type IStateOptions = angular.ui.IStateOptions;
export type IHrefOptions = angular.ui.IHrefOptions;
export type IStateService = angular.ui.IStateService;
export type IResolvedState = angular.ui.IResolvedState;
export type IStateParamsService = angular.ui.IStateParamsService;
export type IUrlRouterService = angular.ui.IUrlRouterService;
export type IUiViewScrollProvider = angular.ui.IUiViewScrollProvider;
export type IType = angular.ui.IType;
}
declare module angular.ui {
+69
View File
@@ -11,3 +11,72 @@ var treeNode2: AngularUITree.ITreeNode = {
nodes: [treeNode],
title: "test2"
};
// fake jquery node here so that we can pull a pretend
// angular scope element out of it
var dummyJQueryNode: ng.IAugmentedJQuery;
var fakeScope: (ng.IScope | AngularUITree.IParentTreeNodeScope) = dummyJQueryNode.scope();
(<AngularUITree.ITreeNodeScope> fakeScope).node = treeNode;
var treeNodeScope: AngularUITree.ITreeNodeScope = <AngularUITree.ITreeNodeScope> fakeScope;
(<AngularUITree.IParentTreeNodeScope> fakeScope).isParent = (nodeScope: AngularUITree.ITreeNodeScope) => {
return true;
};
var parentTreeNodeScope: AngularUITree.IParentTreeNodeScope = <AngularUITree.IParentTreeNodeScope> fakeScope;
var eventSourceInfo: AngularUITree.IEventSourceInfo = {
cloneModel: {},
nodeScope: treeNodeScope,
index: 0,
nodesScope: parentTreeNodeScope
};
var position: AngularUITree.IPosition = {
dirAx: 0,
dirX: 0,
dirY: 0,
distAxX: 0,
distAxY: 0,
distX: 0,
distY: 0,
lastDirX: 0,
lastDirY: 0,
lastX: 0,
lastY: 0,
moving: true,
nowX: 0,
nowY: 0,
offsetX: 0,
offsetY: 0,
startX: 0,
startY: 0
};
var eventInfo: AngularUITree.IEventInfo = {
source: eventSourceInfo,
dest: {
index: 0,
nodesScope: parentTreeNodeScope
},
elements: {},
pos: position
};
var acceptCallback: AngularUITree.IAcceptCallback = (source: AngularUITree.ITreeNodeScope,
destination: AngularUITree.ITreeNodeScope,
destinationIndex: number) => {
return false;
};
var droppedCallback: AngularUITree.IDroppedCallback = (eventInfo: AngularUITree.IEventInfo) => {
return;
};
var callbacks: AngularUITree.ICallbacks = {
accept: acceptCallback,
dropped: droppedCallback
};
+64
View File
@@ -3,7 +3,71 @@
// Definitions by: Calvin Fernandez <https://github.com/CalvinFernandez>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path='../angularjs/angular.d.ts' />
declare module AngularUITree {
interface IEventSourceInfo {
cloneModel: any;
index: number;
nodeScope: ITreeNodeScope;
nodesScope: ITreeNodeScope;
}
interface IPosition {
dirAx: number;
dirX: number;
dirY: number;
distAxX: number;
distAxY: number;
distX: number;
distY: number;
lastDirX: number;
lastDirY: number;
lastX: number;
lastY: number;
moving: boolean;
nowX: number;
nowY: number;
offsetX: number;
offsetY: number;
startX: number;
startY: number;
}
interface IEventInfo {
dest: {
index: number;
nodesScope: IParentTreeNodeScope;
};
elements: any;
pos: IPosition;
source: IEventSourceInfo;
}
interface IAcceptCallback {
(source: ITreeNodeScope, destination: ITreeNodeScope, destinationIndex: number): boolean;
}
interface IDroppedCallback {
(eventInfo: IEventInfo): void;
}
interface ICallbacks {
accept: IAcceptCallback;
dropped: IDroppedCallback;
}
/**
* Internal representation of node in the UI
*/
interface ITreeNodeScope extends ng.IScope {
node: ITreeNode;
}
interface IParentTreeNodeScope extends ITreeNodeScope {
isParent(nodeScope: ITreeNodeScope): boolean;
}
/**
* Node in list
*/
+5
View File
@@ -89,6 +89,9 @@ resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () {
var promise : angular.IPromise<IMyResource>;
var arrayPromise : angular.IPromise<IMyResource[]>;
var json: {
[index: string]: any;
};
promise = resource.$delete();
promise = resource.$delete({ key: 'value' });
@@ -127,6 +130,8 @@ promise = resource.$save(function () { });
promise = resource.$save(function () { }, function () { });
promise = resource.$save({ key: 'value' }, function () { }, function () { });
json = resource.toJSON();
///////////////////////////////////////
// IResourceService
///////////////////////////////////////
+3
View File
@@ -136,6 +136,9 @@ declare module angular.resource {
/** the promise of the original server interaction that created this instance. **/
$promise : angular.IPromise<T>;
$resolved : boolean;
toJSON: () => {
[index: string]: any;
}
}
/**
+10
View File
@@ -35,6 +35,16 @@ declare module angular.route {
// May not always be available. For instance, current will not be available
// to a controller that was not initialized as a result of a route maching.
current?: ICurrentRoute;
/**
* Causes $route service to update the current URL, replacing current route parameters with those specified in newParams.
* Provided property names that match the route's path segment definitions will be interpolated into the
* location's path, while remaining properties will be treated as query params.
*
* @param newParams Object.<string, string> mapping of URL parameter names to values
*/
updateParams(newParams:{[key:string]:string}): void;
}
+2
View File
@@ -72,6 +72,8 @@ interface Auth0LockStatic {
hide(callback: () => void): void;
logout(callback: () => void): void;
getClient(): Auth0Static;
}
declare var Auth0Lock: Auth0LockStatic;
+5
View File
@@ -200,4 +200,9 @@ declare module BigJsLibrary {
}
}
declare module "big.js" {
var bigjs : BigJsLibrary.BigJS;
export = bigjs;
}
declare var Big: BigJsLibrary.BigJS;
@@ -54,6 +54,8 @@ declare module BootstrapV3DatetimePicker {
showTodayButton?: boolean;
viewMode?: string;
inline?: boolean;
toolbarPlacement?: string;
showClear?: boolean;
}
interface Datetimepicker {
+1
View File
@@ -0,0 +1 @@
--target es5 --noImplicitAny --module commonjs
+102
View File
@@ -0,0 +1,102 @@
/**
* Created by Bruno Grieder
*/
///<reference path="./bull.d.ts" />
import * as Queue from "bull"
var videoQueue = Queue( 'video transcoding', 6379, '127.0.0.1' );
var audioQueue = Queue( 'audio transcoding', 6379, '127.0.0.1' );
var imageQueue = Queue( 'image transcoding', 6379, '127.0.0.1' );
videoQueue.process( ( job: Queue.Job, done: Queue.DoneCallback ) => {
// job.data contains the custom data passed when the job was created
// job.jobId contains id of this job.
// transcode video asynchronously and report progress
job.progress( 42 );
// call done when finished
done();
// or give a error if error
done( Error( 'error transcoding' ) );
// or pass it a result
done( null, { framerate: 29.5 /* etc... */ } );
// If the job throws an unhandled exception it is also handled correctly
throw (Error( 'some unexpected error' ));
} );
audioQueue.process( ( job: Queue.Job, done: Queue.DoneCallback ) => {
// transcode audio asynchronously and report progress
job.progress( 42 );
// call done when finished
done();
// or give a error if error
done( Error( 'error transcoding' ) );
// or pass it a result
done( null, { samplerate: 48000 /* etc... */ } );
// If the job throws an unhandled exception it is also handled correctly
throw (Error( 'some unexpected error' ));
} );
imageQueue.process( ( job: Queue.Job, done: Queue.DoneCallback ) => {
// transcode image asynchronously and report progress
job.progress( 42 );
// call done when finished
done();
// or give a error if error
done( Error( 'error transcoding' ) );
// or pass it a result
done( null, { width: 1280, height: 720 /* etc... */ } );
// If the job throws an unhandled exception it is also handled correctly
throw (Error( 'some unexpected error' ));
} );
videoQueue.add( { video: 'http://example.com/video1.mov' } );
audioQueue.add( { audio: 'http://example.com/audio1.mp3' } );
imageQueue.add( { image: 'http://example.com/image1.tiff' } );
//////////////////////////////////////////////////////////////////////////////////
//
// Using Promises
//
//////////////////////////////////////////////////////////////////////////////////
const fetchVideo = ( url: string ): Promise<any> => { return null }
const transcodeVideo = ( data: any ): Promise<void> => { return null }
interface VideoJob extends Queue.Job {
data: {url: string}
}
videoQueue.process( ( job: VideoJob ) => { // don't forget to remove the done callback!
// Simply return a promise
return fetchVideo( job.data.url ).then( transcodeVideo );
// Handles promise rejection
return Promise.reject( new Error( 'error transcoding' ) );
// Passes the value the promise is resolved with to the "completed" event
return Promise.resolve( { framerate: 29.5 /* etc... */ } );
// If the job throws an unhandled exception it is also handled correctly
throw new Error( 'some unexpected error' );
// same as
return Promise.reject( new Error( 'some unexpected error' ) );
} );
+311
View File
@@ -0,0 +1,311 @@
// Type definitions for bull 0.7.0
// Project: https://github.com/OptimalBits/bull
// Definitions by: Bruno Grieder <https://github.com/bgrieder>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../redis/redis.d.ts" />
/// <reference path="../es6-promise/es6-promise.d.ts" />
declare module "bull" {
import * as Redis from "redis";
/**
* This is the Queue constructor.
* It creates a new Queue that is persisted in Redis.
* Everytime the same queue is instantiated it tries to process all the old jobs that may exist from a previous unfinished session.
*/
function Bull(queueName: string, redisPort: number, redisHost: string, redisOpt?: Redis.ClientOpts): Bull.Queue;
module Bull {
export interface DoneCallback {
(error?: Error, value?: any): void
}
export interface Job {
id: string
/**
* The custom data passed when the job was created
*/
data: Object;
/**
* Report progress on a job
*/
progress(value: any): Promise<void>;
/**
* Removes a Job from the queue from all the lists where it may be included.
* @returns {Promise} A promise that resolves when the job is removed.
*/
remove(): Promise<void>;
/**
* Rerun a Job that has failed.
* @returns {Promise} A promise that resolves when the job is scheduled for retry.
*/
retry(): Promise<void>;
}
export interface Backoff {
/**
* Backoff type, which can be either `fixed` or `exponential`
*/
type: string
/**
* Backoff delay, in milliseconds
*/
delay: number;
}
export interface AddOptions {
/**
* An amount of miliseconds to wait until this job can be processed.
* Note that for accurate delays, both server and clients should have their clocks synchronized
*/
delay?: number;
/**
* A number of attempts to retry if the job fails [optional]
*/
attempts?: number;
/**
* Backoff setting for automatic retries if the job fails
*/
backoff?: number | Backoff
/**
* A boolean which, if true, adds the job to the right
* of the queue instead of the left (default false)
*/
lifo?: boolean;
/**
* The number of milliseconds after which the job should be fail with a timeout error
*/
timeout?: number;
}
export interface Queue {
/**
* Defines a processing function for the jobs placed into a given Queue.
*
* The callback is called everytime a job is placed in the queue.
* It is passed an instance of the job as first argument.
*
* The done callback can be called with an Error instance, to signal that the job did not complete successfully,
* or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful.
* Errors will be passed as a second argument to the "failed" event;
* results, as a second argument to the "completed" event.
*
* concurrency: Bull will then call you handler in parallel respecting this max number.
*/
process(concurrency: number, callback: (job: Job, done: DoneCallback) => void): void;
/**
* Defines a processing function for the jobs placed into a given Queue.
*
* The callback is called everytime a job is placed in the queue.
* It is passed an instance of the job as first argument.
*
* The done callback can be called with an Error instance, to signal that the job did not complete successfully,
* or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful.
* Errors will be passed as a second argument to the "failed" event;
* results, as a second argument to the "completed" event.
*/
process(callback: (job: Job, done: DoneCallback) => void): void;
/**
* Defines a processing function for the jobs placed into a given Queue.
*
* The callback is called everytime a job is placed in the queue.
* It is passed an instance of the job as first argument.
*
* A promise must be returned to signal job completion.
* If the promise is rejected, the error will be passed as a second argument to the "failed" event.
* If it is resolved, its value will be the "completed" event's second argument.
*
* concurrency: Bull will then call you handler in parallel respecting this max number.
*/
process(concurrency: number, callback: (job: Job) => void): Promise<any>;
/**
* Defines a processing function for the jobs placed into a given Queue.
*
* The callback is called everytime a job is placed in the queue.
* It is passed an instance of the job as first argument.
*
* A promise must be returned to signal job completion.
* If the promise is rejected, the error will be passed as a second argument to the "failed" event.
* If it is resolved, its value will be the "completed" event's second argument.
*/
process(callback: (job: Job) => void): Promise<any>;
// process(callback: (job: Job, done?: DoneCallback) => void): Promise<any>;
/**
* Creates a new job and adds it to the queue.
* If the queue is empty the job will be executed directly,
* otherwise it will be placed in the queue and executed as soon as possible.
*/
add(data: Object, opts?: AddOptions): Promise<Job>;
/**
* Returns a promise that resolves when the queue is paused.
* The pause is global, meaning that all workers in all queue instances for a given queue will be paused.
* A paused queue will not process new jobs until resumed,
* but current jobs being processed will continue until they are finalized.
*
* Pausing a queue that is already paused does nothing.
*/
pause(): Promise<void>;
/**
* Returns a promise that resolves when the queue is resumed after being paused.
* The resume is global, meaning that all workers in all queue instances for a given queue will be resumed.
*
* Resuming a queue that is not paused does nothing.
*/
resume(): Promise<void>;
/**
* Returns a promise that returns the number of jobs in the queue, waiting or paused.
* Since there may be other processes adding or processing jobs, this value may be true only for a very small amount of time.
*/
count(): Promise<number>;
/**
* Empties a queue deleting all the input lists and associated jobs.
*/
empty(): Promise<void>;
/**
* Closes the underlying redis client. Use this to perform a graceful shutdown.
*
* `close` can be called from anywhere, with one caveat:
* if called from within a job handler the queue won't close until after the job has been processed
*/
close(): Promise<void>;
/**
* Returns a promise that will return the job instance associated with the jobId parameter.
* If the specified job cannot be located, the promise callback parameter will be set to null.
*/
getJob(jobId: string): Promise<Job>;
/**
* Tells the queue remove all jobs created outside of a grace period in milliseconds.
* You can clean the jobs with the following states: completed, waiting, active, delayed, and failed.
*/
clean(gracePeriod: number, jobsState?: string): Promise<Job[]>;
/**
* Listens to queue events
* 'ready', 'error', 'activ', 'progress', 'completed', 'failed', 'paused', 'resumed', 'cleaned'
*/
on(eventName: string, callback: EventCallback): void;
}
interface EventCallback {
(...args: any[]): void
}
interface ReadyEventCallback extends EventCallback {
(): void;
}
interface ErrorEventCallback extends EventCallback {
(error: Error): void;
}
interface JobPromise {
/**
* Abort this job
*/
cancel(): void
}
interface ActiveEventCallback extends EventCallback {
(job: Job, jobPromise: JobPromise): void;
}
interface ProgressEventCallback extends EventCallback {
(job: Job, progress: any): void;
}
interface CompletedEventCallback extends EventCallback {
(job: Job, result: Object): void;
}
interface FailedEventCallback extends EventCallback {
(job: Job, error: Error): void;
}
interface PausedEventCallback extends EventCallback {
(): void;
}
interface ResumedEventCallback extends EventCallback {
(job?: Job): void;
}
/**
* @see clean() for details
*/
interface CleanedEventCallback extends EventCallback {
(jobs: Job[], type: string): void;
}
}
export = Bull;
}
declare module "bull/lib/priority-queue" {
import * as Bull from "bull";
import * as Redis from "redis";
/**
* This is the Queue constructor of priority queue.
*
* It works same a normal queue, with same function and parameters.
* The only difference is that the Queue#add() allow an options opts.priority
* that could take ["low", "normal", "medium", "hight", "critical"]. If no options provider, "normal" will be taken.
*
* The priority queue will process more often highter priority jobs than lower.
*/
function PQueue(queueName: string, redisPort: number, redisHost: string, redisOpt?: Redis.ClientOpts): PQueue.PriorityQueue;
module PQueue {
export interface AddOptions extends Bull.AddOptions {
/**
* "low", "normal", "medium", "high", "critical"
*/
priority?: string;
}
export interface PriorityQueue extends Bull.Queue {
/**
* Creates a new job and adds it to the queue.
* If the queue is empty the job will be executed directly,
* otherwise it will be placed in the queue and executed as soon as possible.
*/
add(data: Object, opts?: PQueue.AddOptions): Promise<Bull.Job>;
}
}
export = PQueue;
}
+128
View File
@@ -0,0 +1,128 @@
/// <reference path="chai-string.d.ts" />
/// <reference path="../mocha/mocha.d.ts" />
/// <reference path="../node/node.d.ts" />
var should = chai.should();
var assert = chai.assert;
var expect = chai.expect;
var chai_string = require('chai-string');
chai.use(chai_string);
describe('chai-string', function() {
describe('#startsWith', function() {
it('check that', function() {
var obj = { foo: 'hello world' };
expect(obj).to.have.property('foo').that.startsWith('hello');
});
});
describe('#startWith', function() {
it('should return true', function() {
var str = 'abcdef',
prefix = 'abc';
str.should.startWith(prefix);
});
it('should return false', function() {
var str = 'abcdef',
prefix = 'cba';
str.should.not.startWith(prefix);
});
});
describe('#endWith', function() {
it('should return true', function() {
var str = 'abcdef',
suffix = 'def';
str.should.endWith(suffix);
});
it('should return false', function() {
var str = 'abcdef',
suffix = 'fed';
str.should.not.endWith(suffix);
});
});
describe('tdd alias', function() {
beforeEach(function() {
this.str = 'abcdef';
this.str2 = 'a\nb\tc\r d ef';
});
it('.startsWith', function() {
assert.startsWith(this.str, 'abc');
});
it('.notStartsWith', function() {
assert.notStartsWith(this.str, 'cba');
});
it('.endsWith', function() {
assert.endsWith(this.str, 'def');
});
it('.notEndsWith', function() {
assert.notEndsWith(this.str, 'fed');
});
it('.equalIgnoreCase', function() {
assert.equalIgnoreCase(this.str, 'AbCdEf');
});
it('.notEqualIgnoreCase', function() {
assert.notEqualIgnoreCase(this.str, 'abDDD');
});
it('.equalIgnoreSpaces', function() {
assert.equalIgnoreSpaces(this.str, this.str2);
});
it('.notEqualIgnoreSpaces', function() {
assert.notEqualIgnoreSpaces(this.str, this.str2 + 'g');
});
it('.singleLine', function() {
assert.singleLine(this.str);
});
it('.notSingleLine', function() {
assert.notSingleLine("abc\ndef");
});
it('.reverseOf', function() {
assert.reverseOf(this.str, 'fedcba');
});
it('.notReverseOf', function() {
assert.notReverseOf(this.str, 'aaaaa');
});
it('.palindrome', function() {
assert.palindrome('abcba');
assert.palindrome('abccba');
assert.palindrome('');
});
it('.notPalindrome', function() {
assert.notPalindrome(this.str);
});
it('.entriesCount', function() {
assert.entriesCount('abcabd', 'ab', 2);
assert.entriesCount('ababd', 'ab', 2);
assert.entriesCount('abab', 'ab', 2);
assert.entriesCount('', 'ab', 0);
});
});
});
+45
View File
@@ -0,0 +1,45 @@
// Type definitions for chai-string 1.1.4
// Project: https://github.com/onechiporenko/chai-string
// Definitions by: Nick Malaguti <https://github.com/nmalaguti/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../chai/chai.d.ts" />
declare module Chai {
interface Assertion extends LanguageChains, NumericComparison, TypeComparison {
startsWith(expected: string, message?: string): Assertion;
startWith(expected: string, message?: string): Assertion;
endsWith(expected: string, message?: string): Assertion;
endWith(expected: string, message?: string): Assertion;
equalIgnoreCase(expected: string, message?: string): Assertion;
equalIgnoreSpaces(expected: string, message?: string): Assertion;
singleLine(message?: string): Assertion;
reverseOf(message?: string): Assertion;
palindrome(message?: string): Assertion;
entriesCount(substr: string, expected: number, message?: string): Assertion;
}
export interface Assert {
startsWith(val: string, exp: string, msg?: string): void;
notStartsWith(val: string, exp: string, msg?: string): void;
endsWith(val: string, exp: string, msg?: string): void;
notEndsWith(val: string, exp: string, msg?: string): void;
equalIgnoreCase(val: string, exp: string, msg?: string): void;
notEqualIgnoreCase(val: string, exp: string, msg?: string): void;
equalIgnoreSpaces(val: string, exp: string, msg?: string): void;
notEqualIgnoreSpaces(val: string, exp: string, msg?: string): void;
singleLine(val: string, msg?: string): void;
notSingleLine(val: string, msg?: string): void;
reverseOf(val: string, exp: string, msg?: string): void;
notReverseOf(val: string, exp: string, msg?: string): void;
palindrome(val: string, msg?: string): void;
notPalindrome(val: string, msg?: string): void;
entriesCount(str: string, substr: string, count: number, msg?: string): void;
}
}
declare module 'chai-string' {
function chaiString(chai: any, utils: any): void;
namespace chaiString {}
export = chaiString;
}
+59
View File
@@ -0,0 +1,59 @@
/// <reference path="chai-things.d.ts" />
import chai = require('chai');
import chaiThings = require('chai-things');
chai.use(chaiThings);
function test_somethingSyntax() {
[].should.not.include.something();
[].should.not.include.something.that.equals(1);
var array = [{ a: 1 }, { b: 2 }];
array.should.include.something();
array.should.include.something.that.deep.equals({ b: 2 });
array.should.include.something.that.not.deep.equals({ b: 2 });
array.should.not.include.something.that.deep.equals({ c: 3 });
array.should.include.something.that.not.deep.equals({ c: 3 });
array.should.include.something.with.property('b', 2);
array.should.not.include.something.with.property('b', 3);
var array2 = [{ a: 'b' }, { a: 'b' }];
array2.should.include.something.that.have.property("a");
array2.should.include.something.that.have.property("a").not.equal("d");
}
function test_somethingVariantsSyntax() {
[].should.not.include.any();
[].should.not.include.any.that.deep.equal({ b: 2 });
var array = [{ a: 1 }, { b: 2 }];
array.should.include.a.thing();
array.should.include.a.thing.that.deep.equals({ b: 2 });
array.should.include.an.item();
array.should.include.an.item.that.deep.equals({ b: 2 });
array.should.include.one.that.deep.equals({ b: 2 });
array.should.include.some();
array.should.include.some.that.deep.equal({ b: 2 });
}
function test_allSyntax() {
[].should.all.equal(1);
[].should.all.not.equal(1);
var array = [1, 1];
array.should.all.equal(1);
array.should.all.not.equal(2);
array.should.not.all.equal(2);
array.should.not.all.not.equal(1);
var array2 = [1, 2];
array2.should.not.all.equal(1);
array2.should.not.all.equal(2);
array2.should.not.all.not.equal(1);
array2.should.not.all.not.equal(2);
var array3 = [{ a: 'b' }, { a: 'c' }];
array3.should.all.have.property("a");
array3.should.all.have.property("a").not.equal("d");
}
+55
View File
@@ -0,0 +1,55 @@
// Type definitions for chai-things
// Project: https://github.com/chaijs/chai-things
// Definitions by: David Broder-Rodgers <https://github.com/DavidBR-SW/>
// Definitions: https://github.com/DavidBR-SW/DefinitelyTyped
/// <reference path="../chai/chai.d.ts" />
declare module Chai {
interface ArrayAssertion {
include: ArrayInclude;
contain: ArrayInclude;
not: ArrayAssertion;
all: Assertion;
}
interface ArrayInclude {
(item: any): any;
a: Item;
an: Item;
one: Something;
some: Something;
something: Something;
any: Anything;
}
interface Anything extends Assertion {
(): any;
that: Assertion
with: Assertion
}
interface Something extends Assertion {
(): any;
that: Assertion
with: Assertion
}
interface Item {
item: Something;
thing: Something;
}
interface Deep {
equals: Equal;
}
}
interface Array<T> {
should: Chai.ArrayAssertion;
}
declare module "chai-things" {
function chaiThings(chai: any, utils: any): void;
export = chaiThings;
}
+1 -1
View File
@@ -19,7 +19,7 @@ declare module Chai {
use(fn: (chai: any, utils: any) => void): any;
assert: AssertStatic;
config: Config;
AssertionError: AssertionError;
AssertionError: typeof AssertionError;
}
export interface ExpectStatic extends AssertionStatic {
+8
View File
@@ -254,3 +254,11 @@ function testOptionsPage() {
});
}
chrome.storage.sync.get("myKey", function (loadedData) {
var myValue: { x: number } = loadedData["myKey"];
});
chrome.storage.onChanged.addListener(function (changes) {
var myNewValue: { x: number } = changes["myKey"].newValue;
var myOldValue: { x: number } = changes["myKey"].oldValue;
});
+29 -28
View File
@@ -1,6 +1,6 @@
// Type definitions for Chrome extension development
// Project: http://developer.chrome.com/extensions/
// Definitions by: Matthew Kimber <https://github.com/matthewkimber>, otiai10 <https://github.com/otiai10>, couven92 <https://gitbus.com/couven92>
// Definitions by: Matthew Kimber <https://github.com/matthewkimber>, otiai10 <https://github.com/otiai10>, couven92 <https://github.com/couven92>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path='../webrtc/MediaStream.d.ts'/>
@@ -5866,13 +5866,13 @@ declare module chrome.sessions {
* @since Chrome 20.
*/
declare module chrome.storage {
interface StorageArea {
interface StorageArea {
/**
* Gets the amount of space (in bytes) being used by one or more items.
* @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set).
* Parameter bytesInUse: Amount of space being used in storage, in bytes.
*/
getBytesInUse(callback: (bytesInUse: number) => void): void;
getBytesInUse(callback: (bytesInUse: number) => void): void;
/**
* Gets the amount of space (in bytes) being used by one or more items.
* @param key A single key to get the total usage for. Pass in null to get the total usage of all of storage.
@@ -5886,11 +5886,11 @@ declare module chrome.storage {
* @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set).
* Parameter bytesInUse: Amount of space being used in storage, in bytes.
*/
getBytesInUse(keys: string[], callback: (bytesInUse: number) => void): void;
getBytesInUse(keys: string[], callback: (bytesInUse: number) => void): void;
/**
* Removes all items from storage.
* @param callback Optional.
* Callback on success, or on failure (in which case runtime.lastError will be set).
* Callback on success, or on failure (in which case runtime.lastError will be set).
*/
clear(callback?: () => void): void;
/**
@@ -5905,14 +5905,14 @@ declare module chrome.storage {
* Removes one item from storage.
* @param key A single key for items to remove.
* @param callback Optional.
* Callback on success, or on failure (in which case runtime.lastError will be set).
* Callback on success, or on failure (in which case runtime.lastError will be set).
*/
remove(key: string, callback?: () => void): void;
/**
* Removes items from storage.
* @param keys A list of keys for items to remove.
* @param callback Optional.
* Callback on success, or on failure (in which case runtime.lastError will be set).
* Callback on success, or on failure (in which case runtime.lastError will be set).
*/
remove(keys: string[], callback?: () => void): void;
/**
@@ -5920,77 +5920,78 @@ declare module chrome.storage {
* @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set).
* Parameter items: Object with items in their key-value mappings.
*/
get(callback: (items: Object) => void): void;
get(callback: (items: { [key: string]: any }) => void): void;
/**
* Gets one or more items from storage.
* @param key A single key to get. Pass in null to get the entire contents of storage.
* @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set).
* Parameter items: Object with items in their key-value mappings.
*/
get(key: string, callback: (items: Object) => void): void;
get(key: string, callback: (items: { [key: string]: any }) => void): void;
/**
* Gets one or more items from storage.
* @param keys A list of keys to get. An empty list or object will return an empty result object. Pass in null to get the entire contents of storage.
* @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set).
* Parameter items: Object with items in their key-value mappings.
*/
get(keys: string[], callback: (items: Object) => void): void;
get(keys: string[], callback: (items: { [key: string]: any }) => void): void;
/**
* Gets one or more items from storage.
* @param keys A dictionary specifying default values. Pass in null to get the entire contents of storage.
* @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set).
* Parameter items: Object with items in their key-value mappings.
*/
get(keys: Object, callback: (items: Object) => void): void;
}
get(keys: Object, callback: (items: { [key: string]: any }) => void): void;
}
interface StorageChange {
interface StorageChange {
/** Optional. The new value of the item, if there is a new value. */
newValue?: any;
newValue?: any;
/** Optional. The old value of the item, if there was an old value. */
oldValue?: any;
}
oldValue?: any;
}
interface LocalStorageArea extends StorageArea {
/** The maximum amount (in bytes) of data that can be stored in local storage, as measured by the JSON stringification of every value plus every key's length. This value will be ignored if the extension has the unlimitedStorage permission. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */
QUOTA_BYTES: number;
}
QUOTA_BYTES: number;
}
interface SyncStorageArea extends StorageArea {
/** @deprecated since Chrome 40. The storage.sync API no longer has a sustained write operation quota. */
MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: number;
MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: number;
/** The maximum total amount (in bytes) of data that can be stored in sync storage, as measured by the JSON stringification of every value plus every key's length. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */
QUOTA_BYTES: number;
QUOTA_BYTES: number;
/** The maximum size (in bytes) of each individual item in sync storage, as measured by the JSON stringification of its value plus its key length. Updates containing items larger than this limit will fail immediately and set runtime.lastError. */
QUOTA_BYTES_PER_ITEM: number;
QUOTA_BYTES_PER_ITEM: number;
/** The maximum number of items that can be stored in sync storage. Updates that would cause this limit to be exceeded will fail immediately and set runtime.lastError. */
MAX_ITEMS: number;
MAX_ITEMS: number;
/**
* The maximum number of set, remove, or clear operations that can be performed each hour. This is 1 every 2 seconds, a lower ceiling than the short term higher writes-per-minute limit.
* Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError.
*/
MAX_WRITE_OPERATIONS_PER_HOUR: number;
MAX_WRITE_OPERATIONS_PER_HOUR: number;
/**
* The maximum number of set, remove, or clear operations that can be performed each minute. This is 2 per second, providing higher throughput than writes-per-hour over a shorter period of time.
* Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError.
* @since Chrome 40.
*/
MAX_WRITE_OPERATIONS_PER_MINUTE: number;
}
}
interface StorageChangedEvent extends chrome.events.Event {
interface StorageChangedEvent extends chrome.events.Event {
/**
* @param callback
* Parameter changes: Object mapping each key that changed to its corresponding storage.StorageChange for that item.
* Parameter areaName: Since Chrome 22. The name of the storage area ("sync", "local" or "managed") the changes are for.
*/
addListener(callback: (changes: Object, areaName: string) => void): void;
}
addListener(callback: (changes: { [key: string]: StorageChange }, areaName: string) => void): void;
}
/** Items in the local storage area are local to each machine. */
var local: LocalStorageArea;
/** Items in the sync storage area are synced using Chrome Sync. */
var sync: SyncStorageArea;
/**
* Items in the managed storage area are set by the domain administrator, and are read-only for the extension; trying to modify this namespace results in an error.
* @since Chrome 33.
@@ -5998,7 +5999,7 @@ declare module chrome.storage {
var managed: StorageArea;
/** Fired when one or more items change. */
var onChanged: StorageChangedEvent;
var onChanged: StorageChangedEvent;
}
////////////////////
Vendored
+2 -2
View File
@@ -791,7 +791,7 @@ declare module d3 {
/**
* Returns the first non-null element in the selection, or null otherwise.
*/
node(): EventTarget;
node(): Node;
/**
* Returns the total number of elements in the selection.
@@ -854,7 +854,7 @@ declare module d3 {
call(func: (transition: Transition<Datum>, ...args: any[]) => any, ...args: any[]): Transition<Datum>;
empty(): boolean;
node(): EventTarget;
node(): Node;
size(): number;
}
+6580
View File
File diff suppressed because it is too large Load Diff
+1161 -426
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -42,6 +42,7 @@ function test_animation() {
function test_graphics() {
var g = new createjs.Graphics();
g.setStrokeStyle(1);
g.setStrokeDash([20, 10], 20);
g.beginStroke(createjs.Graphics.getRGB(0, 0, 0));
g.beginFill(createjs.Graphics.getRGB(255, 0, 0));
g.drawCircle(0, 0, 3);
+2
View File
@@ -344,6 +344,7 @@ declare module createjs {
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): Graphics;
rect(x: number, y: number, w: number, h: number): Graphics;
setStrokeStyle(thickness: number, caps?: string | number, joints?: string | number, miterLimit?: number, ignoreScale?: boolean): Graphics;
setStrokeDash(segments?: number[], offset?: number): Graphics;
store(): Graphics;
toString(): string;
unstore(): Graphics;
@@ -377,6 +378,7 @@ declare module createjs {
qt(cpx: number, cpy: number, x: number, y: number): Graphics;
r(x: number, y: number, w: number, h: number): Graphics;
ss(thickness: number, caps?: string | number, joints?: string | number, miterLimit?: number, ignoreScale?: boolean): Graphics;
sd(segments?: number[], offset?: number): Graphics;
}
+1
View File
@@ -143,6 +143,7 @@ interface FirebaseQuery {
*/
equalTo(value: string, key?: string): FirebaseQuery;
equalTo(value: number, key?: string): FirebaseQuery;
equalTo(value: boolean, key?: string): FirebaseQuery;
/**
* Generates a new Query object limited to the first certain number of children.
*/
+2 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Steve Baker <https://github.com/stkb/>, Giedrius Grabauskas <https://github.com/QuatroDevOfficial/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../react/react-global.d.ts" />
/// <reference path="../react/react.d.ts" />
declare module Flux {
@@ -70,6 +70,7 @@ declare module "flux" {
declare module FluxUtils {
import React = __React;
export class Container {
constructor();
/**
+7
View File
@@ -25,4 +25,11 @@ var simpleinit:com.fontoxml.IInvocator = {
documentIds: ["11-22-33","44-55-66"],
cmsBaseUrl: "/test/",
editSessionToken: "aa-bb-cc-dd-ee"
}
var eventData:com.fontoxml.IFontoMessageEventData = {
command: "test-command",
type: "test-type",
scope: init,
metadata: {}
}
+9
View File
@@ -37,4 +37,13 @@ declare module com.fontoxml
roleId:string;
}
//This is describes the object that is assigned to the MessageEvent.data
//property after the FontoXML editor posts a message
export interface IFontoMessageEventData {
command: string;
type: string;
scope: com.fontoxml.IInvocator;
metadata: any;
}
}
+99
View File
@@ -0,0 +1,99 @@
// Tests for type definitions for Foundation Sites v6.0.4
// Project: http://foundation.zurb.com/
// Definitions by: Sam Vloeberghs <https://github.com/samvloeberghs/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="foundation.d.ts" />
$(document).foundation();
$(document).foundation('method5');
$(document).foundation(['method', 'method2']);
Foundation.Abide($('.selector'));
Foundation.Abide($('.selector'), {});
Foundation.Accordion($('.selector'));
Foundation.Accordion($('.selector'), {});
Foundation.AccordionMenu($('.selector'));
Foundation.AccordionMenu($('.selector'), {});
Foundation.DrillDown($('.selector'));
Foundation.DrillDown($('.selector'), {});
Foundation.Dropdown($('.selector'));
Foundation.Dropdown($('.selector'), {});
Foundation.DropdownMenu($('.selector'));
Foundation.DropdownMenu($('.selector'), {});
Foundation.Equalizer($('.selector'));
Foundation.Equalizer($('.selector'), {});
Foundation.Interchange($('.selector'));
Foundation.Interchange($('.selector'), {});
Foundation.Magellan($('.selector'));
Foundation.Magellan($('.selector'), {});
Foundation.OffCanvas($('.selector'));
Foundation.OffCanvas($('.selector'), {});
Foundation.Orbit($('.selector'));
Foundation.Orbit($('.selector'), {});
Foundation.Reveal($('.selector'));
Foundation.Reveal($('.selector'), {});
Foundation.Slider($('.selector'));
Foundation.Slider($('.selector'), {});
Foundation.Sticky($('.selector'));
Foundation.Sticky($('.selector'), {});
Foundation.Tabs($('.selector'));
Foundation.Tabs($('.selector'), {});
Foundation.Toggler($('.selector'));
Foundation.Toggler($('.selector'), {});
Foundation.Tooltip($('.selector'));
Foundation.Tooltip($('.selector'), {});
/*
TODO: fix this:
error TS7017: Index signature of object type implicitly has an 'any' type.
function pluginList() {
'use strict';
return [
'Abide',
'Accordion',
'AccordionMenu',
'DrillDown',
'Dropdown',
'DropdownMenu',
'Equalizer',
'Interchange',
'Magellan',
'OffCanvas',
'Orbit',
'Reveal',
'Slider',
'Sticky',
'Tabs',
'Toggler',
'Tooltip'
];
}
pluginList().forEach((value:string) => {
Foundation[value]($('.selector'));
Foundation[value]($('.selector'), {});
});
*/
+428
View File
@@ -0,0 +1,428 @@
// Type definitions for Foundation Sites v6.0.4
// Project: http://foundation.zurb.com/
// Definitions by: Sam Vloeberghs <https://github.com/samvloeberghs/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
declare module FoundationSites {
// http://foundation.zurb.com/sites/docs/abide.html#javascript-reference
interface Abide {
requiredChedck(element:Object): boolean;
findLabel(element:Object): boolean;
addErrorClasses(element:Object): void;
removeErrorClasses(element:Object): void;
validateInput(element:Object, form:Object): void;
validateForm(element:Object): void;
validateText(element:Object): boolean;
validateRadio(group:string): boolean;
resetForm($form:Object): void;
}
interface IAbidePatterns {
alpha?: RegExp;
alpha_numeric?: RegExp;
integer?: RegExp;
number?: RegExp;
card?: RegExp;
cvv?: RegExp;
email ?: RegExp;
url?: RegExp;
domain?: RegExp;
datetime?: RegExp;
date?: RegExp;
time?: RegExp;
dateISO?: RegExp;
month_day_year?: RegExp;
day_month_year?: RegExp;
color?: RegExp;
}
interface IAbideOptions {
slideSpeed?: number;
multiOpen?: boolean;
patters?: IAbidePatterns;
}
// http://foundation.zurb.com/sites/docs/accordion.html#javascript-reference
interface Accordion {
toggle($target:JQuery): void;
down($target:JQuery, firstTime:boolean): void;
up($target:JQuery): void;
destroy(): void;
}
interface IAccordionOptions {
slideSpeed?: number
multiOpen?: boolean;
}
// http://foundation.zurb.com/sites/docs/accordion-menu.html#javascript-reference
interface AccordionMenu {
toggle($target:JQuery): void;
down($target:JQuery, firstTime:boolean): void;
up($target:JQuery): void;
destroy(): void;
}
interface IAccordionMenuOptions {
slideSpeed?: number;
multiOpen?: boolean;
}
// http://foundation.zurb.com/sites/docs/drilldown-menu.html#javascript-reference
interface Drilldown {
_hideAll($elem:JQuery): void;
_show($elem:JQuery): void;
_hide($elem:JQuery): void;
destroy(): void;
}
interface IDrilldownOptions {
backButton?: string;
wrapper?: string
closeOnClick?: boolean
}
// http://foundation.zurb.com/sites/docs/dropdown.html#javascript-reference
interface Dropdown {
getPositionClass(): string;
open(): void;
close(): void;
toggle(): void;
destroy(): void;
}
interface IDropdownOptions {
hoverDelay?: number;
hover?: boolean;
vOffset?: number;
hOffset?: number;
positionClass?: string;
trapFocus?: boolean;
autoFocus?: boolean;
}
// http://foundation.zurb.com/sites/docs/dropdown-menu.html#javascript-reference
interface DropdownMenu {
destroy(): void;
}
interface IDropdownMenuOptions {
disableHover?: boolean;
autoclose?: boolean;
hoverDelay?: number;
clickOpen?: boolean;
closingTime?: number;
alignments?: string;
verticalClasss?: string;
rightClasss?: string;
}
// http://foundation.zurb.com/sites/docs/equalizer.html#javascript-reference
interface Equalizer {
getHeights(element:Object): Array<any>;
applyHeight($eqParent:Object, heights:Array<any>): void;
destroy(): void;
}
interface IEqualizerOptions {
equalizeOnStack?: boolean;
throttleInterval?: number;
}
// http://foundation.zurb.com/sites/docs/interchange.html#javascript-reference
interface Interchange {
replace(path:string): void;
destroy(): void;
}
interface IInterchangeOptions {
rules?: Array<any>
}
// http://foundation.zurb.com/sites/docs/magellan.html#javascript-reference
interface Magellan {
calcPoints(): void;
reflow(): void;
destroy(): void;
}
interface IMagellanOptions {
animationDuration?: number;
animationEasing?: string;
threshold?: number;
activeClass?: string;
deepLinking?: boolean;
}
// http://foundation.zurb.com/sites/docs/offcanvas.html#javascript-reference
interface OffCanvas {
open(event:Object, trigger:JQuery): void;
toggle(event:Object, trigger:JQuery): void;
close(): void;
destroy(): void;
}
interface IOffCanvasOptions {
closeOnClick?: boolean;
transitionTime?: number;
position?: string;
forceTop?: boolean;
isRevealed?: boolean;
revealOn?: string;
autoFocus?: boolean;
revealClass?: string;
}
// http://foundation.zurb.com/sites/docs/orbit.html#javascript-reference
interface Orbit {
changeSlide(isLTR:boolean, chosenSlide?:Object, idx?:number): void;
geoSync(): void;
destroy(): void;
}
interface IOrbitOptions {
bullets?: boolean;
navButtons?: boolean;
animInFromRight?: string;
animOutToRight?: string;
animInFromLeft?: string;
animOutToLeft?: string;
autoPlay?: boolean;
timerDelay?: number;
infiniteWrap?: boolean;
swipe?: boolean;
pauseOnHover?: boolean;
accessible?: boolean;
containerClass?: string;
slideClass?: string;
boxOfBullets?: string;
nextClass?: string;
prevClass?: string;
}
// http://foundation.zurb.com/sites/docs/reveal.html#javascript-reference
interface Reveal {
open(): void;
toggle(): void;
close(): void;
destroy(): void;
}
interface IRevealOptions {
animationIn?: string;
animationOut?: string;
showDelay?: number;
hideDelay?: number;
closeOnClick?: boolean;
closeOnEsc?: boolean;
multipleOpened?: boolean;
vOffset?: number;
hOffset?: number;
fullScreen?: boolean;
btmOffsetPct?: number;
overlay?: boolean;
resetOnClose?: boolean;
}
// http://foundation.zurb.com/sites/docs/slider.html#javascript-reference
interface Slider {
destroy(): void;
}
interface ISliderOptions {
start?: number;
end?: number;
step?: number;
initialStart ?: number;
initialEnd?: number;
binding?: boolean;
clickSelect?: boolean;
vertical?: boolean;
draggable?: boolean;
disabled?: boolean;
doubleSided?: boolean;
decimal?: number;
moveTime?: number;
disabledClass?: string;
}
// http://foundation.zurb.com/sites/docs/sticky.html#javascript-reference
interface Sticky {
_pauseListeners(scrollListener:string): void;
_calc(checkSizes:boolean, scroll:number): void;
destroy(): void;
emCalc(number:any): void;
}
interface IStickyOptions {
container?: string;
stickTo?: string;
anchor?: string;
topAnchor?: string;
btmAnchor?: string;
marginTop?: number;
marginBottom?: number;
stickyOn?: string;
stickyClass?: string;
containerClass?: string;
checkEvery?: number;
}
// http://foundation.zurb.com/sites/docs/tabs.html#javascript-reference
interface Tabs {
_handleTabChange($target:JQuery): void;
selectTab($target:JQuery): void;
destroy(): void;
}
interface ITabsOptions {
animate?: boolean;
}
// http://foundation.zurb.com/sites/docs/toggler.html#javascript-reference
interface Toggler {
toggle(): void;
destroy(): void;
}
interface ITogglerOptions {
animate?: boolean;
}
// http://foundation.zurb.com/sites/docs/tooltip.html#javascript-reference
interface Tooltip {
show(): void;
hide(): void;
toggle(): void;
destroy(): void;
}
interface ITooltipOptions {
hoverDelay?: number;
fadeInDuration?: number;
fadeOutDuration?: number;
disableHover?: boolean;
templateClasses?: string;
tooltipClass?: string;
triggerClass?: string;
showOn?: string;
template?: string;
tipText?: string;
clickOpen?: boolean;
positionClass?: string;
vOffset?: number;
hOffset?:number;
}
// Utilities
// ---------
interface Box {
ImNotTouchingYou(element:Object, parent?:Object, lrOnly?:boolean, tbOnly?:boolean): boolean;
GetDimensions(element:Object): Object;
GetOffsets(element:Object, anchor:Object, position:string, vOffset:number, hOffset:number, isOverflow:boolean): Object;
}
interface KeyBoard {
parseKey(event:any): string;
findFocusable($element:Object): Object;
}
interface MediaQuery {
get(size:string): string;
atLeast(size:string): boolean;
queries:Array<any>;
current:any;
}
interface Motion {
animateIn(element:Object, animation:any, cb:Function): void;
animateOut(element:Object, animation:any, cb:Function): void;
}
interface Move {
// TODO
}
interface Nest {
// TODO
//Feather: function(menu, type)
// Burn: function(menu, type){
}
interface Timer {
start(): void;
restart(): void;
pause(): void;
}
interface Touch {
// TODO :extension on jQuery
}
interface Triggers {
// TODO :extension on jQuery
}
interface FoundationSitesStatic {
version : string;
rtl(): boolean;
plugin(plugin:Object, name:string): void;
registerPlugin(plugin:Object): void;
unregisterPlugin(plugin:Object): void;
GetYoDigits(length:number, namespace?:string): string;
reflow(elem:Object, plugins?:Array<string>|string): void;
getFnName(fn:string): string;
transitionend(): string;
util : {
throttle(func:(...args:any[]) => any, delay:number): (...args:any[]) => any;
};
onImagesLoaded(images:Object, cb:Function): void;
Abide(element:Object, options?:IAbideOptions): Abide;
Accordion(element:Object, options?:IAccordionOptions): Accordion;
AccordionMenu(element:Object, options?:IAccordionMenuOptions): AccordionMenu;
DrillDown(element:Object, options?:IDrilldownOptions): Drilldown;
Dropdown(element:Object, options?:IDropdownOptions): Dropdown;
DropdownMenu(element:Object, options?:IDropdownMenuOptions): DropdownMenu;
Equalizer(element:Object, options?:IEqualizerOptions): Equalizer;
Interchange(element:Object, options?:IInterchangeOptions): Interchange;
Magellan(element:Object, options?:IMagellanOptions): Magellan;
OffCanvas(element:Object, options?:IOffCanvasOptions): OffCanvas;
Orbit(element:Object, options?:IOrbitOptions): Orbit;
Reveal(element:Object, options?:IRevealOptions): Reveal;
Slider(element:Object, options?:ISliderOptions): Slider;
Sticky(element:Object, options?:IStickyOptions): Sticky;
Tabs(element:Object, options?:ITabsOptions): Tabs;
Toggler(element:Object, options?:ITogglerOptions): Toggler;
Tooltip(element:Object, options?:ITooltipOptions): Tooltip;
// utils
Box: Box;
KeyBoard: KeyBoard;
MediaQuery: MediaQuery;
Motion: Motion;
Move: Move;
Nest: Nest;
Timer: Timer;
Touch: Touch;
Triggers: Triggers;
}
}
interface JQuery {
foundation(method?:string|Array<any>) : JQuery;
}
declare var Foundation:FoundationSites.FoundationSitesStatic;
declare module "Foundation" {
export = Foundation;
}
+10
View File
@@ -304,6 +304,16 @@ declare module Foundation {
add_custom_rule(rule : string, media : string) : void;
image_loaded(images : JQuery, callback : (...args : any[]) => any) : void;
random_str(length? : number) : string;
is_small_only(): boolean;
is_small_up(): boolean;
is_medium_only(): boolean;
is_medium_up(): boolean;
is_large_only(): boolean;
is_large_up(): boolean;
is_xlarge_only(): boolean;
is_xlarge_up(): boolean;
is_xxlarge_only(): boolean;
is_xxlarge_up(): boolean;
};
}
}
+81 -46
View File
@@ -1,21 +1,23 @@
/// <reference path="./github-electron-main.d.ts" />
import app = require('app');
import AutoUpdater = require('auto-updater');
import BrowserWindow = require('browser-window');
import ContentTracing = require('content-tracing');
import Dialog = require('dialog');
import GlobalShortcut = require('global-shortcut');
import ipc = require('ipc');
import Menu = require('menu');
import MenuItem = require('menu-item');
import PowerMonitor = require('power-monitor');
import Protocol = require('protocol');
import Tray = require('tray');
import Clipboard = require('clipboard');
import CrashReporter = require('crash-reporter');
import NativeImage = require('native-image');
import Screen = require('screen');
import Shell = require('shell');
/// <reference path="./github-electron.d.ts" />
import {
app,
autoUpdater,
BrowserWindow,
contentTracing,
dialog,
globalShortcut,
ipcMain,
Menu,
MenuItem,
powerMonitor,
protocol,
Tray,
clipboard,
crashReporter,
nativeImage,
screen,
shell
} from 'electron';
import path = require('path');
@@ -39,8 +41,8 @@ app.on('window-all-closed', () => {
var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) {
// Someone tried to run a second instance, we should focus our window
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
return true;
});
@@ -125,7 +127,40 @@ var dockMenu = Menu.buildFromTemplate([
<GitHubElectron.MenuItemOptions>{ label: 'Pro' }
]
},
<GitHubElectron.MenuItemOptions>{ label: 'New Command...' }
<GitHubElectron.MenuItemOptions>{ label: 'New Command...' },
<GitHubElectron.MenuItemOptions>{
label: 'Edit',
submenu: [
{
label: 'Undo',
accelerator: 'CmdOrCtrl+Z',
role: 'undo'
},
{
label: 'Redo',
accelerator: 'Shift+CmdOrCtrl+Z',
role: 'redo'
},
{
type: 'separator'
},
{
label: 'Cut',
accelerator: 'CmdOrCtrl+X',
role: 'cut'
},
{
label: 'Copy',
accelerator: 'CmdOrCtrl+C',
role: 'copy'
},
{
label: 'Paste',
accelerator: 'CmdOrCtrl+V',
role: 'paste'
},
]
},
]);
app.dock.setMenu(dockMenu);
@@ -156,7 +191,7 @@ app.on('ready', () => {
onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`);
});
ipc.on('online-status-changed', (event: any, status: any) => {
ipcMain.on('online-status-changed', (event: any, status: any) => {
console.log(status);
});
@@ -167,7 +202,7 @@ app.on('ready', () => {
window = new BrowserWindow({
width: 800,
height: 600,
'title-bar-style': 'hidden-inset',
titleBarStyle: 'hidden-inset',
});
window.loadURL('https://github.com');
});
@@ -183,7 +218,7 @@ app.commandLine.appendSwitch('vmodule', 'console=0');
// auto-updater
// https://github.com/atom/electron/blob/master/docs/api/auto-updater.md
AutoUpdater.setFeedURL('http://mycompany.com/myapp/latest?version=' + app.getVersion());
autoUpdater.setFeedURL('http://mycompany.com/myapp/latest?version=' + app.getVersion());
// browser-window
// https://github.com/atom/electron/blob/master/docs/api/browser-window.md
@@ -199,11 +234,11 @@ win.show();
// content-tracing
// https://github.com/atom/electron/blob/master/docs/api/content-tracing.md
ContentTracing.startRecording('*', ContentTracing.DEFAULT_OPTIONS, () => {
contentTracing.startRecording('*', contentTracing.DEFAULT_OPTIONS, () => {
console.log('Tracing started');
setTimeout(() => {
ContentTracing.stopRecording('', path => {
contentTracing.stopRecording('', path => {
console.log('Tracing data recorded to ' + path);
});
}, 5000);
@@ -212,7 +247,7 @@ ContentTracing.startRecording('*', ContentTracing.DEFAULT_OPTIONS, () => {
// dialog
// https://github.com/atom/electron/blob/master/docs/api/dialog.md
console.log(Dialog.showOpenDialog({
console.log(dialog.showOpenDialog({
properties: ['openFile', 'openDirectory', 'multiSelections']
}));
@@ -220,30 +255,30 @@ console.log(Dialog.showOpenDialog({
// https://github.com/atom/electron/blob/master/docs/api/global-shortcut.md
// Register a 'ctrl+x' shortcut listener.
var ret = GlobalShortcut.register('ctrl+x', () => {
var ret = globalShortcut.register('ctrl+x', () => {
console.log('ctrl+x is pressed');
});
if (!ret)
console.log('registerion fails');
// Check whether a shortcut is registered.
console.log(GlobalShortcut.isRegistered('ctrl+x'));
console.log(globalShortcut.isRegistered('ctrl+x'));
// Unregister a shortcut.
GlobalShortcut.unregister('ctrl+x');
globalShortcut.unregister('ctrl+x');
// Unregister all shortcuts.
GlobalShortcut.unregisterAll();
globalShortcut.unregisterAll();
// ipc
// ipcMain
// https://github.com/atom/electron/blob/master/docs/api/ipc-main-process.md
ipc.on('asynchronous-message', (event: any, arg: any) => {
ipcMain.on('asynchronous-message', (event: any, arg: any) => {
console.log(arg); // prints "ping"
event.sender.send('asynchronous-reply', 'pong');
});
ipc.on('synchronous-message', (event: any, arg: any) => {
ipcMain.on('synchronous-message', (event: any, arg: any) => {
console.log(arg); // prints "ping"
event.returnValue = 'pong';
});
@@ -405,7 +440,7 @@ Menu.buildFromTemplate([
// https://github.com/atom/electron/blob/master/docs/api/power-monitor.md
app.on('ready', () => {
PowerMonitor.on('suspend', () => {
powerMonitor.on('suspend', () => {
console.log('The system is going to sleep');
});
});
@@ -414,9 +449,9 @@ app.on('ready', () => {
// https://github.com/atom/electron/blob/master/docs/api/protocol.md
app.on('ready', () => {
Protocol.registerProtocol('atom', (request: any) => {
protocol.registerProtocol('atom', (request: any) => {
var url = request.url.substr(7);
return new Protocol.RequestFileJob(path.normalize(`${__dirname}/${url}`));
return new protocol.RequestFileJob(path.normalize(`${__dirname}/${url}`));
});
});
@@ -440,26 +475,26 @@ app.on('ready', () => {
// clipboard
// https://github.com/atom/electron/blob/master/docs/api/clipboard.md
Clipboard.writeText('Example String');
Clipboard.writeText('Example String', 'selection');
console.log(Clipboard.readText('selection'));
clipboard.writeText('Example String');
clipboard.writeText('Example String', 'selection');
console.log(clipboard.readText('selection'));
// crash-reporter
// https://github.com/atom/electron/blob/master/docs/api/crash-reporter.md
CrashReporter.start({
crashReporter.start({
productName: 'YourName',
companyName: 'YourCompany',
submitURL: 'https://your-domain.com/url-to-submit',
autoSubmit: true
});
// NativeImage
// nativeImage
// https://github.com/atom/electron/blob/master/docs/api/native-image.md
var appIcon2 = new Tray('/Users/somebody/images/icon.png');
var window2 = new BrowserWindow({ icon: '/Users/somebody/images/window.png' });
var image = Clipboard.readImage();
var image = clipboard.readImage();
var appIcon3 = new Tray(image);
var appIcon4 = new Tray('/Users/somebody/images/icon.png');
@@ -467,12 +502,12 @@ var appIcon4 = new Tray('/Users/somebody/images/icon.png');
// https://github.com/atom/electron/blob/master/docs/api/screen.md
app.on('ready', () => {
var size = Screen.getPrimaryDisplay().workAreaSize;
var size = screen.getPrimaryDisplay().workAreaSize;
mainWindow = new BrowserWindow({ width: size.width, height: size.height });
});
app.on('ready', () => {
var displays = Screen.getAllDisplays();
var displays = screen.getAllDisplays();
var externalDisplay: any = null;
for (var i in displays) {
if (displays[i].bounds.x > 0 || displays[i].bounds.y > 0) {
@@ -492,4 +527,4 @@ app.on('ready', () => {
// shell
// https://github.com/atom/electron/blob/master/docs/api/shell.md
Shell.openExternal('https://github.com');
shell.openExternal('https://github.com');
-270
View File
@@ -1,270 +0,0 @@
// Type definitions for the Electron 0.25.2 main process
// Project: http://electron.atom.io/
// Definitions by: jedmao <https://github.com/jedmao/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="./github-electron.d.ts" />
declare module GitHubElectron {
interface ContentTracing {
/**
* Get a set of category groups. The category groups can change as new code paths are reached.
* @param callback Called once all child processes have acked to the getCategories request.
*/
getCategories(callback: (categoryGroups: any[]) => void): void;
/**
* Start recording on all processes. Recording begins immediately locally, and asynchronously
* on child processes as soon as they receive the EnableRecording request.
* @param categoryFilter A filter to control what category groups should be traced.
* A filter can have an optional "-" prefix to exclude category groups that contain
* a matching category. Having both included and excluded category patterns in the
* same list would not be supported.
* @param options controls what kind of tracing is enabled, it could be a OR-ed
* combination of tracing.DEFAULT_OPTIONS, tracing.ENABLE_SYSTRACE, tracing.ENABLE_SAMPLING
* and tracing.RECORD_CONTINUOUSLY.
* @param callback Called once all child processes have acked to the startRecording request.
*/
startRecording(categoryFilter: string, options: number, callback: Function): void;
/**
* Stop recording on all processes. Child processes typically are caching trace data and
* only rarely flush and send trace data back to the main process. That is because it may
* be an expensive operation to send the trace data over IPC, and we would like to avoid
* much runtime overhead of tracing. So, to end tracing, we must asynchronously ask all
* child processes to flush any pending trace data.
* @param resultFilePath Trace data will be written into this file if it is not empty,
* or into a temporary file.
* @param callback Called once all child processes have acked to the stopRecording request.
*/
stopRecording(resultFilePath: string, callback:
/**
* @param filePath A file that contains the traced data.
*/
(filePath: string) => void
): void;
/**
* Start monitoring on all processes. Monitoring begins immediately locally, and asynchronously
* on child processes as soon as they receive the startMonitoring request.
* @param callback Called once all child processes have acked to the startMonitoring request.
*/
startMonitoring(categoryFilter: string, options: number, callback: Function): void;
/**
* Stop monitoring on all processes.
* @param callback Called once all child processes have acked to the stopMonitoring request.
*/
stopMonitoring(callback: Function): void;
/**
* Get the current monitoring traced data. Child processes typically are caching trace data
* and only rarely flush and send trace data back to the main process. That is because it may
* be an expensive operation to send the trace data over IPC, and we would like to avoid much
* runtime overhead of tracing. So, to end tracing, we must asynchronously ask all child
* processes to flush any pending trace data.
* @param callback Called once all child processes have acked to the captureMonitoringSnapshot request.
*/
captureMonitoringSnapshot(resultFilePath: string, callback:
/**
* @param filePath A file that contains the traced data
* @returns {}
*/
(filePath: string) => void
): void;
/**
* Get the maximum across processes of trace buffer percent full state.
* @param callback Called when the TraceBufferUsage value is determined.
*/
getTraceBufferUsage(callback: Function): void;
/**
* @param callback Called every time the given event occurs on any process.
*/
setWatchEvent(categoryName: string, eventName: string, callback: Function): void;
/**
* Cancel the watch event. If tracing is enabled, this may race with the watch event callback.
*/
cancelWatchEvent(): void;
DEFAULT_OPTIONS: number;
ENABLE_SYSTRACE: number;
ENABLE_SAMPLING: number;
RECORD_CONTINUOUSLY: number;
}
interface Dialog {
/**
* @param callback If supplied, the API call will be asynchronous.
* @returns On success, returns an array of file paths chosen by the user,
* otherwise returns undefined.
*/
showOpenDialog: typeof GitHubElectron.Dialog.showOpenDialog;
/**
* @param callback If supplied, the API call will be asynchronous.
* @returns On success, returns the path of file chosen by the user, otherwise
* returns undefined.
*/
showSaveDialog: typeof GitHubElectron.Dialog.showSaveDialog;
/**
* Shows a message box. It will block until the message box is closed. It returns .
* @param callback If supplied, the API call will be asynchronous.
* @returns The index of the clicked button.
*/
showMessageBox: typeof GitHubElectron.Dialog.showMessageBox;
/**
* Runs a modal dialog that shows an error message. This API can be called safely
* before the ready event of app module emits, it is usually used to report errors
* in early stage of startup.
*/
showErrorBox(title: string, content: string): void;
}
interface GlobalShortcut {
/**
* Registers a global shortcut of accelerator.
* @param accelerator Represents a keyboard shortcut. It can contain modifiers
* and key codes, combined by the "+" character.
* @param callback Called when the registered shortcut is pressed by the user.
* @returns {}
*/
register(accelerator: string, callback: Function): void;
/**
* @param accelerator Represents a keyboard shortcut. It can contain modifiers
* and key codes, combined by the "+" character.
* @returns Whether the accelerator is registered.
*/
isRegistered(accelerator: string): boolean;
/**
* Unregisters the global shortcut of keycode.
* @param accelerator Represents a keyboard shortcut. It can contain modifiers
* and key codes, combined by the "+" character.
*/
unregister(accelerator: string): void;
/**
* Unregisters all the global shortcuts.
*/
unregisterAll(): void;
}
class RequestFileJob {
/**
* Create a request job which would query a file of path and set corresponding mime types.
*/
constructor(path: string);
}
class RequestStringJob {
/**
* Create a request job which sends a string as response.
*/
constructor(options?: {
/**
* Default is "text/plain".
*/
mimeType?: string;
/**
* Default is "UTF-8".
*/
charset?: string;
data?: string;
});
}
class RequestBufferJob {
/**
* Create a request job which accepts a buffer and sends a string as response.
*/
constructor(options?: {
/**
* Default is "application/octet-stream".
*/
mimeType?: string;
/**
* Default is "UTF-8".
*/
encoding?: string;
data?: Buffer;
});
}
interface Protocol {
registerProtocol(scheme: string, handler: (request: any) => void): void;
unregisterProtocol(scheme: string): void;
isHandledProtocol(scheme: string): boolean;
interceptProtocol(scheme: string, handler: (request: any) => void): void;
uninterceptProtocol(scheme: string): void;
RequestFileJob: typeof RequestFileJob;
RequestStringJob: typeof RequestStringJob;
RequestBufferJob: typeof RequestBufferJob;
}
}
declare module 'app' {
var _app: GitHubElectron.App;
export = _app;
}
declare module 'auto-updater' {
var _autoUpdater: GitHubElectron.AutoUpdater;
export = _autoUpdater;
}
declare module 'browser-window' {
var BrowserWindow: typeof GitHubElectron.BrowserWindow;
export = BrowserWindow;
}
declare module 'content-tracing' {
var contentTracing: GitHubElectron.ContentTracing
export = contentTracing;
}
declare module 'dialog' {
var dialog: GitHubElectron.Dialog
export = dialog;
}
declare module 'global-shortcut' {
var globalShortcut: GitHubElectron.GlobalShortcut;
export = globalShortcut;
}
declare module 'ipc' {
var ipc: NodeJS.EventEmitter;
export = ipc;
}
declare module 'menu' {
var Menu: typeof GitHubElectron.Menu;
export = Menu;
}
declare module 'menu-item' {
var MenuItem: typeof GitHubElectron.MenuItem;
export = MenuItem;
}
declare module 'power-monitor' {
var powerMonitor: NodeJS.EventEmitter;
export = powerMonitor;
}
declare module 'protocol' {
var protocol: GitHubElectron.Protocol;
export = protocol;
}
declare module 'tray' {
var Tray: typeof GitHubElectron.Tray;
export = Tray;
}
interface NodeRequireFunction {
(id: 'app'): GitHubElectron.App
(id: 'auto-updater'): GitHubElectron.AutoUpdater
(id: 'browser-window'): typeof GitHubElectron.BrowserWindow
(id: 'content-tracing'): GitHubElectron.ContentTracing
(id: 'dialog'): GitHubElectron.Dialog
(id: 'global-shortcut'): GitHubElectron.GlobalShortcut
(id: 'ipc'): NodeJS.EventEmitter
(id: 'menu'): typeof GitHubElectron.Menu
(id: 'menu-item'): typeof GitHubElectron.MenuItem
(id: 'power-monitor'): NodeJS.EventEmitter
(id: 'protocol'): GitHubElectron.Protocol
(id: 'tray'): typeof GitHubElectron.Tray
}
@@ -1,23 +1,25 @@
/// <reference path="./github-electron-renderer.d.ts" />
import ipc = require('ipc');
import remote = require('remote');
import WebFrame = require('web-frame');
import Clipboard = require('clipboard');
import CrashReporter = require('crash-reporter');
import NativeImage = require('native-image');
import Screen = require('screen');
import Shell = require('shell');
/// <reference path="./github-electron.d.ts" />
import {
ipcRenderer,
remote,
webFrame,
clipboard,
crashReporter,
nativeImage,
screen,
shell
} from 'electron';
import fs = require('fs');
// In renderer process (web page).
// https://github.com/atom/electron/blob/master/docs/api/ipc-renderer.md
console.log(ipc.sendSync('synchronous-message', 'ping')); // prints "pong"
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong"
ipc.on('asynchronous-reply', (arg: any) => {
ipcRenderer.on('asynchronous-reply', (arg: any) => {
console.log(arg); // prints "pong"
});
ipc.send('asynchronous-message', 'ping');
ipcRenderer.send('asynchronous-message', 'ping');
// remote
// https://github.com/atom/electron/blob/master/docs/api/remote.md
@@ -45,9 +47,9 @@ remote.getCurrentWindow().capturePage(buf => {
// web-frame
// https://github.com/atom/electron/blob/master/docs/api/web-frame.md
WebFrame.setZoomFactor(2);
webFrame.setZoomFactor(2);
WebFrame.setSpellCheckProvider('en-US', true, {
webFrame.setSpellCheckProvider('en-US', true, {
spellCheck: text => {
return !(require('spellchecker').isMisspelled(text));
}
@@ -56,27 +58,27 @@ WebFrame.setSpellCheckProvider('en-US', true, {
// clipboard
// https://github.com/atom/electron/blob/master/docs/api/clipboard.md
Clipboard.writeText('Example String');
Clipboard.writeText('Example String', 'selection');
console.log(Clipboard.readText('selection'));
clipboard.writeText('Example String');
clipboard.writeText('Example String', 'selection');
console.log(clipboard.readText('selection'));
// crash-reporter
// https://github.com/atom/electron/blob/master/docs/api/crash-reporter.md
CrashReporter.start({
crashReporter.start({
productName: 'YourName',
companyName: 'YourCompany',
submitURL: 'https://your-domain.com/url-to-submit',
autoSubmit: true
});
// NativeImage
// nativeImage
// https://github.com/atom/electron/blob/master/docs/api/native-image.md
var Tray: typeof GitHubElectron.Tray = remote.require('Tray');
var appIcon2 = new Tray('/Users/somebody/images/icon.png');
var window2 = new BrowserWindow({ icon: '/Users/somebody/images/window.png' });
var image = Clipboard.readImage();
var image = clipboard.readImage();
var appIcon3 = new Tray(image);
var appIcon4 = new Tray('/Users/somebody/images/icon.png');
@@ -88,12 +90,12 @@ var app: GitHubElectron.App = remote.require('app');
var mainWindow: GitHubElectron.BrowserWindow = null;
app.on('ready', () => {
var size = Screen.getPrimaryDisplay().workAreaSize;
var size = screen.getPrimaryDisplay().workAreaSize;
mainWindow = new BrowserWindow({ width: size.width, height: size.height });
});
app.on('ready', () => {
var displays = Screen.getAllDisplays();
var displays = screen.getAllDisplays();
var externalDisplay: any = null;
for (var i in displays) {
if (displays[i].bounds.x > 0 || displays[i].bounds.y > 0) {
@@ -113,4 +115,4 @@ app.on('ready', () => {
// shell
// https://github.com/atom/electron/blob/master/docs/api/shell.md
Shell.openExternal('https://github.com');
shell.openExternal('https://github.com');
-116
View File
@@ -1,116 +0,0 @@
// Type definitions for the Electron 0.25.2 renderer process (web page)
// Project: http://electron.atom.io/
// Definitions by: jedmao <https://github.com/jedmao/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="./github-electron.d.ts" />
declare module GitHubElectron {
export class InProcess implements NodeJS.EventEmitter {
addListener(event: string, listener: Function): InProcess;
on(event: string, listener: Function): InProcess;
once(event: string, listener: Function): InProcess;
removeListener(event: string, listener: Function): InProcess;
removeAllListeners(event?: string): InProcess;
setMaxListeners(n: number): void;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
/**
* Send ...args to the renderer via channel in asynchronous message, the main
* process can handle it by listening to the channel event of ipc module.
*/
send(channel: string, ...args: any[]): void;
/**
* Send ...args to the renderer via channel in synchronous message, and returns
* the result sent from main process. The main process can handle it by listening
* to the channel event of ipc module, and returns by setting event.returnValue.
* Note: Usually developers should never use this API, since sending synchronous
* message would block the whole renderer process.
* @returns The result sent from the main process.
*/
sendSync(channel: string, ...args: any[]): string;
/**
* Like ipc.send but the message will be sent to the host page instead of the main process.
* This is mainly used by the page in <webview> to communicate with host page.
*/
sendToHost(channel: string, ...args: any[]): void;
}
interface Remote {
/**
* @returns The object returned by require(module) in the main process.
*/
require(module: string): any;
/**
* @returns The BrowserWindow object which this web page belongs to.
*/
getCurrentWindow(): BrowserWindow
/**
* @returns The global variable of name (e.g. global[name]) in the main process.
*/
getGlobal(name: string): any;
/**
* Returns the process object in the main process. This is the same as
* remote.getGlobal('process'), but gets cached.
*/
process: any;
}
interface WebFrame {
/**
* Changes the zoom factor to the specified factor, zoom factor is
* zoom percent / 100, so 300% = 3.0.
*/
setZoomFactor(factor: number): void;
/**
* @returns The current zoom factor.
*/
getZoomFactor(): number;
/**
* Changes the zoom level to the specified level, 0 is "original size", and each
* increment above or below represents zooming 20% larger or smaller to default
* limits of 300% and 50% of original size, respectively.
*/
setZoomLevel(level: number): void;
/**
* @returns The current zoom level.
*/
getZoomLevel(): number;
/**
* Sets a provider for spell checking in input fields and text areas.
*/
setSpellCheckProvider(language: string, autoCorrectWord: boolean, provider: {
/**
* @returns Whether the word passed is correctly spelled.
*/
spellCheck: (text: string) => boolean;
}): void;
/**
* Sets the scheme as secure scheme. Secure schemes do not trigger mixed content
* warnings. For example, https and data are secure schemes because they cannot be
* corrupted by active network attackers.
*/
registerURLSchemeAsSecure(scheme: string): void;
}
}
declare module 'ipc' {
var inProcess: GitHubElectron.InProcess;
export = inProcess;
}
declare module 'remote' {
var remote: GitHubElectron.Remote;
export = remote;
}
declare module 'web-frame' {
var webframe: GitHubElectron.WebFrame;
export = webframe;
}
interface NodeRequireFunction {
(id: 'ipc'): GitHubElectron.InProcess
(id: 'remote'): GitHubElectron.Remote
(id: 'web-frame'): GitHubElectron.WebFrame
}
+352 -61
View File
@@ -1,7 +1,7 @@
// Type definitions for Electron 0.25.2 (shared between main and rederer processes)
// Type definitions for Electron v0.35.0
// Project: http://electron.atom.io/
// Definitions by: jedmao <https://github.com/jedmao/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Definitions by: jedmao <https://github.com/jedmao/>, rhysd <https://rhysd.github.io>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
@@ -447,54 +447,63 @@ declare module GitHubElectron {
isVisibleOnAllWorkspaces(): boolean;
}
interface WebPreferences {
nodeIntegration?: boolean;
preload?: string;
partition: string;
zoomFactor: number;
javascript: boolean;
webSecurity: boolean;
allowDisplayingInsecureContent: boolean;
allowRunningInsecureContent: boolean;
images: boolean;
textAreasAreResizable: boolean;
webgl?: boolean;
webaudio?: boolean;
plugins?: boolean;
experimentalFeatures?: boolean;
experimentalCanvasFeatures?: boolean;
overlayScrollbars?: boolean;
sharedWorker?: boolean;
directWrite?: boolean;
pageVisibility?: boolean;
}
// Includes all options BrowserWindow can take as of this writing
// http://electron.atom.io/docs/v0.29.0/api/browser-window/
interface BrowserWindowOptions extends Rectangle {
show?: boolean;
'use-content-size'?: boolean;
useContentSize?: boolean;
center?: boolean;
'min-width'?: number;
'min-height'?: number;
'max-width'?: number;
'max-height'?: number;
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
resizable?: boolean;
'always-on-top'?: boolean;
alwaysOnTop?: boolean;
fullscreen?: boolean;
'skip-taskbar'?: boolean;
'zoom-factor'?: number;
skipTaskbar?: boolean;
zoomFactor?: number;
kiosk?: boolean;
title?: string;
icon?: NativeImage|string;
frame?: boolean;
'node-integration'?: boolean;
'accept-first-mouse'?: boolean;
'disable-auto-hide-cursor'?: boolean;
'auto-hide-menu-bar'?: boolean;
'enable-larger-than-screen'?: boolean;
'dark-theme'?: boolean;
acceptFirstMouse?: boolean;
disableAutoHideCursor?: boolean;
autoHideMenuBar?: boolean;
enableLargerThanScreen?: boolean;
darkTheme?: boolean;
preload?: string;
transparent?: boolean;
type?: string;
'standard-window'?: boolean;
'web-preferences'?: any; // Object
javascript?: boolean;
'web-security'?: boolean;
images?: boolean;
standardWindow?: boolean;
webPreferences?: WebPreferences;
java?: boolean;
'text-areas-are-resizable'?: boolean;
webgl?: boolean;
webaudio?: boolean;
plugins?: boolean;
'extra-plugin-dirs'?: string[];
'experimental-features'?: boolean;
'experimental-canvas-features'?: boolean;
'subpixel-font-scaling'?: boolean;
'overlay-scrollbars'?: boolean;
'overlay-fullscreen-video'?: boolean;
'shared-worker'?: boolean;
'direct-write'?: boolean;
'page-visibility'?: boolean;
'title-bar-style'?: string;
textAreasAreResizable?: boolean;
extraPluginDirs?: string[];
subpixelFontScaling?: boolean;
overlayFullscreenVideo?: boolean;
titleBarStyle?: string;
}
interface Rectangle {
@@ -880,6 +889,10 @@ declare module GitHubElectron {
* a given menu.
*/
position?: string;
/**
* Define the action of the menu item, when specified the click property will be ignored
*/
role?: string;
}
class BrowserWindowProxy {
@@ -1404,31 +1417,308 @@ declare module GitHubElectron {
*/
beep(): void;
}
}
declare module 'clipboard' {
var clipboard: GitHubElectron.Clipboard
export = clipboard;
}
// Type definitions for renderer process
declare module 'crash-reporter' {
var crashReporter: GitHubElectron.CrashReporter
export = crashReporter;
}
export class IpcRenderer implements NodeJS.EventEmitter {
addListener(event: string, listener: Function): IpcRenderer;
on(event: string, listener: Function): IpcRenderer;
once(event: string, listener: Function): IpcRenderer;
removeListener(event: string, listener: Function): IpcRenderer;
removeAllListeners(event?: string): IpcRenderer;
setMaxListeners(n: number): void;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
/**
* Send ...args to the renderer via channel in asynchronous message, the main
* process can handle it by listening to the channel event of ipc module.
*/
send(channel: string, ...args: any[]): void;
/**
* Send ...args to the renderer via channel in synchronous message, and returns
* the result sent from main process. The main process can handle it by listening
* to the channel event of ipc module, and returns by setting event.returnValue.
* Note: Usually developers should never use this API, since sending synchronous
* message would block the whole renderer process.
* @returns The result sent from the main process.
*/
sendSync(channel: string, ...args: any[]): string;
/**
* Like ipc.send but the message will be sent to the host page instead of the main process.
* This is mainly used by the page in <webview> to communicate with host page.
*/
sendToHost(channel: string, ...args: any[]): void;
}
declare module 'native-image' {
var nativeImage: typeof GitHubElectron.NativeImage;
export = nativeImage;
}
interface Remote {
/**
* @returns The object returned by require(module) in the main process.
*/
require(module: string): any;
/**
* @returns The BrowserWindow object which this web page belongs to.
*/
getCurrentWindow(): BrowserWindow
/**
* @returns The global variable of name (e.g. global[name]) in the main process.
*/
getGlobal(name: string): any;
/**
* Returns the process object in the main process. This is the same as
* remote.getGlobal('process'), but gets cached.
*/
process: any;
}
interface WebFrame {
/**
* Changes the zoom factor to the specified factor, zoom factor is
* zoom percent / 100, so 300% = 3.0.
*/
setZoomFactor(factor: number): void;
/**
* @returns The current zoom factor.
*/
getZoomFactor(): number;
/**
* Changes the zoom level to the specified level, 0 is "original size", and each
* increment above or below represents zooming 20% larger or smaller to default
* limits of 300% and 50% of original size, respectively.
*/
setZoomLevel(level: number): void;
/**
* @returns The current zoom level.
*/
getZoomLevel(): number;
/**
* Sets a provider for spell checking in input fields and text areas.
*/
setSpellCheckProvider(language: string, autoCorrectWord: boolean, provider: {
/**
* @returns Whether the word passed is correctly spelled.
*/
spellCheck: (text: string) => boolean;
}): void;
/**
* Sets the scheme as secure scheme. Secure schemes do not trigger mixed content
* warnings. For example, https and data are secure schemes because they cannot be
* corrupted by active network attackers.
*/
registerURLSchemeAsSecure(scheme: string): void;
}
declare module 'screen' {
var screen: GitHubElectron.Screen;
export = screen;
}
// Type definitions for main process
declare module 'shell' {
var shell: GitHubElectron.Shell;
export = shell;
interface ContentTracing {
/**
* Get a set of category groups. The category groups can change as new code paths are reached.
* @param callback Called once all child processes have acked to the getCategories request.
*/
getCategories(callback: (categoryGroups: any[]) => void): void;
/**
* Start recording on all processes. Recording begins immediately locally, and asynchronously
* on child processes as soon as they receive the EnableRecording request.
* @param categoryFilter A filter to control what category groups should be traced.
* A filter can have an optional "-" prefix to exclude category groups that contain
* a matching category. Having both included and excluded category patterns in the
* same list would not be supported.
* @param options controls what kind of tracing is enabled, it could be a OR-ed
* combination of tracing.DEFAULT_OPTIONS, tracing.ENABLE_SYSTRACE, tracing.ENABLE_SAMPLING
* and tracing.RECORD_CONTINUOUSLY.
* @param callback Called once all child processes have acked to the startRecording request.
*/
startRecording(categoryFilter: string, options: number, callback: Function): void;
/**
* Stop recording on all processes. Child processes typically are caching trace data and
* only rarely flush and send trace data back to the main process. That is because it may
* be an expensive operation to send the trace data over IPC, and we would like to avoid
* much runtime overhead of tracing. So, to end tracing, we must asynchronously ask all
* child processes to flush any pending trace data.
* @param resultFilePath Trace data will be written into this file if it is not empty,
* or into a temporary file.
* @param callback Called once all child processes have acked to the stopRecording request.
*/
stopRecording(resultFilePath: string, callback:
/**
* @param filePath A file that contains the traced data.
*/
(filePath: string) => void
): void;
/**
* Start monitoring on all processes. Monitoring begins immediately locally, and asynchronously
* on child processes as soon as they receive the startMonitoring request.
* @param callback Called once all child processes have acked to the startMonitoring request.
*/
startMonitoring(categoryFilter: string, options: number, callback: Function): void;
/**
* Stop monitoring on all processes.
* @param callback Called once all child processes have acked to the stopMonitoring request.
*/
stopMonitoring(callback: Function): void;
/**
* Get the current monitoring traced data. Child processes typically are caching trace data
* and only rarely flush and send trace data back to the main process. That is because it may
* be an expensive operation to send the trace data over IPC, and we would like to avoid much
* runtime overhead of tracing. So, to end tracing, we must asynchronously ask all child
* processes to flush any pending trace data.
* @param callback Called once all child processes have acked to the captureMonitoringSnapshot request.
*/
captureMonitoringSnapshot(resultFilePath: string, callback:
/**
* @param filePath A file that contains the traced data
* @returns {}
*/
(filePath: string) => void
): void;
/**
* Get the maximum across processes of trace buffer percent full state.
* @param callback Called when the TraceBufferUsage value is determined.
*/
getTraceBufferUsage(callback: Function): void;
/**
* @param callback Called every time the given event occurs on any process.
*/
setWatchEvent(categoryName: string, eventName: string, callback: Function): void;
/**
* Cancel the watch event. If tracing is enabled, this may race with the watch event callback.
*/
cancelWatchEvent(): void;
DEFAULT_OPTIONS: number;
ENABLE_SYSTRACE: number;
ENABLE_SAMPLING: number;
RECORD_CONTINUOUSLY: number;
}
interface Dialog {
/**
* @param callback If supplied, the API call will be asynchronous.
* @returns On success, returns an array of file paths chosen by the user,
* otherwise returns undefined.
*/
showOpenDialog: typeof GitHubElectron.Dialog.showOpenDialog;
/**
* @param callback If supplied, the API call will be asynchronous.
* @returns On success, returns the path of file chosen by the user, otherwise
* returns undefined.
*/
showSaveDialog: typeof GitHubElectron.Dialog.showSaveDialog;
/**
* Shows a message box. It will block until the message box is closed. It returns .
* @param callback If supplied, the API call will be asynchronous.
* @returns The index of the clicked button.
*/
showMessageBox: typeof GitHubElectron.Dialog.showMessageBox;
/**
* Runs a modal dialog that shows an error message. This API can be called safely
* before the ready event of app module emits, it is usually used to report errors
* in early stage of startup.
*/
showErrorBox(title: string, content: string): void;
}
interface GlobalShortcut {
/**
* Registers a global shortcut of accelerator.
* @param accelerator Represents a keyboard shortcut. It can contain modifiers
* and key codes, combined by the "+" character.
* @param callback Called when the registered shortcut is pressed by the user.
* @returns {}
*/
register(accelerator: string, callback: Function): void;
/**
* @param accelerator Represents a keyboard shortcut. It can contain modifiers
* and key codes, combined by the "+" character.
* @returns Whether the accelerator is registered.
*/
isRegistered(accelerator: string): boolean;
/**
* Unregisters the global shortcut of keycode.
* @param accelerator Represents a keyboard shortcut. It can contain modifiers
* and key codes, combined by the "+" character.
*/
unregister(accelerator: string): void;
/**
* Unregisters all the global shortcuts.
*/
unregisterAll(): void;
}
class RequestFileJob {
/**
* Create a request job which would query a file of path and set corresponding mime types.
*/
constructor(path: string);
}
class RequestStringJob {
/**
* Create a request job which sends a string as response.
*/
constructor(options?: {
/**
* Default is "text/plain".
*/
mimeType?: string;
/**
* Default is "UTF-8".
*/
charset?: string;
data?: string;
});
}
class RequestBufferJob {
/**
* Create a request job which accepts a buffer and sends a string as response.
*/
constructor(options?: {
/**
* Default is "application/octet-stream".
*/
mimeType?: string;
/**
* Default is "UTF-8".
*/
encoding?: string;
data?: Buffer;
});
}
interface Protocol {
registerProtocol(scheme: string, handler: (request: any) => void): void;
unregisterProtocol(scheme: string): void;
isHandledProtocol(scheme: string): boolean;
interceptProtocol(scheme: string, handler: (request: any) => void): void;
uninterceptProtocol(scheme: string): void;
RequestFileJob: typeof RequestFileJob;
RequestStringJob: typeof RequestStringJob;
RequestBufferJob: typeof RequestBufferJob;
}
interface Electron {
clipboard: GitHubElectron.Clipboard;
crashReporter: GitHubElectron.CrashReporter;
nativeImage: GitHubElectron.NativeImage;
screen: GitHubElectron.Screen;
shell: GitHubElectron.Shell;
remote: GitHubElectron.Remote;
ipcRenderer: GitHubElectron.IpcRenderer;
webFrame: GitHubElectron.WebFrame;
app: GitHubElectron.App;
autoUpdater: GitHubElectron.AutoUpdater;
BrowserWindow: typeof GitHubElectron.BrowserWindow;
contentTracing: GitHubElectron.ContentTracing;
dialog: GitHubElectron.Dialog;
globalShortcut: GitHubElectron.GlobalShortcut;
ipcMain: NodeJS.EventEmitter;
Menu: typeof GitHubElectron.Menu;
MenuItem: typeof GitHubElectron.MenuItem;
powerMonitor: NodeJS.EventEmitter;
protocol: GitHubElectron.Protocol;
Tray: typeof GitHubElectron.Tray;
}
}
interface Window {
@@ -1446,10 +1736,11 @@ interface File {
path: string;
}
declare module 'electron' {
var electron: GitHubElectron.Electron;
export = electron;
}
interface NodeRequireFunction {
(id: 'clipboard'): GitHubElectron.Clipboard
(id: 'crash-reporter'): GitHubElectron.CrashReporter
(id: 'native-image'): typeof GitHubElectron.NativeImage
(id: 'screen'): GitHubElectron.Screen
(id: 'shell'): GitHubElectron.Shell
(id: 'electron'): GitHubElectron.Electron;
}
+27
View File
@@ -0,0 +1,27 @@
/// <reference path="google-maps.d.ts" />
import GoogleMapsLoader = require('google-maps');
GoogleMapsLoader.load(function(google) {
var loadedMap = google.maps.Map;
});
GoogleMapsLoader.KEY = 'qwertyuiopasdfghjklzxcvbnm';
GoogleMapsLoader.CLIENT = 'yourclientkey';
GoogleMapsLoader.VERSION = '3.14';
GoogleMapsLoader.SENSOR = true;
GoogleMapsLoader.LIBRARIES = ['geometry', 'places'];
GoogleMapsLoader.LANGUAGE = 'fr';
GoogleMapsLoader.release(function() {
console.log('No google maps api around');
});
GoogleMapsLoader.onLoad(function(google) {
var loadedMap = google.maps.Map;
console.log('I just loaded google maps api');
});
+26
View File
@@ -0,0 +1,26 @@
// Type definitions for google-maps 3.1.0
// Project: https://www.npmjs.com/package/google-maps
// Definitions by: Deividas Bakanas <https://github.com/DeividasBakanas>, Giedrius Grabauskas <https://github.com/GiedriusGrabauskas>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../googlemaps/google.maps.d.ts" />
declare namespace GoogleMapsLoader {
interface CallBack {
(google: { maps: { Map: google.maps.Map } }): void;
}
export var KEY: string;
export var CLIENT: string;
export var VERSION: string;
export var SENSOR: boolean;
export var LIBRARIES: Array<string>;
export var LANGUAGE: string;
export function release(callBack: Function): void;
export function onLoad(callBack?: CallBack): void;
export function load(callBack?: CallBack): void;
export function isLoaded(): boolean;
}
declare module 'google-maps' {
export = GoogleMapsLoader;
}
+19 -19
View File
@@ -911,10 +911,10 @@ declare module google.maps {
avoidFerries?: boolean;
avoidHighways?: boolean;
avoidTolls?: boolean;
destination?: LatLng|string;
destination?: LatLng|LatLngLiteral|string;
durationInTraffic?: boolean;
optimizeWaypoints?: boolean;
origin?: LatLng|string;
origin?: LatLng|LatLngLiteral|string;
provideRouteAlternatives?: boolean;
region?: string;
transitOptions?: TransitOptions;
@@ -959,7 +959,7 @@ declare module google.maps {
export interface TransitFare { }
export interface DirectionsWaypoint {
location: LatLng|string;
location: LatLng|LatLngLiteral|string;
stopover: boolean;
}
@@ -1917,16 +1917,16 @@ declare module google.maps {
}
export interface PlaceSearchRequest {
bounds: LatLngBounds;
keyword: string;
location: LatLng|LatLngLiteral;
bounds?: LatLngBounds;
keyword?: string;
location?: LatLng|LatLngLiteral;
maxPriceLevel?: number;
minPriceLevel?: number;
name: string;
openNow: boolean;
radius: number;
rankBy: RankBy;
types: string[];
name?: string;
openNow?: boolean;
radius?: number;
rankBy?: RankBy;
types?: string[];
}
export class PlacesService {
@@ -1963,11 +1963,11 @@ declare module google.maps {
export interface RadarSearchRequest {
bounds?: LatLngBounds;
keyword: string;
location: LatLng|LatLngLiteral;
name: string;
radius: number;
types: string[];
keyword?: string;
location?: LatLng|LatLngLiteral;
name?: string;
radius?: number;
types?: string[];
}
export enum RankBy {
@@ -1988,10 +1988,10 @@ declare module google.maps {
export interface TextSearchRequest {
bounds?: LatLngBounds;
location: LatLng|LatLngLiteral;
location?: LatLng|LatLngLiteral;
query: string;
radius: number;
types: string[];
radius?: number;
types?: string[];
}
}
+2
View File
@@ -36,5 +36,7 @@ declare module 'gulp-babel' {
retainLines?: boolean
}): NodeJS.ReadWriteStream;
module babel { }
export = babel;
}
+4
View File
@@ -60,3 +60,7 @@ gulp.task('default', function () {
.pipe(typescript())
.pipe(gulp.dest('built/local'));
});
var compilerOptions = tsProject.config.compilerOptions;
var exclude = tsProject.config.exclude;
var files = tsProject.config.files;
+21 -3
View File
@@ -20,14 +20,32 @@ declare module "gulp-typescript" {
noImplicitAny?: boolean;
noLib?: boolean;
removeComments?: boolean;
sourceRoot?: string;
sourceRoot?: string; // use gulp-sourcemaps instead
sortOutput?: boolean;
target?: string;
typescript?: any;
outFile?: string;
outDir?: string;
suppressImplicitAnyIndexErrors?: boolean;
jsx?: string;
declaration?: boolean;
emitDecoratorMetadata?: boolean;
experimentalAsyncFunctions?: boolean;
moduleResolution?: string;
noEmitHelpers?: boolean;
preserveConstEnums?: boolean;
isolatedModules?: boolean;
}
interface TsConfig {
files?: string[];
exclude?: string[];
compilerOptions?: any;
}
interface Project {
src(): NodeJS.ReadWriteStream
config: TsConfig;
src(): NodeJS.ReadWriteStream;
}
interface FilterSettings {
@@ -51,4 +69,4 @@ declare module "gulp-typescript" {
}
export = GulpTypescript;
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
/// <reference path="hopscotch.d.ts" />
var tourDefinition = {
var tourDefinition: TourDefinition = {
id: 'intro-tour',
steps: [
{
+69 -10
View File
@@ -3,14 +3,44 @@
// Definitions by: Tim Perry <https://github.com/pimterry>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface TourDefinition {
declare type CallbackNameNamesOrDefinition = string | string[] | (() => void);
interface HopscotchConfiguration {
bubbleWidth?: number;
buddleHeight?: number;
smoothScroll?: boolean;
scrollDuration?: number;
scrollTopMargin?: number;
showCloseButton?: boolean;
showNextButton?: boolean;
showPrevButton?: boolean;
arrowWidth?: number;
skipIfNoElement?: boolean;
nextOnTargetClick?: boolean;
onNext?: CallbackNameNamesOrDefinition;
onPrev?: CallbackNameNamesOrDefinition;
onStart?: CallbackNameNamesOrDefinition;
onEnd?: CallbackNameNamesOrDefinition;
onClose?: CallbackNameNamesOrDefinition;
onError?: CallbackNameNamesOrDefinition;
i18n?: {
nextBtn?: string;
prevBtn?: string;
doneBtn?: string;
skipBtn?: string;
closeTooltip?: string;
stepNums?: string[];
}
}
interface TourDefinition extends HopscotchConfiguration {
id: string;
steps: StepDefinition[];
skipIfNoElement: boolean;
onEnd: () => void;
onClose: () => void;
}
interface StepDefinition {
@@ -20,22 +50,51 @@ interface StepDefinition {
title?: string;
content?: string;
width?: number;
padding?: number;
xOffset?: number;
yOffset?: number;
arrowOffset?: number;
height?: number;
width?: number;
delay?: number;
zIndex?: number;
multipage?: boolean;
showNextButton?: boolean;
showPrevButton?: boolean;
showCTAButton?: boolean;
ctaLabel?: string;
multipage?: boolean;
showSkip?: boolean;
fixedElement?: boolean;
nextOnTargetClick?: boolean;
onShow?: () => void;
onPrev?: CallbackNameNamesOrDefinition;
onNext?: CallbackNameNamesOrDefinition;
onShow?: CallbackNameNamesOrDefinition;
onCTA?: CallbackNameNamesOrDefinition;
}
interface HopscotchStatic {
startTour(tour: TourDefinition, stepNum?: number): void;
showStep(id: number): void;
prevStep(): void;
nextStep(): void;
endTour(clearCookie: boolean): void;
configure(options: HopscotchConfiguration): void;
getCurrTour(): TourDefinition;
getCurrStepNum(): number;
getState(): string;
listen(eventName: string, callback: () => void): void;
unlisten(eventName: string, callback: () => void): void;
removeCallbacks(eventName?: string, tourOnly?: boolean): void;
registerHelper(id: string, helper: (...args: any[]) => void): void;
resetDefaultI18N(): void;
resetDefaultOptions(): void;
}
declare var hopscotch: HopscotchStatic;
+172 -141
View File
@@ -5,32 +5,46 @@
/// <reference path='../node/node.d.ts' />
declare module IMAP {
// The property names of these interfaces match the documentation (where type names were given).
export interface Config {
user: string; // Username for plain-text authentication.
password: string; // Password for plain-text authentication.
xoauth?: string; // Base64-encoded OAuth token for OAuth authentication for servers that support it (See Andris Reinman's xoauth.js module to help generate this string).
xoauth2?: string; // Base64-encoded OAuth2 token for The SASL XOAUTH2 Mechanism for servers that support it (See Andris Reinman's xoauth2 module to help generate this string).
host?: string; // Hostname or IP address of the IMAP server. Default: "localhost"
port?: number; // Port number of the IMAP server. Default: 143
tls?: boolean; // Perform implicit TLS connection? Default: false
tlsOptions?: Object; // Options object to pass to tls.connect() Default: (none)
autotls?: string; // Set to 'always' to always attempt connection upgrades via STARTTLS, 'required' only if upgrading is required, or 'never' to never attempt upgrading. Default: 'never'
connTimeout?: number; // Number of milliseconds to wait for a connection to be established. Default: 10000
authTimeout?: number; // Number of milliseconds to wait to be authenticated after a connection has been established. Default: 5000
keepalive?: any; /* boolean|KeepAlive */ // Configures the keepalive mechanism. Set to true to enable keepalive with defaults or set to object to enable and configure keepalive behavior: Default: true
debug?: Function; // If set, the function will be called with one argument, a string containing some debug info Default: (no debug output)
/** Username for plain-text authentication. */
user: string;
/** Password for plain-text authentication. */
password: string;
/** Base64-encoded OAuth token for OAuth authentication for servers that support it (See Andris Reinman's xoauth.js module to help generate this string). */
xoauth?: string;
/** Base64-encoded OAuth2 token for The SASL XOAUTH2 Mechanism for servers that support it (See Andris Reinman's xoauth2 module to help generate this string). */
xoauth2?: string;
/** Hostname or IP address of the IMAP server. Default: "localhost" */
host?: string;
/** Port number of the IMAP server. Default: 143 */
port?: number;
/** Perform implicit TLS connection? Default: false */
tls?: boolean;
/** Options object to pass to tls.connect() Default: (none) */
tlsOptions?: Object;
/** Set to 'always' to always attempt connection upgrades via STARTTLS, 'required' only if upgrading is required, or 'never' to never attempt upgrading. Default: 'never' */
autotls?: string;
/** Number of milliseconds to wait for a connection to be established. Default: 10000 */
connTimeout?: number;
/** Number of milliseconds to wait to be authenticated after a connection has been established. Default: 5000 */
authTimeout?: number;
/** Configures the keepalive mechanism. Set to true to enable keepalive with defaults or set to object to enable and configure keepalive behavior: Default: true */
keepalive?: any; /* boolean|KeepAlive */
/** If set, the function will be called with one argument, a string containing some debug info Default: (no debug output) */
debug?: Function;
}
export interface KeepAlive {
interval?: number; // This is the interval (in milliseconds) at which NOOPs are sent and the interval at which idleInterval is checked. Default: 10000
idleInterval?: number; // This is the interval (in milliseconds) at which an IDLE command (for servers that support IDLE) is re-sent. Default: 300000 (5 mins)
forceNoop?: boolean; // Set to true to force use of NOOP keepalive on servers also support IDLE. Default: false
/** This is the interval (in milliseconds) at which NOOPs are sent and the interval at which idleInterval is checked. Default: 10000 */
interval?: number;
/** This is the interval (in milliseconds) at which an IDLE command (for servers that support IDLE) is re-sent. Default: 300000 (5 mins) */
idleInterval?: number;
/** Set to true to force use of NOOP keepalive on servers also support IDLE. Default: false */
forceNoop?: boolean;
}
// One of:
@@ -41,63 +55,78 @@ declare module IMAP {
// type MessageSource = string | string[]
export interface Box {
name: string; // The name of this mailbox.
readOnly?: boolean; // True if this mailbox was opened in read-only mode. (Only available with openBox() calls)
newKeywords: boolean; //True if new keywords can be added to messages in this mailbox.
uidvalidity: number; // A 32-bit number that can be used to determine if UIDs in this mailbox have changed since the last time this mailbox was opened.
uidnext: number; // The uid that will be assigned to the next message that arrives at this mailbox.
flags: string[]; // array - A list of system-defined flags applicable for this mailbox. Flags in this list but not in permFlags may be stored for the current session only. Additional server implementation-specific flags may also be available.
permFlags: string[]; // A list of flags that can be permanently added/removed to/from messages in this mailbox.
persistentUIDs: boolean; // Whether or not this mailbox has persistent UIDs. This should almost always be true for modern mailboxes and should only be false for legacy mail stores where supporting persistent UIDs was not technically feasible.
messages: { //Contains various message counts for this mailbox:
total: number; // Total number of messages in this mailbox.
new: number; // Number of messages in this mailbox having the Recent flag (this IMAP session is the first to see these messages).
unseen: number; // (Only available with status() calls) Number of messages in this mailbox not having the Seen flag (marked as not having been read).
/** The name of this mailbox. */
name: string;
/** True if this mailbox was opened in read-only mode. (Only available with openBox() calls) */
readOnly?: boolean;
/** True if new keywords can be added to messages in this mailbox. */
newKeywords: boolean;
/** A 32-bit number that can be used to determine if UIDs in this mailbox have changed since the last time this mailbox was opened. */
uidvalidity: number;
/** The uid that will be assigned to the next message that arrives at this mailbox. */
uidnext: number;
/** array - A list of system-defined flags applicable for this mailbox. Flags in this list but not in permFlags may be stored for the current session only. Additional server implementation-specific flags may also be available. */
flags: string[];
/** A list of flags that can be permanently added/removed to/from messages in this mailbox. */
permFlags: string[];
/** Whether or not this mailbox has persistent UIDs. This should almost always be true for modern mailboxes and should only be false for legacy mail stores where supporting persistent UIDs was not technically feasible. */
persistentUIDs: boolean;
/** Contains various message counts for this mailbox: */
messages: {
/** Total number of messages in this mailbox. */
total: number;
/** Number of messages in this mailbox having the Recent flag (this IMAP session is the first to see these messages). */
new: number;
/** (Only available with status() calls) Number of messages in this mailbox not having the Seen flag (marked as not having been read). */
unseen: number;
};
}
// Given in a 'message' event from ImapFetch
export interface ImapMessage extends NodeJS.EventEmitter {
}
/** Given in a 'message' event from ImapFetch */
export interface ImapMessage extends NodeJS.EventEmitter { }
export interface FetchOptions {
markSeen?: boolean; // Mark message(s) as read when fetched. Default: false
struct?: boolean; // Fetch the message structure. Default: false
envelope?: boolean; // Fetch the message envelope. Default: false
size?: boolean; // Fetch the RFC822 size. Default: false
modifiers?: Object; // Fetch modifiers defined by IMAP extensions. Default: (none)
bodies?: any; /* string|string[] */ // A string or Array of strings containing the body part section to fetch. Default: (none) Example sections:
/** Mark message(s) as read when fetched. Default: false */
markSeen?: boolean;
/** Fetch the message structure. Default: false */
struct?: boolean;
/** Fetch the message envelope. Default: false */
envelope?: boolean;
/** Fetch the RFC822 size. Default: false */
size?: boolean;
/** Fetch modifiers defined by IMAP extensions. Default: (none) */
modifiers?: Object;
/** A string or Array of strings containing the body part section to fetch. Default: (none) Example sections: */
bodies?: any; /* string|string[] */
}
// Returned from fetch()
export interface ImapFetch extends NodeJS.EventEmitter {
}
/** Returned from fetch() */
export interface ImapFetch extends NodeJS.EventEmitter { }
export interface Folder {
attribs: string[];
delimiter: string;
children: Folder[];
parent: Folder;
attribs: string[];
delimiter: string;
children: Folder[];
parent: Folder;
}
export interface MailBoxes {
[name: string] : Folder;
[name: string]: Folder;
}
export interface AppendOptions {
mailbox?: string; // The name of the mailbox to append the message to. Default: the currently open mailbox
flags?: any; /* string|string[] */ // A single flag (e.g. 'Seen') or an array of flags (e.g. ['Seen', 'Flagged']) to append to the message. Default: (no flags)
date?: Date; // What to use for message arrival date/time. Default: (current date/time)
/** The name of the mailbox to append the message to. Default: the currently open mailbox */
mailbox?: string;
/** A single flag (e.g. 'Seen') or an array of flags (e.g. ['Seen', 'Flagged']) to append to the message. Default: (no flags) */
flags?: any; /* string|string[] */
/** What to use for message arrival date/time. Default: (current date/time) */
date?: Date;
}
@@ -118,7 +147,7 @@ declare module IMAP {
UNDRAFT: void; // Messages that do not have the Draft flag set.
UNFLAGGED: void; // Messages that do not have the Flagged flag set.
UNSEEN: void; // Messages that do not have the Seen flag set.
// The following are valid types that require string value(s):
BCC: any; // Messages that contain the specified string in the BCC field.
@@ -146,28 +175,28 @@ declare module IMAP {
export interface MessageFunctions {
// Searches the currently open mailbox for messages using given criteria. criteria is a list describing what you want to find. For criteria types that require arguments, use an array instead of just the string criteria type name (e.g. ['FROM', 'foo@bar.com']). Prefix criteria types with an "!" to negate.
search(criteria : any[], callback : (error : Error, uids : string[]) => void) : void;
// Fetches message(s) in the currently open mailbox.
fetch(source : any /* MessageSource */, options : FetchOptions) : ImapFetch;
// Copies message(s) in the currently open mailbox to another mailbox.
copy(source : any /* MessageSource */, mailboxName : string, callback : (error : Error) => void) : void;
// Moves message(s) in the currently open mailbox to another mailbox. Note: The message(s) in the destination mailbox will have a new message UID.
move(source : any /* MessageSource */, mailboxName : string, callback : (error : Error) => void) : void;
// Adds flag(s) to message(s).
addFlags(source : any /* MessageSource */, flags : any, callback : (error : Error) => void) : void;
// Removes flag(s) from message(s).
delFlags(source : any /* MessageSource */, flags : any, callback : (error : Error) => void) : void;
// Sets the flag(s) for message(s).
setFlags(source : any /* MessageSource */, flags : any, callback : (error : Error) => void) : void;
// Adds keyword(s) to message(s). keywords is either a single keyword or an array of keywords.
addKeywords(source : any /* MessageSource */, keywords : any /* string|string[] */, callback : (error : Error) => void) : void;
//Removes keyword(s) from message(s). keywords is either a single keyword or an array of keywords.
delKeywords(source : any /* MessageSource */, keywords : any /* string|string[] */, callback : (error : Error) => void) : void;
// Sets keyword(s) for message(s). keywords is either a single keyword or an array of keywords.
setKeywords(source : any /* MessageSource */, keywords : any /* string|string[] */, callback : (error : Error) => void) : void;
// Checks if the server supports the specified capability.
serverSupports(capability : string) : boolean;
/** Searches the currently open mailbox for messages using given criteria. criteria is a list describing what you want to find. For criteria types that require arguments, use an array instead of just the string criteria type name (e.g. ['FROM', 'foo@bar.com']). Prefix criteria types with an "!" to negate. */
search(criteria: any[], callback: (error: Error, uids: string[]) => void): void;
/** Fetches message(s) in the currently open mailbox. */
fetch(source: any /* MessageSource */, options: FetchOptions): ImapFetch;
/** Copies message(s) in the currently open mailbox to another mailbox. */
copy(source: any /* MessageSource */, mailboxName: string, callback: (error: Error) => void): void;
/** Moves message(s) in the currently open mailbox to another mailbox. Note: The message(s) in the destination mailbox will have a new message UID. */
move(source: any /* MessageSource */, mailboxName: string, callback: (error: Error) => void): void;
/** Adds flag(s) to message(s). */
addFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void;
/** Removes flag(s) from message(s). */
delFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void;
/** Sets the flag(s) for message(s). */
setFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void;
/** Adds keyword(s) to message(s). keywords is either a single keyword or an array of keywords. */
addKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void;
/** Removes keyword(s) from message(s). keywords is either a single keyword or an array of keywords. */
delKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void;
/** Sets keyword(s) for message(s). keywords is either a single keyword or an array of keywords. */
setKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void;
/** Checks if the server supports the specified capability. */
serverSupports(capability: string): boolean;
}
@@ -175,8 +204,8 @@ declare module IMAP {
export class Connection implements NodeJS.EventEmitter, MessageFunctions {
/** @constructor */
constructor(config : Config);
constructor(config: Config);
// from NodeJS.EventEmitter
addListener(event: string, listener: Function): NodeJS.EventEmitter;
on(event: string, listener: Function): NodeJS.EventEmitter;
@@ -186,87 +215,89 @@ declare module IMAP {
setMaxListeners(n: number): void;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
// from MessageFunctions
// Searches the currently open mailbox for messages using given criteria. criteria is a list describing what you want to find. For criteria types that require arguments, use an array instead of just the string criteria type name (e.g. ['FROM', 'foo@bar.com']). Prefix criteria types with an "!" to negate.
search(criteria : any[], callback : (error : Error, uids : string[]) => void) : void;
// Fetches message(s) in the currently open mailbox.
fetch(source : any /* MessageSource */, options : FetchOptions) : ImapFetch;
// Copies message(s) in the currently open mailbox to another mailbox.
copy(source : any /* MessageSource */, mailboxName : string, callback : (error : Error) => void) : void;
// Moves message(s) in the currently open mailbox to another mailbox. Note: The message(s) in the destination mailbox will have a new message UID.
move(source : any /* MessageSource */, mailboxName : string, callback : (error : Error) => void) : void;
// Adds flag(s) to message(s).
addFlags(source : any /* MessageSource */, flags : any, callback : (error : Error) => void) : void;
// Removes flag(s) from message(s).
delFlags(source : any /* MessageSource */, flags : any, callback : (error : Error) => void) : void;
// Sets the flag(s) for message(s).
setFlags(source : any /* MessageSource */, flags : any, callback : (error : Error) => void) : void;
// Adds keyword(s) to message(s). keywords is either a single keyword or an array of keywords.
addKeywords(source : any /* MessageSource */, keywords : any /* string|string[] */, callback : (error : Error) => void) : void;
//Removes keyword(s) from message(s). keywords is either a single keyword or an array of keywords.
delKeywords(source : any /* MessageSource */, keywords : any /* string|string[] */, callback : (error : Error) => void) : void;
// Sets keyword(s) for message(s). keywords is either a single keyword or an array of keywords.
setKeywords(source : any /* MessageSource */, keywords : any /* string|string[] */, callback : (error : Error) => void) : void;
// Checks if the server supports the specified capability.
serverSupports(capability : string) : boolean;
// Parses a raw header and returns an object keyed on header fields and the values are Arrays of header field values. Set disableAutoDecode to true to disable automatic decoding of MIME encoded-words that may exist in header field values.
static parseHeader(rawHeader: string, disableAutoDecode? : boolean) : any;
state: string; // The current state of the connection (e.g. 'disconnected', 'connected', 'authenticated').
delimiter: string; // The (top-level) mailbox hierarchy delimiter. If the server does not support mailbox hierarchies and only a flat list, this value will be falsey.
namespaces: { // Contains information about each namespace type (if supported by the server) with the following properties:
personal: any[]; // Mailboxes that belong to the logged in user.
other: any[]; // Mailboxes that belong to other users that the logged in user has access to.
shared: any[]; // Mailboxes that are accessible by any logged in user.
/** Searches the currently open mailbox for messages using given criteria. criteria is a list describing what you want to find. For criteria types that require arguments, use an array instead of just the string criteria type name (e.g. ['FROM', 'foo@bar.com']). Prefix criteria types with an "!" to negate. */
search(criteria: any[], callback: (error: Error, uids: string[]) => void): void;
/** Fetches message(s) in the currently open mailbox. */
fetch(source: any /* MessageSource */, options: FetchOptions): ImapFetch;
/** Copies message(s) in the currently open mailbox to another mailbox. */
copy(source: any /* MessageSource */, mailboxName: string, callback: (error: Error) => void): void;
/** Moves message(s) in the currently open mailbox to another mailbox. Note: The message(s) in the destination mailbox will have a new message UID. */
move(source: any /* MessageSource */, mailboxName: string, callback: (error: Error) => void): void;
/** Adds flag(s) to message(s). */
addFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void;
/** Removes flag(s) from message(s). */
delFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void;
/** Sets the flag(s) for message(s). */
setFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void;
/** Adds keyword(s) to message(s). keywords is either a single keyword or an array of keywords. */
addKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void;
/** Removes keyword(s) from message(s). keywords is either a single keyword or an array of keywords. */
delKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void;
/** Sets keyword(s) for message(s). keywords is either a single keyword or an array of keywords. */
setKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void;
/** Checks if the server supports the specified capability. */
serverSupports(capability: string): boolean;
/** Parses a raw header and returns an object keyed on header fields and the values are Arrays of header field values. Set disableAutoDecode to true to disable automatic decoding of MIME encoded-words that may exist in header field values. */
static parseHeader(rawHeader: string, disableAutoDecode?: boolean): any;
/** The current state of the connection (e.g. 'disconnected', 'connected', 'authenticated'). */
state: string;
/** The (top-level) mailbox hierarchy delimiter. If the server does not support mailbox hierarchies and only a flat list, this value will be falsey. */
delimiter: string;
/** Contains information about each namespace type (if supported by the server) with the following properties: */
namespaces: {
/** Mailboxes that belong to the logged in user. */
personal: any[];
/** Mailboxes that belong to other users that the logged in user has access to. */
other: any[];
/** Mailboxes that are accessible by any logged in user. */
shared: any[];
};
seq: MessageFunctions;
/** Attempts to connect and authenticate with the IMAP server. */
connect() : void;
connect(): void;
/** Closes the connection to the server after all requests in the queue have been sent. */
end() : void;
end(): void;
/** Immediately destroys the connection to the server. */
destroy() : void;
destroy(): void;
/** Opens a specific mailbox that exists on the server. mailboxName should include any necessary prefix/path. modifiers is used by IMAP extensions. */
openBox(mailboxName : string, callback : (error : Error, mailbox: Box) => void) : void;
openBox(mailboxName : string, openReadOnly : boolean, callback : (error : Error, mailbox: Box) => void) : void;
openBox(mailboxName : string, openReadOnly : boolean, modifiers : Object, callback : (error : Error, mailbox: Box) => void) : void;
openBox(mailboxName: string, callback: (error: Error, mailbox: Box) => void): void;
openBox(mailboxName: string, openReadOnly: boolean, callback: (error: Error, mailbox: Box) => void): void;
openBox(mailboxName: string, openReadOnly: boolean, modifiers: Object, callback: (error: Error, mailbox: Box) => void): void;
/** Closes the currently open mailbox. If autoExpunge is true, any messages marked as Deleted in the currently open mailbox will be removed if the mailbox was NOT opened in read-only mode. If autoExpunge is false, you disconnect, or you open another mailbox, messages marked as Deleted will NOT be removed from the currently open mailbox. */
closeBox(callback : (error : Error) => void) : void;
closeBox(autoExpunge : boolean, callback : (error : Error) => void) : void;
closeBox(callback: (error: Error) => void): void;
closeBox(autoExpunge: boolean, callback: (error: Error) => void): void;
/** Creates a new mailbox on the server. mailboxName should include any necessary prefix/path. */
addBox(mailboxName : string, callback : (error : Error) => void) : void;
addBox(mailboxName: string, callback: (error: Error) => void): void;
/** Removes a specific mailbox that exists on the server. mailboxName should including any necessary prefix/path. */
delBox(mailboxName : string, callback : (error : Error, uids : string[]) => void) : void;
delBox(mailboxName: string, callback: (error: Error, uids: string[]) => void): void;
/** Renames a specific mailbox that exists on the server. Both oldMailboxName and newMailboxName should include any necessary prefix/path. Note: Renaming the 'INBOX' mailbox will instead cause all messages in 'INBOX' to be moved to the new mailbox. */
renameBox(oldMailboxName : string, newMailboxName : string, callback : (error : Error, mailbox: Box) => void) : void;
renameBox(oldMailboxName: string, newMailboxName: string, callback: (error: Error, mailbox: Box) => void): void;
/** Subscribes to a specific mailbox that exists on the server. mailboxName should include any necessary prefix/path. */
subscribeBox(mailboxName : string, callback : (error : Error) => void) : void;
subscribeBox(mailboxName: string, callback: (error: Error) => void): void;
/** Unsubscribes from a specific mailbox that exists on the server. mailboxName should include any necessary prefix/path. */
unsubscribeBox(mailboxName : string, callback : (error : Error) => void) : void;
unsubscribeBox(mailboxName: string, callback: (error: Error) => void): void;
/** Fetches information about a mailbox other than the one currently open. Note: There is no guarantee that this will be a fast operation on the server. Also, do not call this on the currently open mailbox. */
status(mailboxName : string, callback : (error : Error, mailbox: Box) => void) : void;
status(mailboxName: string, callback: (error: Error, mailbox: Box) => void): void;
/** Obtains the full list of mailboxes. If nsPrefix is not specified, the main personal namespace is used. */
getBoxes(callback : (error : Error, mailboxes: MailBoxes) => void) : void;
getBoxes(nsPrefix : string, callback : (error : Error, mailboxes: MailBoxes) => void) : void;
getBoxes(callback: (error: Error, mailboxes: MailBoxes) => void): void;
getBoxes(nsPrefix: string, callback: (error: Error, mailboxes: MailBoxes) => void): void;
/** Obtains the full list of subscribed mailboxes. If nsPrefix is not specified, the main personal namespace is used. */
getSubscribedBoxes(callback : (error : Error, mailboxes: MailBoxes) => void) : void;
getSubscribedBoxes(nsPrefix : string, callback : (error : Error, mailboxes: MailBoxes) => void) : void;
getSubscribedBoxes(callback: (error: Error, mailboxes: MailBoxes) => void): void;
getSubscribedBoxes(nsPrefix: string, callback: (error: Error, mailboxes: MailBoxes) => void): void;
/** Permanently removes all messages flagged as Deleted in the currently open mailbox. If the server supports the 'UIDPLUS' capability, uids can be supplied to only remove messages that both have their uid in uids and have the \Deleted flag set. Note: At least on Gmail, performing this operation with any currently open mailbox that is not the Spam or Trash mailbox will merely archive any messages marked as Deleted (by moving them to the 'All Mail' mailbox). */
expunge(callback : (error : Error) => void) : void;
expunge(uids : any /* MessageSource */, callback : (error : Error) => void) : void;
// Appends a message to selected mailbox. msgData is a string or Buffer containing an RFC-822 compatible MIME message. Valid options properties are:
append(msgData : any, callback : (error : Error) => void) : void;
append(msgData : any, options : AppendOptions, callback : (error : Error) => void) : void;
expunge(callback: (error: Error) => void): void;
expunge(uids: any /* MessageSource */, callback: (error: Error) => void): void;
/** Appends a message to selected mailbox. msgData is a string or Buffer containing an RFC-822 compatible MIME message. Valid options properties are: */
append(msgData: any, callback: (error: Error) => void): void;
append(msgData: any, options: AppendOptions, callback: (error: Error) => void): void;
}
}
declare module "imap" {
var out: typeof IMAP.Connection;
export = out;
}
+27
View File
@@ -0,0 +1,27 @@
/// <reference path="jsf.d.ts" />
function callbackWithoutData() {
}
function callback(data:jsf.ajax.RequestData) {
}
class RequestOptionsImpl implements jsf.ajax.RequestOptions {
execute = "@all";
render = "@none";
}
jsf.ajax.addOnEvent(callbackWithoutData);
jsf.ajax.addOnEvent(callback);
jsf.ajax.addOnError(callbackWithoutData);
jsf.ajax.addOnError(callback);
jsf.ajax.request("someSource");
jsf.ajax.request("someSource", "change");
jsf.ajax.request("someSource", "change", new RequestOptionsImpl());
jsf.ajax.response("someRequestObject", {context: "someContextObject"});
+72
View File
@@ -0,0 +1,72 @@
// Type definitions for for the JSF 2.0 Ajax request API
// Project: https://docs.oracle.com/cd/E17802_01/j2ee/javaee/javaserverfaces/2.0/docs/js-api/symbols/jsf.ajax.html
// Definitions by: Lars Michaelis and Stephan Zerhusen <https://github.com/ButterFaces/ButterFaces>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module jsf {
module ajax {
interface RequestData {
status: string;
description: string;
}
interface RequestOptions {
/**
* space seperated list of client identifiers
*/
execute?: String;
/**
* space seperated list of client identifiers
*/
render?: String;
/**
* function to callback for event
* @param callback the callback function
*/
onevent?(callback:(data:RequestData) => void): void;
/**
* function to callback for error
* @param callback the callback function
*/
onerror?(callback:(data:RequestData) => void): void;
/**
* object containing parameters to include in the request
*/
params?: any;
}
/**
* Register a callback for event handling.
* @param callback a reference to a function to call on an event
*/
function addOnEvent(callback:(data:RequestData) => void):void;
/**
* Register a callback for error handling.
* @param callback a reference to a function to call on an error
*/
function addOnError(callback:(data:RequestData) => void):void;
/**
* Send an asynchronous Ajax request to the server.
* @param source The DOM element that triggered this Ajax request, or an id string of the element to use as the triggering element.
* @param event The DOM event that triggered this Ajax request. The event argument is optional.
* @param options The set of available options that can be sent as request parameters to control client and/or server side request processing.
*/
function request(source:any, event?:String, options?:RequestOptions):void;
/**
* Receive an Ajax response from the server.
* @param request The XMLHttpRequest instance that contains the status code and response message from the server.
* @param context An object containing the request context, including the following properties: the source element, per call onerror callback function, and per call onevent callback function.
* @throws EmptyResponse error if request contains no data
*/
function response(request:any, context:any):void;
}
}
+6
View File
@@ -37,3 +37,9 @@ cropboxWithOptions.update();
cropboxWithOptions.getDataURL();
cropboxWithOptions.getBlob();
cropboxWithOptions.remove();
cropboxWithOptions.on("cropbox",(e: Event, data: any, img: jQueryCropBox.Cropbox) => {
//DoStuff
});
+7
View File
@@ -103,7 +103,14 @@ declare module jQueryCropBox {
* Remove the cropbox functionality from the image.
*/
remove(): void;
/**
* Attach an event handler function for one event on the Crop Box
*/
on(event: string, callback: jQueryCropBox.EventCallback): void;
}
type EventCallback = (e: Event, data: any, img: jQueryCropBox.Cropbox) => void;
}
interface JQuery {
+2 -1
View File
@@ -362,7 +362,8 @@ declare module JQueryUI {
title?: string;
width?: any; // number or string
zIndex?: number;
open?: DialogEvent;
close?: DialogEvent;
}
+4 -3
View File
@@ -30,9 +30,9 @@ interface KnockoutObservableArrayFunctions<T> {
push(...items: T[]): void;
shift(): T;
unshift(...items: T[]): number;
reverse(): T[];
sort(): void;
sort(compareFunction: (left: T, right: T) => number): void;
reverse(): KnockoutObservableArray<T>;
sort(): KnockoutObservableArray<T>;
sort(compareFunction: (left: T, right: T) => number): KnockoutObservableArray<T>;
// Ko specific
[key: string]: KnockoutBindingHandler;
@@ -562,6 +562,7 @@ declare module KnockoutComponentTypes {
}
interface ComponentConfig {
viewModel?: ViewModelFunction | ViewModelSharedInstance | ViewModelFactoryFunction | AMDModule;
template: any;
createViewModel?: any;
}
+144
View File
@@ -0,0 +1,144 @@
/**
* Created by itboy on 11/22/2015.
*/
///<reference path="lobibox.d.ts"/>
///<reference path="../jquery/jquery.d.ts"/>
//Run test : LobiboxTest.test() after window load event
class LobiboxTest {
static test() {
// extending default parameters
Lobibox.notify.DEFAULTS = $.extend({}, Lobibox.notify.DEFAULTS, {
//override any options from default options
delay: false,
soundPath: '/libraries/lobibox/sounds/',
size: 'mini'
});
// notify
Lobibox.notify("error", {msg: "Hello world"});
Lobibox.notify("success", {msg: "Hello world"});
Lobibox.notify("warning", {msg: "Hello world"});
Lobibox.notify("info", {msg: "Hello world"});
// alert
Lobibox.alert("error", {msg: "Hello world"});
Lobibox.alert("success", {msg: "Hello world"});
Lobibox.alert("warning", {msg: "Hello world"});
Lobibox.alert("info", {msg: "Hello world"});
//alert with more options
Lobibox.alert('error', {
msg: 'This is an error message',
//buttons: ['ok', 'cancel', 'yes', 'no'],
//Or more powerfull way
buttons: {
ok: {
'class': 'btn btn-info',
closeOnClick: false
},
cancel: {
'class': 'btn btn-danger',
closeOnClick: false
},
yes: {
'class': 'btn btn-success',
closeOnClick: false
},
no: {
'class': 'btn btn-warning',
closeOnClick: false
},
custom: {
'class': 'btn btn-default',
text: 'Custom'
}
},
callback: function (lobibox:any, type:string):any {
let btnType:string = "";
if (type === 'no') {
btnType = 'warning';
} else if (type === 'yes') {
btnType = 'success';
} else if (type === 'ok') {
btnType = 'info';
} else if (type === 'cancel') {
btnType = 'error';
}
Lobibox.notify(btnType, {
size: 'mini',
msg: 'This is ' + btnType + ' message'
});
}
});
// confirm
Lobibox.confirm({
msg: "Are you ok",
});
// prompt
Lobibox.prompt("text", {
title: 'Please enter username',
//Attributes of <input>
attrs: {
placeholder: "Username"
}
});
// progress
Lobibox.progress({
title: 'Please wait',
label: 'Uploading files...',
onShow: function ($this:any):void {
var i = 0;
var inter = setInterval(function ():void {
window.console.log(i);
if (i > 100) {
clearInterval(inter);
}
i = i + 0.1;
$this.setProgress(i);
}, 10);
}
});
// window
Lobibox.window({
title: 'Window title',
//Available types: string, jquery object, function
content: function ():any {
return $('.container');
},
url: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.css',
autoload: false,
loadMethod: 'GET',
//Load parameters
params: {
param1: 'Lorem',
param2: 'Ipsum'
},
buttons: {
load: {
text: 'Load from url'
},
close: {
text: 'Close',
closeOnClick: true
}
},
callback: function ($this:any, type:string, ev:any):void {
if (type === 'load') {
$this.load(function ():any {
//Do something when content is loaded
});
}
}
});
}
}
window.onload = (): void => {
LobiboxTest.test();
};
+197
View File
@@ -0,0 +1,197 @@
// Type definitions for lobibox 1.0.1
// Project: https://github.com/arboshiki/lobibox
// Definitions by: Sabeeh Ul Hussnain <https://github.com/itboy87>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var Lobibox: LobiboxModule.LobiboxStatic;
declare module "Lobibox" {
export = Lobibox;
}
declare module LobiboxModule {
interface MessageBoxesDefault {
title? : string;
horizontalOffset?: number;
width? : number;
height? : string; // Height is automatically given calculated by width
closeButton? : boolean; // Show close button or not
draggable? : boolean; // Make messagebox draggable
customBtnClass? : string; // Class for custom buttons
modal? : boolean;
debug? : boolean;
buttonsAlign? : string; // Position where buttons should be aligned
closeOnEsc? : boolean; // Close messagebox on Esc press
delayToRemove? : number;
baseClass? : string;
showClass? : string;
hideClass? : string;
msg? : string;
// methods
hide? (): MessageBoxesDefault;
show? (): MessageBoxesDefault;
setWidth? (width?: number): MessageBoxesDefault;
setHeight? (height?: number): MessageBoxesDefault;
setSize? (width?: number, height?: number): MessageBoxesDefault;
setPosition? (left?: number|string, top?: number): MessageBoxesDefault;
setTitle? (title?: string): MessageBoxesDefault;
getTitle? (): string;
// events
// when messagebox show is called but before it is actually shown
onShow? (lobibox:any): void ;
// after messagebox is shown
shown? (lobibox:any): void;
// when messagebox remove method is called but before it is actually hidden
beforeClose? (lobibox:any): void;
// after messagebox is hidden
closed? (lobibox:any): void;
}
interface MessageBoxesOptions extends MessageBoxesDefault {
bodyClass? : string;
modalClasses? : {
'error'? : string,
'success'? : string,
'info'? : string,
'warning'? : string,
'confirm'? : string,
'progress'? : string,
'prompt'? : string,
'default'? : string,
'window'? : string
},
buttonsAlign?: any;
buttons?: {
ok?: {
'class'?: string,
text?: string,
closeOnClick?: boolean
},
cancel?: {
'class'?: string,
text?: string,
closeOnClick?: boolean
},
yes?: {
'class'?: string,
text?: string,
closeOnClick?: boolean
},
no?: {
'class'?: string,
text?: string,
closeOnClick?: boolean
},
}|any;
callback? (lobibox:any, type?:string, ev?: any): void;
}
interface ConfirmOptions extends MessageBoxesOptions {
title? : string;
width? : number;
iconClass? : string;
}
interface PromptOptions extends MessageBoxesOptions, PromptMethods {
width?: number;
attrs?: any; // Object of any valid attribute of input field
value?: string; // Value which is given to textfield when messagebox is created
multiline?: boolean; // Set this true for multiline prompt
lines?: number; // This works only for multiline prompt. Number of lines
type?: string; // Prompt type. Available types (text|number|color)
label?: string; // Set some text which will be shown exactly on top of textfield
}
interface AlertOptions extends MessageBoxesOptions {
warning?: {
title?: string,
iconClass?: string // Change warning alert icon globally
};
info?:{
title?: string,
iconClass?: string // Change info alert icon globally
};
success?: {
title?: string,
iconClass?: string // Change success alert icon globally
};
error?: {
title?: string,
iconClass?: string // Change error alert icon globally
};
}
interface ProgressOptions extends MessageBoxesOptions, ProgressMethods, ProgressEvents {
width? : number;
showProgressLabel? : boolean; // Show percentage of progress
label? : string; // Show progress label
progressTpl? : boolean; //Template of progress bar
//Events
progressUpdated? : any;
progressCompleted? : any;
}
interface WindowOptions extends MessageBoxesOptions {
width? : number;
height? : any;
content? : any; // HTML Content of window
url? : string; // URL which will be used to load content
draggable? : boolean; // Override default option
autoload? : boolean; // Auto load from given url when window is created
loadMethod? : string; // Ajax method to load content
showAfterLoad? : boolean; // Show window after content is loaded or show and then load content
params? : {}; // Parameters which will be send by ajax for loading content
}
interface ProgressEvents {
progressUpdated? (lobibox:LobiboxStatic): void;
progressComplete? (lobibox:LobiboxStatic): void;
}
interface PromptMethods {
setValue? (val?:string): PromptMethods;
getValue? (): string;
}
interface ProgressMethods {
setProgress? (progress:number): ProgressMethods;
getProgress? (): number;
}
interface NotifyDefault {
title?: boolean; // Title of notification. If you do not include the title in options it will automatically takes its value
//from Lobibox.notify.OPTIONS object depending of the type of the notifications or set custom string. Set this false to disable title
size?: string; // normal, mini, large
soundPath?: string; // The folder path where sounds are located
soundExt?: string; // Default extension for all sounds
showClass?: string; // Show animation class.
hideClass?: string; // Hide animation class.
icon?: boolean; // Icon of notification. Leave as is for default icon or set custom string
msg?: string; // Message of notification
img?: string; // Image source string
closable?: boolean; // Make notifications closable
delay?: number; // Hide notification after this time (in miliseconds)
delayIndicator?: boolean; // Show timer indicator
closeOnClick?: boolean; // Close notifications by clicking on them
width?: number; // Width of notification box
sound?: boolean; // Sound of notification. Set this false to disable sound. Leave as is for default sound or set custom soud path
position?: string; // Place to show notification. Available options: "top left", "top right", "bottom left", "bottom right"
}
interface NotifyOptions extends NotifyDefault, NotifyMethods {
'class'?: string; //You can override options for large notifications from here
large?: {width?: number}; //You can override options for small notifications from here
mini?: {'class'?: string}; //Default options of different style notifications
success?: {'class'?: string, 'title'?: string,'icon'?: string,sound?: string};
error?: {'class'?: string, 'title'?: string,'icon'?: string,sound?: string};
warning?: {'class'?: string, 'title'?: string,'icon'?: string,sound?: string};
info?: {'class'?: string, 'title'?: string,'icon'?: string,sound?: string};
}
interface NotifyMethods {
remove? (): any;
}
interface LobiboxStatic {
base: {OPTIONS: MessageBoxesOptions, DEFAULTS: MessageBoxesDefault};
alert: {<T extends MessageBoxesDefault>(type: string, options?: T): LobiboxStatic, DEFAULTS: AlertOptions};
prompt: {<T extends MessageBoxesDefault>(type: string, options?: T): LobiboxStatic, DEFAULTS: PromptOptions};
confirm: {<T extends MessageBoxesDefault>(options?: ConfirmOptions): T, DEFAULTS: ConfirmOptions};
progress: {<T extends MessageBoxesDefault>(options: ProgressOptions): T, DEFAULTS: ProgressOptions};
window: {<T extends MessageBoxesDefault>(options: WindowOptions): T, DEFAULTS: WindowOptions};
notify: {<T extends NotifyDefault>(type: string, options?: NotifyOptions): T, DEFAULTS?: NotifyDefault,OPTIONS?:NotifyOptions};
}
}
+182 -68
View File
@@ -4658,22 +4658,31 @@ module TestBackflow {
}
// _.before
var testBeforeFn = ((n: number) => () => ++n)(0);
var testBeforeResultFn = <() => number>_.before<() => number>(3, testBeforeFn);
result = <number>testBeforeResultFn();
// → 1
result = <number>testBeforeResultFn();
// → 2
result = <number>testBeforeResultFn();
// → 2
var testBeforeFn = ((n: number) => () => ++n)(0);
var testBeforeResultFn = <() => number>_(3).before<() => number>(testBeforeFn);
result = <number>testBeforeResultFn();
// → 1
result = <number>testBeforeResultFn();
// → 2
result = <number>testBeforeResultFn();
// → 2
module TestBefore {
interface Func {
(a: string, b: number): boolean;
}
let func: Func;
{
let result: Func;
_.before(42, func);
}
{
let result: _.LoDashImplicitObjectWrapper<Func>;
_(42).before(func);
}
{
let result: _.LoDashExplicitObjectWrapper<Func>;
_(42).chain().before(func);
}
}
var funcBind = function(greeting: string, punctuation: string) { return greeting + ' ' + this.user + punctuation; };
var funcBound1: (punctuation: string) => any = _.bind(funcBind, { 'name': 'moe' }, 'hi');
@@ -4891,10 +4900,34 @@ module TestDelay {
}
// _.flow
var testFlowSquareFn = (n: number) => n * n;
var testFlowAddFn = (n: number, m: number) => n + m;
result = <number>_.flow<(n: number, m: number) => number>(testFlowAddFn, testFlowSquareFn)(1, 2);
result = <number>_(testFlowAddFn).flow<(n: number, m: number) => number>(testFlowSquareFn).value()(1, 2);
module TestFlow {
let Fn1: (n: number) => number;
let Fn2: (m: number, n: number) => number;
{
let result: (m: number, n: number) => number;
result = _.flow<(m: number, n: number) => number>(Fn1, Fn2);
result = _.flow<(m: number, n: number) => number>(Fn1, Fn1, Fn2);
result = _.flow<(m: number, n: number) => number>(Fn1, Fn1, Fn1, Fn2);
}
{
let result: _.LoDashImplicitObjectWrapper<(m: number, n: number) => number>;
result = _(Fn1).flow<(m: number, n: number) => number>(Fn2);
result = _(Fn1).flow<(m: number, n: number) => number>(Fn1, Fn2);
result = _(Fn1).flow<(m: number, n: number) => number>(Fn1, Fn1, Fn2);
}
{
let result: _.LoDashExplicitObjectWrapper<(m: number, n: number) => number>;
result = _(Fn1).chain().flow<(m: number, n: number) => number>(Fn2);
result = _(Fn1).chain().flow<(m: number, n: number) => number>(Fn1, Fn2);
result = _(Fn1).chain().flow<(m: number, n: number) => number>(Fn1, Fn1, Fn2);
}
}
// _.flowRight
module TestFlowRight {
@@ -4994,17 +5027,38 @@ module TestModArgs {
}
// _.negate
interface TestNegatePredicate {
(a1: number, a2: number): boolean;
module TestNegate {
interface PredicateFn {
(a1: number, a2: number): boolean;
}
interface ResultFn {
(a1: number, a2: number): boolean;
}
var predicate = (a1: number, a2: number) => a1 > a2;
{
let result: ResultFn;
result = _.negate<PredicateFn>(predicate);
result = _.negate<PredicateFn, ResultFn>(predicate);
}
{
let result: _.LoDashImplicitObjectWrapper<ResultFn>;
result = _(predicate).negate();
result = _(predicate).negate<ResultFn>();
}
{
let result: _.LoDashExplicitObjectWrapper<ResultFn>;
result = _(predicate).chain().negate();
result = _(predicate).chain().negate<ResultFn>();
}
}
interface TestNegateResult {
(a1: number, a2: number): boolean;
}
var testNegatePredicate = (a1: number, a2: number) => a1 > a2;
result = <TestNegateResult>_.negate<TestNegatePredicate>(testNegatePredicate);
result = <TestNegateResult>_.negate<TestNegatePredicate, TestNegateResult>(testNegatePredicate);
result = <TestNegateResult>_(testNegatePredicate).negate().value();
result = <TestNegateResult>_(testNegatePredicate).negate<TestNegateResult>().value();
// _.once
module TestOnce {
@@ -5337,20 +5391,33 @@ result = <boolean>_({}).isArray();
}
// _.isBoolean
result = <boolean>_.isBoolean(any);
result = <boolean>_(1).isBoolean();
result = <boolean>_<any>([]).isBoolean();
result = <boolean>_({}).isBoolean();
{
let value: number[]|boolean = [1, 3, 5];
if (_.isBoolean(value)) {
let b: boolean = value;
// compile error
// let length: number = value.length;
} else {
let length: number = value.length;
// compile error
// let b: boolean = value;
module TestIsBoolean {
{
let value: number|boolean;
if (_.isBoolean(value)) {
let result: boolean = value;
}
else {
let result: number = value;
}
}
{
let result: boolean;
result = _.isBoolean(any);
result = _(1).isBoolean();
result = _<any>([]).isBoolean();
result = _({}).isBoolean();
}
{
let result: _.LoDashExplicitWrapper<boolean>;
result = _(1).chain().isBoolean();
result = _<any>([]).chain().isBoolean();
result = _({}).chain().isBoolean();
}
}
@@ -7073,19 +7140,43 @@ module TestFunctions {
}
}
interface HasName {
name: string;
// _.omit
module TestOmit {
let predicate: (element: any, key: string, collection: any) => boolean;
{
let result: TResult;
result = _.omit<TResult, Object>({}, 'a');
result = _.omit<TResult, Object>({}, 0, 'a');
result = _.omit<TResult, Object>({}, true, 0, 'a');
result = _.omit<TResult, Object>({}, ['b', 1, false], true, 0, 'a');
result = _.omit<TResult, Object>({}, predicate);
result = _.omit<TResult, Object>({}, predicate, any);
}
{
let result: _.LoDashImplicitObjectWrapper<TResult>;
result = _({}).omit<TResult>('a');
result = _({}).omit<TResult>(0, 'a');
result = _({}).omit<TResult>(true, 0, 'a');
result = _({}).omit<TResult>(['b', 1, false], true, 0, 'a');
result = _({}).omit<TResult>(predicate);
result = _({}).omit<TResult>(predicate, any);
}
{
let result: _.LoDashExplicitObjectWrapper<TResult>;
result = _({}).chain().omit<TResult>('a');
result = _({}).chain().omit<TResult>(0, 'a');
result = _({}).chain().omit<TResult>(true, 0, 'a');
result = _({}).chain().omit<TResult>(['b', 1, false], true, 0, 'a');
result = _({}).chain().omit<TResult>(predicate);
result = _({}).chain().omit<TResult>(predicate, any);
}
}
result = <HasName>_.omit({ 'name': 'moe', 'age': 40 }, 'age');
result = <HasName>_.omit({ 'name': 'moe', 'age': 40 }, ['age']);
result = <HasName>_.omit({ 'name': 'moe', 'age': 40 }, function (value) {
return typeof value == 'number';
});
result = <HasName>_({ 'name': 'moe', 'age': 40 }).omit('age').value();
result = <HasName>_({ 'name': 'moe', 'age': 40 }).omit(['age']).value();
result = <HasName>_({ 'name': 'moe', 'age': 40 }).omit(function (value) {
return typeof value == 'number';
}).value();
// _.pairs
module TestPairs {
@@ -7129,18 +7220,41 @@ module TestPairs {
}
// _.pick
interface TestPickFn {
(element: any, key: string, collection: any): boolean;
}
{
let testPickFn: TestPickFn;
let result: TResult;
result = _.pick<TResult, Object>({}, 0, '1', true, [2], ['3'], [true], [4, '5', true]);
result = _.pick<TResult, Object>({}, testPickFn);
result = _.pick<TResult, Object>({}, testPickFn, any);
result = _({}).pick<TResult>(0, '1', true, [2], ['3'], [true], [4, '5', true]).value();
result = _({}).pick<TResult>(testPickFn).value();
result = _({}).pick<TResult>(testPickFn, any).value();
module TestPick {
let predicate: (element: any, key: string, collection: any) => boolean;
{
let result: TResult;
result = _.pick<TResult, Object>({}, 'a');
result = _.pick<TResult, Object>({}, 0, 'a');
result = _.pick<TResult, Object>({}, true, 0, 'a');
result = _.pick<TResult, Object>({}, ['b', 1, false], true, 0, 'a');
result = _.pick<TResult, Object>({}, predicate);
result = _.pick<TResult, Object>({}, predicate, any);
}
{
let result: _.LoDashImplicitObjectWrapper<TResult>;
result = _({}).pick<TResult>('a');
result = _({}).pick<TResult>(0, 'a');
result = _({}).pick<TResult>(true, 0, 'a');
result = _({}).pick<TResult>(['b', 1, false], true, 0, 'a');
result = _({}).pick<TResult>(predicate);
result = _({}).pick<TResult>(predicate, any);
}
{
let result: _.LoDashExplicitObjectWrapper<TResult>;
result = _({}).chain().pick<TResult>('a');
result = _({}).chain().pick<TResult>(0, 'a');
result = _({}).chain().pick<TResult>(true, 0, 'a');
result = _({}).chain().pick<TResult>(['b', 1, false], true, 0, 'a');
result = _({}).chain().pick<TResult>(predicate);
result = _({}).chain().pick<TResult>(predicate, any);
}
}
// _.result
+115 -50
View File
@@ -8048,20 +8048,31 @@ declare module _ {
interface LoDashStatic {
/**
* Creates a function that invokes func, with the this binding and arguments of the created function, while
* it is called less than n times. Subsequent calls to the created function return the result of the last func
* its called less than n times. Subsequent calls to the created function return the result of the last func
* invocation.
*
* @param n The number of calls at which func is no longer invoked.
* @param func The function to restrict.
* @return Returns the new restricted function.
*/
before<TFunc extends Function>(n: number, func: TFunc): TFunc;
before<TFunc extends Function>(
n: number,
func: TFunc
): TFunc;
}
interface LoDashImplicitWrapper<T> {
/**
* @sed _.before
*/
before<TFunc extends Function>(func: TFunc): TFunc;
* @see _.before
**/
before<TFunc extends Function>(func: TFunc): LoDashImplicitObjectWrapper<TFunc>;
}
interface LoDashExplicitWrapper<T> {
/**
* @see _.before
**/
before<TFunc extends Function>(func: TFunc): LoDashExplicitObjectWrapper<TFunc>;
}
//_.bind
@@ -8491,6 +8502,7 @@ declare module _ {
/**
* Creates a function that returns the result of invoking the provided functions with the this binding of the
* created function, where each successive invocation is supplied the return value of the previous.
*
* @param funcs Functions to invoke.
* @return Returns the new function.
*/
@@ -8500,10 +8512,17 @@ declare module _ {
interface LoDashImplicitObjectWrapper<T> {
/**
* @see _.flow
**/
*/
flow<TResult extends Function>(...funcs: Function[]): LoDashImplicitObjectWrapper<TResult>;
}
interface LoDashExplicitObjectWrapper<T> {
/**
* @see _.flow
*/
flow<TResult extends Function>(...funcs: Function[]): LoDashExplicitObjectWrapper<TResult>;
}
//_.flowRight
interface LoDashStatic {
/**
@@ -8613,6 +8632,7 @@ declare module _ {
/**
* Creates a function that negates the result of the predicate func. The func predicate is invoked with
* the this binding and arguments of the created function.
*
* @param predicate The predicate to negate.
* @return Returns the new function.
*/
@@ -8636,6 +8656,18 @@ declare module _ {
negate<TResult extends Function>(): LoDashImplicitObjectWrapper<TResult>;
}
interface LoDashExplicitObjectWrapper<T> {
/**
* @see _.negate
*/
negate(): LoDashExplicitObjectWrapper<(...args: any[]) => boolean>;
/**
* @see _.negate
*/
negate<TResult extends Function>(): LoDashExplicitObjectWrapper<TResult>;
}
//_.once
interface LoDashStatic {
/**
@@ -9212,9 +9244,10 @@ declare module _ {
interface LoDashStatic {
/**
* Checks if value is classified as a boolean primitive or object.
*
* @param value The value to check.
* @return Returns true if value is correctly classified, else false.
**/
*/
isBoolean(value?: any): value is boolean;
}
@@ -9225,6 +9258,13 @@ declare module _ {
isBoolean(): boolean;
}
interface LoDashExplicitWrapperBase<T, TWrapper> {
/**
* @see _.isBoolean
*/
isBoolean(): LoDashExplicitWrapper<boolean>;
}
//_.isDate
interface LoDashStatic {
/**
@@ -11842,54 +11882,62 @@ declare module _ {
//_.omit
interface LoDashStatic {
/**
* Creates a shallow clone of object excluding the specified properties. Property names may be
* specified as individual arguments or as arrays of property names. If a callback is provided
* it will be executed for each property of object omitting the properties the callback returns
* truey for. The callback is bound to thisArg and invoked with three arguments; (value, key,
* object).
* @param object The source object.
* @param keys The properties to omit.
* @return An object without the omitted properties.
**/
omit<Omitted, T>(
* The opposite of _.pick; this method creates an object composed of the own and inherited enumerable
* properties of object that are not omitted.
*
* @param object The source object.
* @param predicate The function invoked per iteration or property names to omit, specified as individual
* property names or arrays of property names.
* @param thisArg The this binding of predicate.
* @return Returns the new object.
*/
omit<TResult extends {}, T extends {}>(
object: T,
...keys: string[]): Omitted;
predicate: ObjectIterator<any, boolean>,
thisArg?: any
): TResult;
/**
* @see _.omit
**/
omit<Omitted, T>(
* @see _.omit
*/
omit<TResult extends {}, T extends {}>(
object: T,
keys: string[]): Omitted;
/**
* @see _.omit
**/
omit<Omitted, T>(
object: T,
callback: ObjectIterator<any, boolean>,
thisArg?: any): Omitted;
...predicate: (StringRepresentable|StringRepresentable[])[]
): TResult;
}
interface LoDashImplicitObjectWrapper<T> {
/**
* @see _.omit
**/
omit<Omitted>(
...keys: string[]): LoDashImplicitObjectWrapper<Omitted>;
* @see _.omit
*/
omit<TResult extends {}>(
predicate: ObjectIterator<any, boolean>,
thisArg?: any
): LoDashImplicitObjectWrapper<TResult>;
/**
* @see _.omit
**/
omit<Omitted>(
keys: string[]): LoDashImplicitObjectWrapper<Omitted>;
* @see _.omit
*/
omit<TResult extends {}>(
...predicate: (StringRepresentable|StringRepresentable[])[]
): LoDashImplicitObjectWrapper<TResult>;
}
interface LoDashExplicitObjectWrapper<T> {
/**
* @see _.omit
*/
omit<TResult extends {}>(
predicate: ObjectIterator<any, boolean>,
thisArg?: any
): LoDashExplicitObjectWrapper<TResult>;
/**
* @see _.omit
**/
omit<Omitted>(
callback: ObjectIterator<any, boolean>,
thisArg?: any): LoDashImplicitObjectWrapper<Omitted>;
* @see _.omit
*/
omit<TResult extends {}>(
...predicate: (StringRepresentable|StringRepresentable[])[]
): LoDashExplicitObjectWrapper<TResult>;
}
//_.pairs
@@ -11931,9 +11979,9 @@ declare module _ {
* @param predicate The function invoked per iteration or property names to pick, specified as individual
* property names or arrays of property names.
* @param thisArg The this binding of predicate.
* @return An object composed of the picked properties.
* @return Returns the new object.
*/
pick<TResult extends Object, T extends Object>(
pick<TResult extends {}, T extends {}>(
object: T,
predicate: ObjectIterator<any, boolean>,
thisArg?: any
@@ -11942,9 +11990,9 @@ declare module _ {
/**
* @see _.pick
*/
pick<TResult extends Object, T extends Object>(
pick<TResult extends {}, T extends {}>(
object: T,
...predicate: Array<string|number|boolean|Array<string|number|boolean>>
...predicate: (StringRepresentable|StringRepresentable[])[]
): TResult;
}
@@ -11952,7 +12000,7 @@ declare module _ {
/**
* @see _.pick
*/
pick<TResult extends Object>(
pick<TResult extends {}>(
predicate: ObjectIterator<any, boolean>,
thisArg?: any
): LoDashImplicitObjectWrapper<TResult>;
@@ -11960,11 +12008,28 @@ declare module _ {
/**
* @see _.pick
*/
pick<TResult extends Object>(
...predicate: Array<string|number|boolean|Array<string|number|boolean>>
pick<TResult extends {}>(
...predicate: (StringRepresentable|StringRepresentable[])[]
): LoDashImplicitObjectWrapper<TResult>;
}
interface LoDashExplicitObjectWrapper<T> {
/**
* @see _.pick
*/
pick<TResult extends {}>(
predicate: ObjectIterator<any, boolean>,
thisArg?: any
): LoDashExplicitObjectWrapper<TResult>;
/**
* @see _.pick
*/
pick<TResult extends {}>(
...predicate: (StringRepresentable|StringRepresentable[])[]
): LoDashExplicitObjectWrapper<TResult>;
}
//_.result
interface LoDashStatic {
/**
+1
View File
@@ -16,4 +16,5 @@ declare module "mime" {
}
export var charsets: Charsets;
export var default_type: string;
}
+15 -5
View File
@@ -8,24 +8,27 @@
declare module "natural" {
import events = require("events");
class WordTokenizer {
interface Tokenizer {
tokenize(text: string): string[];
}
class AggressiveTokenizer {
class WordTokenizer implements Tokenizer {
tokenize(text: string): string[];
}
class TreebankWordTokenizer {
class AggressiveTokenizer implements Tokenizer {
tokenize(text: string): string[];
}
class TreebankWordTokenizer implements Tokenizer {
tokenize(text: string): string[];
}
interface RegexTokenizerOptions {
pattern: RegExp;
discardEmpty?: boolean;
}
class RegexpTokenizer {
class RegexpTokenizer implements Tokenizer {
constructor(options: RegexTokenizerOptions);
tokenize(text: string): string[];
}
class WordPunctTokenizer {
class WordPunctTokenizer implements Tokenizer {
tokenize(text: string): string[];
}
@@ -60,6 +63,9 @@ declare module "natural" {
var PorterStemmerPt: {
stem(token: string): string;
}
var LancasterStemmer: {
stem(token: string): string;
}
interface BayesClassifierCallback { (err: any, classifier: any): void }
class BayesClassifier {
@@ -74,6 +80,10 @@ declare module "natural" {
static restore(classifier: any, stemmer?: Stemmer): BayesClassifier;
}
interface Phonetic {
compare(stringA: string, stringB: string): boolean;
process(token: string, maxLength?: number): string;
}
var Metaphone: {
compare(stringA: string, stringB: string): boolean;
process(token: string, maxLength?: number): string;
+15 -6
View File
@@ -38,8 +38,8 @@ module NavigationTests {
// Configuration
Navigation.StateInfoConfig.build([
{ key: 'home', initial: 'page', states: [
{ key: 'page', route: '' }
{ key: 'home', initial: 'page', help: 'home.htm', states: [
{ key: 'page', route: '', help: 'page.htm' }
]},
{ key: 'person', initial: 'list', states: [
{ key: 'list', route: ['people/{page}', 'people/{page}/sort/{sort}'], transitions: [
@@ -97,24 +97,28 @@ module NavigationTests {
// Navigation
Navigation.start('home');
Navigation.StateController.navigate('person');
Navigation.StateController.navigate('person', null, Navigation.HistoryAction.Add);
Navigation.StateController.refresh();
Navigation.StateController.refresh({ page: 2 });
Navigation.StateController.refresh({ page: 3 });
Navigation.StateController.refresh({ page: 2 }, Navigation.HistoryAction.Replace);
Navigation.StateController.navigate('select', { id: 10 });
var canGoBack: boolean = Navigation.StateController.canNavigateBack(1);
Navigation.StateController.navigateBack(1);
Navigation.StateController.clearStateContext();
// Navigation Link
var link = Navigation.StateController.getNavigationLink('person');
link = Navigation.StateController.getRefreshLink();
link = Navigation.StateController.getRefreshLink({ page: 2 });
Navigation.StateController.navigateLink(link);
link = Navigation.StateController.getNavigationLink('select', { id: 10 });
var nextDialog = Navigation.StateController.getNextState('select').parent;
person = nextDialog;
Navigation.StateController.navigateLink(link);
Navigation.StateController.navigateLink(link, false);
link = Navigation.StateController.getNavigationBackLink(1);
var crumb = Navigation.StateController.crumbs[0];
link = crumb.navigationLink;
Navigation.StateController.navigateLink(link, true);
Navigation.StateController.navigateLink(link, true, Navigation.HistoryAction.None);
// StateContext
Navigation.StateController.navigate('home');
@@ -124,10 +128,15 @@ module NavigationTests {
person === Navigation.StateContext.dialog;
personList === Navigation.StateContext.state;
var url: string = Navigation.StateContext.url;
var title: string = Navigation.StateContext.title;
var page: number = Navigation.StateContext.data.page;
Navigation.StateController.refresh({ page: 2 });
person = Navigation.StateContext.oldDialog;
personList = Navigation.StateContext.oldState;
page = Navigation.StateContext.oldData.page;
page = Navigation.StateContext.previousData.page;
// Navigation Data
Navigation.StateController.refresh({ page: 2 });
var data = Navigation.StateContext.includeCurrentData({ sort: 'name' }, ['page']);
Navigation.StateController.refresh(data);
Navigation.StateContext.clear('sort');
+123 -4
View File
@@ -1,4 +1,4 @@
// Type definitions for Navigation 1.1.0
// Type definitions for Navigation 1.2.0
// Project: http://grahammendick.github.io/navigation/
// Definitions by: Graham Mendick <https://github.com/grahammendick>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -31,6 +31,10 @@ declare module Navigation {
* Gets the textual description of the dialog
*/
title?: string;
/**
* Gets the additional dialog attributes
*/
[extras: string]: any;
}
/**
@@ -75,6 +79,10 @@ declare module Navigation {
* preserved when navigating
*/
trackTypes?: boolean;
/**
* Gets the additional state attributes
*/
[extras: string]: any;
}
/**
@@ -278,6 +286,24 @@ declare module Navigation {
*/
static build(dialogs: IDialog<string, IState<ITransition<string>[]>[]>[]): void;
}
/**
* Determines the effect on browser history after a successful navigation
*/
enum HistoryAction {
/**
* Creates a new browser history entry
*/
Add = 0,
/**
* Changes the current browser history entry
*/
Replace = 1,
/**
* Leaves browser history unchanged
*/
None = 2,
}
/**
* Defines a contract a class must implement in order to manage the browser
@@ -295,9 +321,17 @@ declare module Navigation {
/**
* Adds browser history
* @param state The State navigated to
* @param url The current url
* @param url The current url
*/
addHistory(state: State, url: string): void;
/**
* Adds browser history
* @param state The State navigated to
* @param url The current url
* @param replace A value indicating whether to replace the current
* browser history entry
*/
addHistory(state: State, url: string, replace: boolean): void;
/**
* Gets the current location
*/
@@ -339,6 +373,14 @@ declare module Navigation {
* @param url The current url
*/
addHistory(state: State, url: string): void;
/**
* Sets the browser Url's hash to the url
* @param state The State navigated to
* @param url The current url
* @param replace A value indicating whether to replace the current
* browser history entry
*/
addHistory(state: State, url: string, replace: boolean): void;
/**
* Gets the current location
*/
@@ -375,6 +417,14 @@ declare module Navigation {
* @param url The current url
*/
addHistory(state: State, url: string): void;
/**
* Sets the browser Url to the url using pushState
* @param state The State navigated to
* @param url The current url
* @param replace A value indicating whether to replace the current
* browser history entry
*/
addHistory(state: State, url: string, replace: boolean): void;
/**
* Gets the current location
*/
@@ -587,6 +637,11 @@ declare module Navigation {
* ReturnData should be part of the CrumbTrail
*/
combineCrumbTrail: boolean;
/**
* Gets or sets a value indicating whether to track PreviousData when
* navigating back or refreshing and combineCrumbTrail is false
*/
trackAllPreviousData: boolean;
}
/**
@@ -595,6 +650,18 @@ declare module Navigation {
* previous State (this is not the same as the previous Crumb)
*/
class StateContext {
/**
* Gets the last State displayed before the current State
*/
static oldState: State;
/**
* Gets the parent of the OldState property
*/
static oldDialog: Dialog;
/**
* Gets the NavigationData for the last displayed State
*/
static oldData: any;
/**
* Gets the State navigated away from to reach the current State
*/
@@ -603,6 +670,10 @@ declare module Navigation {
* Gets the parent of the PreviousState property
*/
static previousDialog: Dialog;
/**
* Gets the NavigationData for the navigated away from State
*/
static previousData: any;
/**
* Gets the current State
*/
@@ -612,14 +683,17 @@ declare module Navigation {
*/
static dialog: Dialog;
/**
* Gets the NavigationData for the current State. It can be accessed.
* Will become the data stored in a Crumb when part of a crumb trail
* Gets the NavigationData for the current State
*/
static data: any;
/**
* Gets the current Url
*/
static url: string;
/**
* Gets or sets the current title
*/
static title: string;
/**
* Combines the data with all the current NavigationData
* @param The data to add to the current NavigationData
@@ -660,6 +734,10 @@ declare module Navigation {
* @param url The current Url
*/
static setStateContext(state: State, url: string): void;
/**
* Clears the Context Data
*/
static clearStateContext(): void;
/**
* Registers a navigate event listener
* @param handler The navigate event listener
@@ -694,6 +772,20 @@ declare module Navigation {
* @throws A mandatory route parameter has not been supplied a value
*/
static navigate(action: string, toData: any): void;
/**
* Navigates to a State. Depending on the action will either navigate
* to the 'to' State of a Transition or the 'initial' State of a
* Dialog
* @param action The key of a child Transition or the key of a Dialog
* @param toData The NavigationData to be passed to the next State and
* stored in the StateContext
* @param A value determining the effect on browser history
* @throws action does not match the key of a child Transition or the
* key of a Dialog; or there is NavigationData that cannot be converted
* to a String
* @throws A mandatory route parameter has not been supplied a value
*/
static navigate(action: string, toData: any, historyAction: HistoryAction): void;
/**
* Gets a Url to navigate to a State. Depending on the action will
* either navigate to the 'to' State of a Transition or the 'initial'
@@ -733,6 +825,17 @@ declare module Navigation {
* @throws A mandatory route parameter has not been supplied a value
*/
static navigateBack(distance: number): void;
/**
* Navigates back to the Crumb contained in the crumb trail,
* represented by the Crumbs collection, as specified by the distance.
* In the crumb trail no two crumbs can have the same State but all
* must have the same Dialog
* @param distance Starting at 1, the number of Crumb steps to go back
* @param A value determining the effect on browser history
* @throws canNavigateBack returns false for this distance
* @throws A mandatory route parameter has not been supplied a value
*/
static navigateBack(distance: number, historyAction: HistoryAction): void;
/**
* Gets a Url to navigate to a Crumb contained in the crumb trail,
* represented by the Crumbs collection, as specified by the distance.
@@ -755,6 +858,15 @@ declare module Navigation {
* @throws A mandatory route parameter has not been supplied a value
*/
static refresh(toData: any): void;
/**
* Navigates to the current State
* @param toData The NavigationData to be passed to the current State
* and stored in the StateContext
* @param A value determining the effect on browser history
* @throws There is NavigationData that cannot be converted to a String
* @throws A mandatory route parameter has not been supplied a value
*/
static refresh(toData: any, historyAction: HistoryAction): void;
/**
* Gets a Url to navigate to the current State passing no
* NavigationData
@@ -779,6 +891,13 @@ declare module Navigation {
* @param history A value indicating whether browser history was used
*/
static navigateLink(url: string, history: boolean): void;
/**
* Navigates to the url
* @param url The target location
* @param history A value indicating whether browser history was used
* @param A value determining the effect on browser history
*/
static navigateLink(url: string, history: boolean, historyAction: HistoryAction): void;
/**
* Gets the next State. Depending on the action will either return the
* 'to' State of a Transition or the 'initial' State of a Dialog
+2
View File
@@ -48,6 +48,8 @@ p = nconf.use(str, opts);
p = nconf.defaults();
p = nconf.defaults(opts);
p = nconf.defaults({foo: 'bar'});
nconf.init();
nconf.init(opts);
+4 -3
View File
@@ -48,11 +48,12 @@ declare module "nconf" {
parse: (str: string) => any;
}
export interface IOptions {
type?: string;
export interface IOptions {
[index: string]: any;
}
export interface IFileOptions extends IOptions {
export interface IFileOptions {
type?: string;
file?: string;
dir?: string;
search?: boolean;
+47
View File
@@ -14,6 +14,7 @@ import * as querystring from "querystring";
import * as path from "path";
import * as readline from "readline";
import * as childProcess from "child_process";
import * as os from "os";
assert(1 + 1 - 2 === 0, "The universe isn't how it should.");
@@ -411,3 +412,49 @@ rl.question("do you like typescript?", function(answer: string) {
childProcess.exec("echo test");
childProcess.spawnSync("echo test");
////////////////////////////////////////////////////
/// os tests : https://nodejs.org/api/os.html
////////////////////////////////////////////////////
module os_tests {
{
let result: string;
result = os.tmpdir();
result = os.homedir();
result = os.endianness();
result = os.hostname();
result = os.type();
result = os.platform();
result = os.arch();
result = os.release();
result = os.EOL;
}
{
let result: number;
result = os.uptime();
result = os.totalmem();
result = os.freemem();
}
{
let result: number[];
result = os.loadavg();
}
{
let result: os.CpuInfo[];
result = os.cpus();
}
{
let result: {[index: string]: os.NetworkInterfaceInfo[]};
result = os.networkInterfaces();
}
}
+25 -3
View File
@@ -698,7 +698,29 @@ declare module "zlib" {
}
declare module "os" {
export interface CpuInfo {
model: string;
speed: number;
times: {
user: number;
nice: number;
sys: number;
idle: number;
irq: number;
}
}
export interface NetworkInterfaceInfo {
address: string;
netmask: string;
family: string;
mac: string;
internal: boolean;
}
export function tmpdir(): string;
export function homedir(): string;
export function endianness(): string;
export function hostname(): string;
export function type(): string;
export function platform(): string;
@@ -708,8 +730,8 @@ declare module "os" {
export function loadavg(): number[];
export function totalmem(): number;
export function freemem(): number;
export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[];
export function networkInterfaces(): any;
export function cpus(): CpuInfo[];
export function networkInterfaces(): {[index: string]: NetworkInterfaceInfo[]};
export var EOL: string;
}
@@ -1675,7 +1697,7 @@ declare module "crypto" {
declare module "stream" {
import * as events from "events";
export interface Stream extends events.EventEmitter {
export class Stream extends events.EventEmitter {
pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;
}
+1 -1
View File
@@ -115,7 +115,7 @@ declare module "progress"
*/
terminate():void;
}
module ProgressBar { }
export = ProgressBar;
}
Vendored
+1 -1
View File
@@ -20,7 +20,7 @@ declare module Q {
interface Deferred<T> {
promise: Promise<T>;
resolve(value: T): void;
resolve(value?: T): void;
reject(reason: any): void;
notify(value: any): void;
makeNodeResolver(): (reason: any, value: T) => void;
@@ -0,0 +1,7 @@
/// <reference path="./react-bootstrap-daterangepicker.d.tsx" />
/// <reference path="./../react/react.d.ts" />
import * as DateRangePicker from "react-bootstrap-daterangepicker";
import * as React from "react";
let pickerCoponent = <DateRangePicker onEvent={(ev: any, picker: any) => true} />;
@@ -0,0 +1,29 @@
// Type definitions for react-bootstrap-daterangepicker
// Project: https://github.com/skratchdot/react-bootstrap-daterangepicker
// Definitions by: Ian Ker-Seymer https://github.com/ianks
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../react/react.d.ts" />
/// <reference path="../bootstrap.datepicker/bootstrap.datepicker.d.ts" />
declare module ReactBootstrapDaterangepicker {
export interface EventHandler { (event?: any, picker?: any): any; }
export interface Props extends DatepickerOptions {
onShow?: EventHandler;
onHide?: EventHandler;
onShowCalendar?: EventHandler;
onHideCalendar?: EventHandler;
onApply?: EventHandler;
onCancel?: EventHandler;
onEvent?: EventHandler;
}
export class DateRangePicker extends __React.Component<Props, {}> {}
}
declare var DateRangePicker: typeof ReactBootstrapDaterangepicker.DateRangePicker;
declare module "react-bootstrap-daterangepicker" {
export = DateRangePicker;
}
@@ -0,0 +1 @@
--noImplicitAny --module commonjs --jsx react
+1
View File
@@ -1864,6 +1864,7 @@ declare namespace __React {
stroke?: string;
strokeDasharray?: string;
strokeLinecap?: string;
strokeMiterlimit?: string;
strokeOpacity?: number | string;
strokeWidth?: number | string;
textAnchor?: string;
+6 -3
View File
@@ -13,9 +13,12 @@ declare module 'request-promise' {
import http = require('http');
interface RequestPromise extends request.Request {
then(onFulfilled: Function, onRejected?: Function): Promise<any>;
catch(onRejected: Function): Promise<any>;
finally(onFinished: Function): Promise<any>;
then<TResult>(onfulfilled?: (value: any) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<TResult>;
then<TResult>(onfulfilled?: (value: any) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): Promise<TResult>;
catch(onrejected?: (reason: any) => any | PromiseLike<any>): Promise<any>;
catch(onrejected?: (reason: any) => void): Promise<any>;
finally<TResult>(handler: () => PromiseLike<TResult>): Promise<any>;
finally<TResult>(handler: () => TResult): Promise<any>;
promise(): Promise<any>;
}
+1 -1
View File
@@ -10,6 +10,6 @@
///<reference path="rx.backpressure-lite.d.ts" />
///<reference path="rx.coincidence-lite.d.ts" />
declare module "rx.lite" {
declare module "rx-lite" {
export = Rx;
}
+7 -2
View File
@@ -3949,6 +3949,11 @@ declare module "sequelize" {
* We don't have a definition for the QueryGenerator, because I doubt it is commonly in use separately.
*/
QueryGenerator: any;
/**
* Returns the current sequelize instance.
*/
sequelize: Sequelize;
/**
* Queries the schema (table list).
@@ -5706,12 +5711,12 @@ declare module "sequelize" {
/**
* Commit the transaction
*/
commit() : Transaction;
commit() : Promise<void>;
/**
* Rollback (abort) the transaction
*/
rollback() : Transaction;
rollback() : Promise<void>;
}
+9 -6
View File
@@ -1,12 +1,15 @@
// Type definitions for SharePoint 2010 and 2013
// Project: https://github.com/gandjustas/sptypescript
// Definitions by: Stanislav Vyshchepan <http://blog.gandjustas.ru>, Andrey Markeev <http://markeev.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../microsoft-ajax/microsoft.ajax.d.ts" />
// Type definitions for SharePoint 2010 and 2013
// Project: https://github.com/gandjustas/sptypescript
// Definitions by: Stanislav Vyshchepan <http://blog.gandjustas.ru>, Andrey Markeev <http://markeev.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../microsoft-ajax/microsoft.ajax.d.ts" />
declare var _spBodyOnLoadFunctions: Function[];
declare var _spBodyOnLoadFunctionNames: string[];
declare var _spBodyOnLoadCalled: boolean;
declare function ExecuteOrDelayUntilBodyLoaded(initFunc: () => void): void;
declare function ExecuteOrDelayUntilScriptLoaded(func: () => void, depScriptFileName: string): boolean;
declare function ExecuteOrDelayUntilEventNotified(func: Function, eventName: string): boolean;
declare var Strings:any;
declare module SP {
+20
View File
@@ -0,0 +1,20 @@
/// <reference path="../shuffle-array/shuffle-array.d.ts" />
import shuffle = require('shuffle-array');
// shuffle()
var a = [1, 2, 3, 4, 5];
var result: number[];
result = shuffle(a);
result = shuffle(a, {});
result = shuffle(a, {copy: true});
result = shuffle(a, {rng: () => 0});
result = shuffle(a, {copy: true, rng: () => 0});
var b = ['aaa', 'bbb', 'ccc']
var result2: string[];
result2 = shuffle.pick(b);
result2 = shuffle.pick(b, {});
result2 = shuffle.pick(b, {picks: 3});
result2 = shuffle.pick(b, {rng: () => 0});
result2 = shuffle.pick(b, {picks: 3, rng: () => 0});
+42
View File
@@ -0,0 +1,42 @@
// Type definitions for shuffle-array
// Project: https://github.com/pazguille/shuffle-array
// Definitions by: rhysd <https://rhysd.github.io>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "shuffle-array" {
/**
* copy - Sets if should return a shuffled copy of the given array. By default it's a falsy value.
* rng - Specifies a custom random number generator.
*/
interface ShuffleOption {
copy?: boolean;
rng?: () => number;
}
/**
* picks - Specifies how many random elements you want to pick. By default it picks 1.
* rng - Specifies a custom random number generator.
*/
interface PickOption {
picks?: number;
rng?: () => number;
}
interface ShuffleArray {
/**
* Randomizes the order of the elements in a given array.
*
* arr - The given array.
* options - Optional configuration options.
*/
<T>(arr: T[], options?: ShuffleOption): T[];
/**
* Pick one or more random elements from the given array.
*
* arr - The given array.
* options - Optional configuration options.
*/
pick<T>(arr: T[], options?: Object): T[];
}
var shuffle: ShuffleArray;
export = shuffle;
}
File diff suppressed because it is too large Load Diff
+194
View File
@@ -0,0 +1,194 @@
// Type definitions for simple-mock
// Project: https://github.com/jupiter/simple-mock
// Definitions by: Leon Yu <https://github.com/leonyu>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare namespace Simple {
type Fn<T> = {
(...args: any[]): T
}
export interface Static {
/**
* Restores all current mocks.
*/
restore(): void;
/**
* Wraps fn in a spy and sets this on the obj, restorable with all mocks.
*/
mock<T>(obj: any, key: string, fn: Fn<T>): Stub<T>;
/**
* Sets the value on this object. E.g. mock(config, 'title', 'test') is the same as config.title = 'test', but restorable with all mocks.
*/
mock<T>(obj: any, key: string, mockValue: T): T;
/**
* If obj has already has this function, it is wrapped in a spy. The resulting spy can be turned into a stub by further configuration. Restores with all mocks.
*/
mock(obj: any, key: string): Stub<any>;
mock<T>(obj: any, key: string): Stub<T>;
/**
* Wraps fn in a spy.
*/
spy<T>(fn: Fn<T>): Spy<T>;
/**
* Wraps fn in a spy.
*/
mock<T>(fn: Fn<T>): Spy<T>;
/**
* Returns a stub function that is also a spy.
*/
stub(): Stub<any>;
stub<T>(): Stub<T>;
/**
* Returns a stub function that is also a spy.
*/
mock(): Stub<any>;
mock<T>(): Stub<T>;
Promise?: PromiseConstructorLike;
}
interface Calls<T> {
/**
* an array of arguments received on the call
*/
args: any[];
/**
* first argument
*/
arg: any;
/**
* the context (this) of the call
*/
context: any;
/**
* the value returned by the wrapped function
*/
returned: T;
/**
* the error thrown by the wrapped function
*/
threw: Error;
/**
* autoincrementing number, can be compared to evaluate call order
*/
k: number;
}
export interface Spy<T>{
(...args: any[]): T;
called: boolean;
/**
* Number of times the function was called.
*/
callCount: number;
calls: Calls<T>[];
firstCall: Calls<T>;
/**
* The last call object. (This is often also the first and only call.)
*/
lastCall: Calls<T>;
/**
* Resets all counts and properties to the original state.
*/
reset(): void;
}
interface Action<T> {
/**
* arguments to call back with
*/
cbArgs: ArrayLike<any>;
returnValue: T;
throwError: Error;
}
export interface Stub<T> extends Spy<T> {
/**
* Configures this stub to call this function, returning its return value.
* Subsequent calls of this on the same stub (chainable) will queue up different behaviours for each subsequent call of the stub.
*/
callFn<R>(fn: Fn<R>): Stub<R>;
/**
* Configures this stub to call the original, unstubbed function, returning its return value.
* Subsequent calls of this on the same stub (chainable) will queue up different behaviours for each subsequent call of the stub.
*/
callOriginal(): Stub<T>;
/**
* Configures this stub to return with this value.
* Subsequent calls of this on the same stub (chainable) will queue up different behaviours for each subsequent call of the stub.
*/
returnWith<R>(val: R): Stub<R>;
/**
* Configures this stub to throw this error.
* Subsequent calls of this on the same stub (chainable) will queue up different behaviours for each subsequent call of the stub.
*/
throwWith(err: Error): Stub<T>;
/**
* Configures this stub to call back with the arguments passed. It will use either the last argument as callback, or the argument at cbArgumentIndex.
* Subsequent calls of this on the same stub (chainable) will queue up different behaviours for each subsequent call of the stub.
*/
callback(...args: any[]): Stub<T>;
/**
* Configures this stub to call back with the arguments passed. It will use either the last argument as callback, or the argument at cbArgumentIndex.
* Subsequent calls of this on the same stub (chainable) will queue up different behaviours for each subsequent call of the stub.
*/
callbackWith(...args: any[]): Stub<T>;
/**
* Configures this stub to call back with the arguments passed. It will use either the last argument as callback, or the argument at cbArgumentIndex.
* Subsequent calls of this on the same stub (chainable) will queue up different behaviours for each subsequent call of the stub.
*/
callbackAtIndex(cbArgumentIndex: number, ...args: any[]): Stub<T>;
/**
* Configures this stub to call back with the arguments passed. It will use either the last argument as callback, or the argument at cbArgumentIndex.
* Subsequent calls of this on the same stub (chainable) will queue up different behaviours for each subsequent call of the stub.
*/
callbackArgWith(cbArgumentIndex: number, ...args: any[]): Stub<T>;
/**
* Configures the last configured function or callback to be called in this context, i.e. this will be obj.
*/
inThisContext(obj: any): Stub<T>;
/**
* Configures the stub to return a Promise (where available] resolving to this value. Same as stub.returnWith(Promise.resolve(val)).
* You can use a custom Promise-conforming library, i.e. simple.Promise = require('bluebird') or simple.Promise = $q.
*/
resolveWith<V>(val: V): Stub<PromiseLike<V>>;
/**
* Configures the stub to return a Promise (where available) rejecting with this error. Same as stub.returnWith(Promise.reject(val)).
* You can use a custom Promise-conforming library, i.e. simple.Promise = require('bluebird') or simple.Promise = $q.
*/
rejectWith<V>(val: V): Stub<PromiseLike<V>>;
/**
* An array of behaviours, each having one of these properties:
*/
actions: Action<T>[];
/**
* setting whether the queue of actions for this stub should repeat.
* @default true
*/
loop: boolean;
}
}
declare module "simple-mock" {
var simple: Simple.Static;
export = simple;
}
+1 -1
View File
@@ -79,5 +79,5 @@ interface StateMachine {
declare var StateMachine: StateMachineStatic;
declare module "state-machine" {
export = StateMachineStatic;
export = StateMachine;
}
@@ -0,0 +1,11 @@
// Type definitions for strip-json-comments
// Project: https://github.com/sindresorhus/strip-json-comments
// Definitions by: Dylan R. E. Moonfire <https://github.com/dmoonfire/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="strip-json-comments.d.ts" />
import stripJsonComments = require("strip-json-comments");
const json = '{/*rainbows*/"unicorn":"cake"}';
JSON.parse(stripJsonComments(json));
//=> {unicorn: 'cake'}
+13
View File
@@ -0,0 +1,13 @@
// Type definitions for strip-json-comments
// Project: https://github.com/sindresorhus/strip-json-comments
// Definitions by: Dylan R. E. Moonfire <https://github.com/dmoonfire/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "strip-json-comments" {
interface StripJsonOptions {
whitespace?: boolean;
}
function stripJsonComments(input: string, opts?: StripJsonOptions): string;
export = stripJsonComments;
}
+112 -55
View File
@@ -2,23 +2,18 @@
/// <reference path="../node/node.d.ts" />
import tape = require('tape');
import tape = require("tape");
var x: any;
var value: any;
var err: any;
var a: any;
var b: any;
var err: any;
var num: number;
var name: string;
var msg: string;
var rs: NodeJS.ReadableStream;
var cb: tape.TestCase;
var opts: tape.TestOptions;
var t: tape.Test;
tape(cb);
tape(name, cb);
tape(opts, cb);
tape(name, opts, cb);
tape(name, (test: tape.Test) => {
t = test;
});
@@ -26,29 +21,51 @@ tape(name, (test: tape.Test) => {
tape.skip(name, cb);
tape.only(name, cb);
rs = tape.createStream();
rs = tape.createStream(x);
var tx = tape.createHarness();
tx(name, cb);
tape.skip(name, cb);
tape.only(name, cb);
var sopts: tape.StreamOptions;
var rs: NodeJS.ReadableStream;
rs = tape.createStream();
rs = tape.createStream(sopts);
var htest: typeof tape;
htest = tape.createHarness();
tape(name, (test: tape.Test) => {
var num: number;
var ms: number;
var value: any;
var actual: any;
var expected: any;
var err: any;
var fn = function() {};
var msg: string;
var exceptionExpected: RegExp | (() => void);
test.plan(num);
test.end();
test.end(err);
test.fail(msg);
test.pass(msg);
test.timeoutAfter(ms);
test.skip(msg);
test.ok(value);
test.ok(value, msg);
test.true(value);
test.true(value, msg);
test.assert(value);
test.assert(value, msg);
test.notOk(value);
test.notOk(value, msg);
test.false(value);
test.false(value, msg);
test.notok(value);
test.notok(value, msg);
test.error(err, msg);
@@ -56,51 +73,91 @@ tape(name, (test: tape.Test) => {
test.ifErr(err, msg);
test.iferror(err, msg);
test.equal(a, b, msg);
test.equals(a, b, msg);
test.isEqual(a, b, msg);
test.is(a, b, msg);
test.strictEqual(a, b, msg);
test.strictEquals(a, b, msg);
test.equal(actual, expected);
test.equal(actual, expected, msg);
test.equals(actual, expected);
test.equals(actual, expected, msg);
test.isEqual(actual, expected);
test.isEqual(actual, expected, msg);
test.is(actual, expected);
test.is(actual, expected, msg);
test.strictEqual(actual, expected);
test.strictEqual(actual, expected, msg);
test.strictEquals(actual, expected);
test.strictEquals(actual, expected, msg);
test.notEqual(a, b, msg);
test.notEquals(a, b, msg);
test.notStrictEqual(a, b, msg);
test.notStrictEquals(a, b, msg);
test.isNotEqual(a, b, msg);
test.isNot(a, b, msg);
test.not(a, b, msg);
test.doesNotEqual(a, b, msg);
test.notEqual(a, b, msg);
test.isInequal(a, b, msg);
test.notEqual(actual, expected);
test.notEqual(actual, expected, msg);
test.notEquals(actual, expected);
test.notEquals(actual, expected, msg);
test.notStrictEqual(actual, expected);
test.notStrictEqual(actual, expected, msg);
test.notStrictEquals(actual, expected);
test.notStrictEquals(actual, expected, msg);
test.isNotEqual(actual, expected);
test.isNotEqual(actual, expected, msg);
test.isNot(actual, expected);
test.isNot(actual, expected, msg);
test.not(actual, expected);
test.not(actual, expected, msg);
test.doesNotEqual(actual, expected);
test.doesNotEqual(actual, expected, msg);
test.isInequal(actual, expected);
test.isInequal(actual, expected, msg);
test.deepEqual(a, b, msg);
test.deepEquals(a, b, msg);
test.isEquivalent(a, b, msg);
test.same(a, b, msg);
test.deepEqual(actual, expected);
test.deepEqual(actual, expected, msg);
test.deepEquals(actual, expected);
test.deepEquals(actual, expected, msg);
test.isEquivalent(actual, expected);
test.isEquivalent(actual, expected, msg);
test.same(actual, expected);
test.same(actual, expected, msg);
test.notDeepEqual(a, b, msg);
test.notEquivalent(a, b, msg);
test.notDeeply(a, b, msg);
test.notSame(a, b, msg);
test.isNotDeepEqual(a, b, msg);
test.isNotDeeply(a, b, msg);
test.isNotEquivalent(a, b, msg);
test.isInequivalent(a, b, msg);
test.notDeepEqual(actual, expected);
test.notDeepEqual(actual, expected, msg);
test.notEquivalent(actual, expected);
test.notEquivalent(actual, expected, msg);
test.notDeeply(actual, expected);
test.notDeeply(actual, expected, msg);
test.notSame(actual, expected);
test.notSame(actual, expected, msg);
test.isNotDeepEqual(actual, expected);
test.isNotDeepEqual(actual, expected, msg);
test.isNotDeeply(actual, expected);
test.isNotDeeply(actual, expected, msg);
test.isNotEquivalent(actual, expected);
test.isNotEquivalent(actual, expected, msg);
test.isInequivalent(actual, expected);
test.isInequivalent(actual, expected, msg);
test.deepLooseEqual(a, b, msg);
test.looseEqual(a, b, msg);
test.looseEquals(a, b, msg);
test.deepLooseEqual(actual, expected);
test.deepLooseEqual(actual, expected, msg);
test.looseEqual(actual, expected);
test.looseEqual(actual, expected, msg);
test.looseEquals(actual, expected);
test.looseEquals(actual, expected, msg);
test.notDeepLooseEqual(a, b, msg);
test.notLooseEqual(a, b, msg);
test.notLooseEquals(a, b, msg);
test.notDeepLooseEqual(actual, expected);
test.notDeepLooseEqual(actual, expected, msg);
test.notLooseEqual(actual, expected);
test.notLooseEqual(actual, expected, msg);
test.notLooseEquals(actual, expected);
test.notLooseEquals(actual, expected, msg);
test.throws(() => {
test.throws(fn);
test.throws(fn, msg);
test.throws(fn, exceptionExpected);
test.throws(fn, exceptionExpected, msg);
}, value, msg);
test.doesNotThrow(fn);
test.doesNotThrow(fn, msg);
test.doesNotThrow(fn, exceptionExpected);
test.doesNotThrow(fn, exceptionExpected, msg);
test.doesNotThrow(() => {
test.test(name, (st) => {
t = st;
});
}, value, msg);
test.comment(msg);
});
+52 -11
View File
@@ -1,6 +1,6 @@
// Type definitions for tape v2.12.3
// Type definitions for tape v4.2.2
// Project: https://github.com/substack/tape
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Haoqun Jiang <https://github.com/sodatea>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
@@ -9,22 +9,43 @@ declare module 'tape' {
export = tape;
/**
* Create a new test with an optional name string. cb(t) fires with the new test object t once all preceeding tests have finished. Tests execute serially.
* Create a new test with an optional name string and optional opts object.
* cb(t) fires with the new test object t once all preceeding tests have finished.
* Tests execute serially.
*/
function tape(name: string, cb: tape.TestCase): void;
function tape(name: string, opts: tape.TestOptions, cb: tape.TestCase): void;
function tape(cb: tape.TestCase): void;
function tape(opts: tape.TestOptions, cb: tape.TestCase): void;
module tape {
interface TestCase {
(test: Test): void;
}
/**
* Available opts options for the tape function.
*/
interface TestOptions {
skip?: boolean; // See tape.skip.
timeout?: number; // Set a timeout for the test, after which it will fail. See tape.timeoutAfter.
}
/**
* Options for the createStream function.
*/
interface StreamOptions {
objectMode?: boolean;
}
/**
* Generate a new test that will be skipped over.
*/
export function skip(name: string, cb: tape.TestCase): void;
/**
* Like test(name, cb) except if you use .only this is the only test case that will run for the entire process, all other test cases using tape will be ignored
* Like test(name, cb) except if you use .only this is the only test case that will run for the entire process, all other test cases using tape will be ignored.
*/
export function only(name: string, cb: tape.TestCase): void;
@@ -34,24 +55,29 @@ declare module 'tape' {
export function createHarness(): typeof tape;
/**
* Create a stream of output, bypassing the default output stream that writes messages to console.log().
* By default stream will be a text stream of TAP output, but you can get an object stream instead by setting opts.objectMode to true.
*/
export function createStream(opts?: any): NodeJS.ReadableStream;
export function createStream(opts?: tape.StreamOptions): NodeJS.ReadableStream;
interface Test {
/**
* Create a subtest with a new test handle st from cb(st) inside the current test cb(st) will only fire when t finishes. Additional tests queued up after t will not be run until all subtests finish.
* Create a subtest with a new test handle st from cb(st) inside the current test.
* cb(st) will only fire when t finishes.
* Additional tests queued up after t will not be run until all subtests finish.
*/
test(name: string, cb: tape.TestCase): void;
/**
* Declare that n assertions should be run. end() will be called automatically after the nth assertion. If there are any more assertions after the nth, or after end() is called, they will generate errors.
* Declare that n assertions should be run. end() will be called automatically after the nth assertion.
* If there are any more assertions after the nth, or after end() is called, they will generate errors.
*/
plan(n: number): void;
/**
* Declare the end of a test explicitly.
* If err is passed in t.end will assert that it is falsey.
*/
end(): void;
end(err?: any): void;
/**
* Generate a failing assertion with a message msg.
@@ -63,6 +89,11 @@ declare module 'tape' {
*/
pass(msg?: string): void;
/**
* Automatically timeout the test after X ms.
*/
timeoutAfter(ms: number): void;
/**
* Generate an assertion that will be skipped over.
*/
@@ -83,7 +114,8 @@ declare module 'tape' {
notok(value: any, msg?: string): void;
/**
* Assert that err is falsy. If err is non-falsy, use its err.message as the description message.
* Assert that err is falsy.
* If err is non-falsy, use its err.message as the description message.
*/
error(err: any, msg?: string): void;
ifError(err: any, msg?: string): void;
@@ -149,13 +181,22 @@ declare module 'tape' {
/**
* Assert that the function call fn() throws an exception.
* expected, if present, must be a RegExp or Function, which is used to test the exception object.
*/
throws(fn: () => void, expected: any, msg?: string): void;
throws(fn: () => void, msg?: string): void;
throws(fn: () => void, exceptionExpected: RegExp | (() => void), msg?: string): void;
/**
* Assert that the function call fn() does not throw an exception.
*/
doesNotThrow(fn: () => void, expected: any, msg?: string): void;
doesNotThrow(fn: () => void, msg?: string): void;
doesNotThrow(fn: () => void, exceptionExpected: RegExp | (() => void), msg?: string): void;
/**
* Print a message without breaking the tap output.
* (Useful when using e.g. tap-colorize where output is buffered & console.log will print in incorrect order vis-a-vis tap output.)
*/
comment(msg: string): void;
}
}
}
+522
View File
@@ -0,0 +1,522 @@
/// <reference path="turf.d.ts"/>
///////////////////////////////////////////
// Tests data initialisation
///////////////////////////////////////////
var point1 = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-75.343, 39.984]
}
};
var point2 = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-75.534, 39.123]
}
};
var line = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [
[-77.031669, 38.878605],
[-77.029609, 38.881946],
[-77.020339, 38.884084],
[-77.025661, 38.885821],
[-77.021884, 38.889563],
[-77.019824, 38.892368]
]
}
};
var polygons = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [[
[-67.031021, 10.458102],
[-67.031021, 10.53372],
[-66.929397, 10.53372],
[-66.929397, 10.458102],
[-67.031021, 10.458102]
]]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [[
[-66.919784, 10.397325],
[-66.919784, 10.513467],
[-66.805114, 10.513467],
[-66.805114, 10.397325],
[-66.919784, 10.397325]
]]
}
}
]
};
var polygon1 = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [[
[105.818939,21.004714],
[105.818939,21.061754],
[105.890007,21.061754],
[105.890007,21.004714],
[105.818939,21.004714]
]]
}
};
var polygon2 = {
"type": "Feature",
"properties": {
"fill": "#00f"
},
"geometry": {
"type": "Polygon",
"coordinates": [[
[-122.520217, 45.535693],
[-122.64038, 45.553967],
[-122.720031, 45.526554],
[-122.669906, 45.507309],
[-122.723464, 45.446643],
[-122.532577, 45.408574],
[-122.487258, 45.477466],
[-122.520217, 45.535693]
]]
}
}
var features = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-97.522259, 35.4691]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-97.502754, 35.463455]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-97.508269, 35.463245]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-97.516809, 35.465779]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-97.515372, 35.467072]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-97.509363, 35.463053]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-97.511123, 35.466601]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-97.518547, 35.469327]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-97.519706, 35.469659]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-97.517839, 35.466998]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-97.508678, 35.464942]
}
}, {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-97.514914, 35.463453]
}
}
]
};
var triangle = {
"type": "Feature",
"properties": {
"a": 11,
"b": 122,
"c": 44
},
"geometry": {
"type": "Polygon",
"coordinates": [[
[-75.1221, 39.57],
[-75.58, 39.18],
[-75.97, 39.86],
[-75.1221, 39.57]
]]
}
};
var aggregations = [
{
aggregation: 'sum',
inField: 'population',
outField: 'pop_sum'
},
{
aggregation: 'average',
inField: 'population',
outField: 'pop_avg'
},
{
aggregation: 'median',
inField: 'population',
outField: 'pop_median'
},
{
aggregation: 'min',
inField: 'population',
outField: 'pop_min'
},
{
aggregation: 'max',
inField: 'population',
outField: 'pop_max'
},
{
aggregation: 'deviation',
inField: 'population',
outField: 'pop_deviation'
},
{
aggregation: 'variance',
inField: 'population',
outField: 'pop_variance'
},
{
aggregation: 'count',
inField: '',
outField: 'point_count'
}
];
///////////////////////////////////////////
// Tests Aggregation
///////////////////////////////////////////
// -- Test aggregate --
var aggregated = turf.aggregate(polygons, points, aggregations);
// -- Test average --
var averaged = turf.average(polygons, points, 'population', 'pop_avg');
// -- Test count --
var counted = turf.count(polygons, points, 'pt_count');
// -- Test deviation --
var deviated = turf.deviation(polygons, points, 'population', 'pop_deviation');
// -- Test max --
var aggregated = turf.max(polygons, points, 'population', 'max');
// -- Test median --
var medians = turf.median(polygons, points, 'population', 'median');
// -- Test min --
var minimums = turf.min(polygons, points, 'population', 'min');
// -- Test sum --
var summed = turf.sum(polygons, points, 'population', 'sum');
// -- Test variance --
var varianced = turf.variance(polygons, points, 'population', 'variance');
///////////////////////////////////////////
// Tests Measurement
///////////////////////////////////////////
// -- Test along --
var along = turf.along(line, 1, 'miles');
// -- Test area --
var area = turf.area(polygons);
// -- Test bboxPolygon --
var bbox = [0, 0, 10, 10];
var poly = turf.bboxPolygon(bbox);
// -- Test bearing --
var bearing = turf.bearing(point1, point2);
// -- Test center
var centerPt = turf.center(features);
// -- Test centroid --
var centroidPt = turf.centroid(polygon1);
// -- Test destination --
var distance = 50;
var bearing = 90;
var units = 'miles';
var destination = turf.destination(point1, distance, bearing, units);
// -- Test distance --
var units = "miles";
var distance = turf.distance(point1, point2, units);
// -- Test envelope --
var enveloped = turf.envelope(polygons);
// -- Test extent --
var bbox = turf.extent(polygons);
// -- Test lineDistance
var length = turf.lineDistance(line, 'miles');
// -- Test midpoint --
var midpointed = turf.midpoint(point1, point2);
// -- Test pointOnSurface --
var pointOnPolygon = turf.pointOnSurface(polygon1);
// -- Test size --
var resized = turf.size(bbox, 2);
// -- Test square --
var squared = turf.square(bbox);
///////////////////////////////////////////
// Tests Transformation
///////////////////////////////////////////
// -- Test bezier --
var curved = turf.bezier(line);
// -- Test buffer --
var buffered = turf.buffer(point1, 500, units);
// -- Test concave --
var hull = turf.concave(features, 1, 'miles');
// -- Test convex --
var hull = turf.convex(features);
// -- Test difference --
var differenced = turf.difference(polygon1, polygon2);
// -- Test intersect --
var intersection = turf.intersect(polygon1, polygon2);
// -- Test merge --
var merged = turf.merge(polygons);
// -- Test simplify --
var tolerance = 0.01;
var simplified = turf.simplify(polygon1, tolerance, false);
// -- Test union --
var union = turf.union(polygon1, polygon2);
///////////////////////////////////////////
// Tests Misc
///////////////////////////////////////////
// -- Test combine --
var combined = turf.combine(features);
// -- Test explode --
var points = turf.explode(polygon1);
// -- Test flip --
var flipedPoint = turf.flip(point1);
// -- Test kinks --
var kinks = turf.kinks(polygon1);
// -- Test lineSlice --
var sliced = turf.lineSlice(point1, point2, line);
// -- Test pointOnLine --
var snapped = turf.pointOnLine(line, point1);
///////////////////////////////////////////
// Tests Helper
///////////////////////////////////////////
// -- Test featurecollection --
var fc = turf.featurecollection([point1, point2]);
// -- Test linestring --
var linestring1 = turf.linestring([
[-21.964416, 64.148203],
[-21.956176, 64.141316],
[-21.93901, 64.135924],
[-21.927337, 64.136673]
]);
var linestring2 = turf.linestring([
[-21.929054, 64.127985],
[-21.912918, 64.134726],
[-21.916007, 64.141016],
[-21.930084, 64.14446]
], {name: 'line 1', distance: 145});
// -- Test point --
var pt1 = turf.point([-75.343, 39.984]);
var pt2 = turf.point([-75.343, 39.984], {name: 'point 1', distance: 145});
// -- Test polygon --
var polygon = turf.polygon([[
[-2.275543, 53.464547],
[-2.275543, 53.489271],
[-2.215118, 53.489271],
[-2.215118, 53.464547],
[-2.275543, 53.464547]
]], { name: 'poly1', population: 400});
///////////////////////////////////////////
// Tests Data
///////////////////////////////////////////
// -- Test filter --
var key = "species";
var value = "oak";
var filtered = turf.filter(features, key, value);
// -- Test random --
var points = turf.random('points', 100, {
bbox: [-70, 40, -60, 60]
});
var points = turf.random('points', 100, {
bbox: [-70, 40, -60, 60],
num_vertices: 2,
max_radial_length: 10
});
// -- Test remove --
var filtered = turf.remove(points, 'marker-color', '#00f');
// -- Test sample --
var points = turf.random('points', 1000);
var sample = turf.sample(points, 10);
///////////////////////////////////////////
// Tests Interpolation
///////////////////////////////////////////
// -- Test hexGrid --
var cellWidth = 50;
var hexgrid = turf.hexGrid(bbox, cellWidth, units);
// -- Test isolines --
var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var isolined = turf.isolines(points, 'z', 15, breaks);
// -- Test planepoint --
var zValue = turf.planepoint(point1, triangle);
// -- Test pointGrid --
var extent = [-70.823364, -33.553984, -70.473175, -33.302986];
var cellWidth = 3;
var grid = turf.pointGrid(extent, cellWidth, units);
// -- Test squareGrid --
var squareGrid = turf.squareGrid(extent, cellWidth, units);
// -- Test tin --
var tin = turf.tin(points, 'z');
// -- Test triangleGrid --
var triangleGrid = turf.triangleGrid(extent, cellWidth, units);
///////////////////////////////////////////
// Tests Joins
///////////////////////////////////////////
// -- Test inside --
var isInside1 = turf.inside(point1, polygon);
// -- Test tag --
var tagged = turf.tag(points, triangleGrid, 'fill', 'marker-color');
// -- Test within --
var ptsWithin = turf.within(points, polygons);
///////////////////////////////////////////
// Tests Classification
///////////////////////////////////////////
// -- Test jenks --
var breaks = turf.jenks(points, 'population', 3);
// -- Test nearest --
var nearest = turf.nearest(point1, points);
// -- Test quantile --
var breaks = turf.quantile(points, 'population', [25, 50, 75, 99]);
// -- Test reclass --
var translations = [
[0, 200, "small"],
[200, 400, "medium"],
[400, 600, "large"]
];
var reclassed = turf.reclass(points, 'population', 'size', translations);
+576
View File
@@ -0,0 +1,576 @@
// Type definitions for Turf 2.0
// Project: http://turfjs.org/
// Definitions by: Guillaume Croteau <https://github.com/gcroteau>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../geojson/geojson.d.ts" />
declare module turf {
//////////////////////////////////////////////////////
// Aggregation
//////////////////////////////////////////////////////
/**
* Calculates a series of aggregations for a set of points within a set of polygons.
* Sum, average, count, min, max, and deviation are supported.
* @param polygons Polygons with values on which to aggregate
* @param points Points to be aggregated
* @param aggregations An array of aggregation objects
* @returns Polygons with properties listed based on outField values in aggregations
*/
function aggregate(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, aggregations: Array<{aggregation: string, inField: string, outField: string}>): GeoJSON.FeatureCollection;
/**
* Calculates the average value of a field for a set of points within a set of polygons.
* @param polygons Polygons with values on which to average
* @param points Points from which to calculate the average
* @param field The field in the points features from which to pull values to average
* @param outField The field in polygons to put results of the averages
* @returns Polygons with the value of outField set to the calculated averages
*/
function average(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, field: string, outField: string): GeoJSON.FeatureCollection;
/**
* Takes a set of points and a set of polygons and calculates the number of points that fall within the set of polygons.
* @param polygons Input polygons
* @param points Input points
* @param countField A field to append to the attributes of the Polygon features representing Point counts
* @returns Polygons with countField appended
*/
function count(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, countField: string): GeoJSON.FeatureCollection;
/**
* Calculates the standard deviation value of a field for a set of points within a set of polygons.
* @param polygons Input polygons
* @param points Input points
* @param inField The field in points from which to aggregate
* @param outField The field to append to polygons representing deviation
* @returns Polygons with appended field representing deviation
*/
function deviation(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection;
/**
* Calculates the maximum value of a field for a set of points within a set of polygons.
* @param polygons Input polygons
* @param points Input points
* @param inField The field in input data to analyze
* @param outField The field in which to store results
* @returns Polygons with properties listed as outField values
*/
function max(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection;
/**
* Calculates the median value of a field for a set of points within a set of polygons.
* @param polygons Input polygons
* @param points Input points
* @param inField The field in input data to analyze
* @param outField The field in which to store results
* @returns Polygons with properties listed as outField values
*/
function median(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection;
/**
* Calculates the minimum value of a field for a set of points within a set of polygons.
* @param polygons Input polygons
* @param points Input points
* @param inField The field in input data to analyze
* @param outField The field in which to store results
* @returns Polygons with properties listed as outField values
*/
function min(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection;
/**
* Calculates the sum of a field for a set of points within a set of polygons.
* @param polygons Input polygons
* @param points Input points
* @param inField The field in input data to analyze
* @param outField The field in which to store results
* @returns Polygons with properties listed as outField
*/
function sum(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection;
/**
* Calculates the variance value of a field for a set of points within a set of polygons.
* @param polygons Input polygons
* @param points Input points
* @param inField The field in input data to analyze
* @param outField The field in which to store results
* @returns Polygons with properties listed as outField
*/
function variance(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection;
//////////////////////////////////////////////////////
// Measurement
//////////////////////////////////////////////////////
/**
* Takes a line and returns a point at a specified distance along the line.
* @param line Input line
* @param distance Distance along the line
* @param [units=miles] 'miles', 'kilometers', 'radians' or 'degrees'
* @returns Point along the line
*/
function along(line: GeoJSON.Feature, distance: number, units?: string): GeoJSON.Feature;
/**
* Takes one or more features and returns their area in square meters.
* @param input Input features
* @returns Area in square meters
*/
function area(input: GeoJSON.Feature | GeoJSON.FeatureCollection): number;
/**
* Takes a bbox and returns an equivalent polygon.
* @param bbox An Array of bounding box coordinates in the form: [xLow, yLow, xHigh, yHigh]
* @returns A Polygon representation of the bounding box
*/
function bboxPolygon(bbox: Array<number>): GeoJSON.Feature;
/**
* Takes two points and finds the geographic bearing between them.
* @param start Starting Point
* @param end Ending point
* @returns Bearing in decimal degrees
*/
function bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number;
/**
* Takes a FeatureCollection and returns the absolute center point of all features.
* @param features Input features
* @returns A Point feature at the absolute center point of all input features
*/
function center(features: GeoJSON.FeatureCollection): GeoJSON.Feature;
/**
* Takes one or more features and calculates the centroid using the arithmetic mean of all vertices.
* This lessens the effect of small islands and artifacts when calculating the centroid of a set of polygons.
* @param features Input features
* @returns The centroid of the input features
*/
function centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature;
/**
* Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers; and bearing in degrees.
* This uses the Haversine formula to account for global curvature.
* @param start Starting point
* @param distance Distance from the starting point
* @param bearing Ranging from -180 and 180
* @param units 'miles', 'kilometers', 'radians', or 'degrees'
* @returns Destination point
*/
function destination(start: GeoJSON.Feature, distance: number, bearing: number, units: string): GeoJSON.Feature;
/**
* Calculates the distance between two points in degress, radians, miles, or kilometers.
* This uses the Haversine formula to account for global curvature.
* @param from Origin point
* @param to Destination point
* @param [units=kilometers] 'miles', 'kilometers', 'radians', or 'degrees'
* @returns Distance between the two points
*/
function distance(from: GeoJSON.Feature, to: GeoJSON.Feature, units?: string): number;
/**
* Takes any number of features and returns a rectangular Polygon that encompasses all vertices.
* @param fc Input features
* @returns A rectangular Polygon feature that encompasses all vertices
*/
function envelope(fc: GeoJSON.FeatureCollection): GeoJSON.Feature;
/**
* Takes a set of features, calculates the extent of all input features, and returns a bounding box.
* @param input Input features
* @returns The bounding box of input given as an array in WSEN order (west, south, east, north)
*/
function extent(input: GeoJSON.Feature | GeoJSON.FeatureCollection): Array<number>;
/**
* Takes a line and measures its length in the specified units.
* @param line Line to measure
* @param units 'miles', 'kilometers', 'radians', or 'degrees'
* @returns Length of the input line
*/
function lineDistance(line: GeoJSON.Feature, units: string): number;
/**
* Takes two points and returns a point midway between them.
* @param pt1 First point
* @param pt2 Second point
* @returns A point midway between pt1 and pt2
*/
function midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature;
/**
* Takes a feature and returns a Point guaranteed to be on the surface of the feature. Given a Polygon, the point will be in the area of the polygon.
* Given a LineString, the point will be along the string. Given a Point, the point will the same as the input.
* @param input Any feature or set of features
* @returns A point on the surface of input
*/
function pointOnSurface(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature;
/**
* Takes a bounding box and returns a new bounding box with a size expanded or contracted by a factor of X.
* @param bbox A bounding box
* @param factor The ratio of the new bbox to the input bbox
* @returns The resized bbox
*/
function size(bbox: Array<number>, factor: number): Array<number>;
/**
* Takes a bounding box and calculates the minimum square bounding box that would contain the input.
* @param bbox A bounding box
* @returns A square surrounding bbox
*/
function square(bbox: Array<number>): Array<number>;
//////////////////////////////////////////////////////
// Transformation
//////////////////////////////////////////////////////
/**
* Takes a line and returns a curved version by applying a Bezier spline algorithm.
* The bezier spline implementation is by Leszek Rybicki.
* @param line Input LineString
* @param [resolution=10000] Time in milliseconds between points
* @param [sharpness=0.85] A measure of how curvy the path should be between splines
* @returns Curved line
*/
function bezier(line: GeoJSON.Feature, resolution?: number, sharpness?: number): GeoJSON.Feature;
/**
* Calculates a buffer for input features for a given radius. Units supported are miles, kilometers, and degrees.
* @param feature Input to be buffered
* @param distance Distance to draw the buffer
* @param units 'miles', 'kilometers', 'radians', or 'degrees'
* @returns Buffered features
*/
function buffer(feature: GeoJSON.Feature | GeoJSON.FeatureCollection, distance: number, units: string): GeoJSON.Feature | GeoJSON.FeatureCollection;
/**
* Takes a set of points and returns a concave hull polygon. Internally, this implements a Monotone chain algorithm.
* @param points Input points
* @param maxEdge The size of an edge necessary for part of the hull to become concave (in miles)
* @param units Used for maxEdge distance (miles or kilometers)
* @returns A concave hull
*/
function concave(points: GeoJSON.FeatureCollection, maxEdge: number, units: string): GeoJSON.Feature;
/**
* Takes a set of points and returns a convex hull polygon. Internally this uses the convex-hull module that implements a monotone chain hull.
* @param input Input points
* @returns A convex hull
*/
function convex(input: GeoJSON.FeatureCollection): GeoJSON.Feature;
/**
* Finds the difference between two polygons by clipping the second polygon from the first.
* @param poly1 Input Polygon feaure
* @param poly2 Polygon feature to difference from poly1
* @returns A Polygon feature showing the area of poly1 excluding the area of poly2
*/
function difference(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature;
/**
* Takes two polygons and finds their intersection.
* If they share a border, returns the border; if they don't intersect, returns undefined.
* @param poly1 The first polygon
* @param poly2 The second polygon
* @returns If poly1 and poly2 overlap, returns a Polygon feature representing the area they overlap;
* if poly1 and poly2 do not overlap, returns undefined;
* if poly1 and poly2 share a border, a MultiLineString of the locations where their borders are shared
*/
function intersect(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature;
/**
* Takes a set of polygons and returns a single merged polygon feature.
* If the input polygon features are not contiguous, this function returns a MultiPolygon feature.
* @param fc Input polygons
* @returns Merged polygon or multipolygon
*/
function merge(fc: GeoJSON.FeatureCollection): GeoJSON.Feature;
/**
* Takes a LineString or Polygon and returns a simplified version.
* Internally uses simplify-js to perform simplification.
* @param feature Feature to be simplified
* @param tolerance Simplification tolerance
* @param highQuality Whether or not to spend more time to create a higher-quality simplification with a different algorithm
* @returns A simplified feature
*/
function simplify(feature: GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection, tolerance: number, highQuality: boolean): GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection;
/**
* Takes two polygons and returns a combined polygon.
* If the input polygons are not contiguous, this function returns a MultiPolygon feature.
* @param poly1 Input polygon
* @param poly2 Another input polygon
* @returns A combined Polygon or MultiPolygon feature
*/
function union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature;
//////////////////////////////////////////////////////
// Misc
//////////////////////////////////////////////////////
/**
* Combines a FeatureCollection of Point, LineString, or Polygon features into MultiPoint, MultiLineString, or MultiPolygon features.
* @param fc A FeatureCollection of any type
* @returns A FeatureCollection of corresponding type to input
*/
function combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection;
/**
* Takes a feature or set of features and returns all positions as points.
* @param input Input features
* @returns Points representing the exploded input features
*/
function explode(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.FeatureCollection;
/**
* Takes input features and flips all of their coordinates from [x, y] to [y, x].
* @param input Input features
* @returns A feature or set of features of the same type as input with flipped coordinates
*/
function flip(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature | GeoJSON.FeatureCollection;
/**
* Takes a polygon and returns points at all self-intersections.
* @param polygon Input polygon
* @returns Self-intersections
*/
function kinks(polygon: GeoJSON.Feature): GeoJSON.FeatureCollection;
/**
* Takes a line, a start Point, and a stop point and returns the line in between those points.
* @param point1 Starting point
* @param point2 Stopping point
* @param line Line to slice
* @returns Sliced line
*/
function lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature;
/**
* Takes a Point and a LineString and calculates the closest Point on the LineString.
* @param line Line to snap to
* @param point Point to snap from
* @returns Closest point on the line to point
*/
function pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature;
//////////////////////////////////////////////////////
// Helper
//////////////////////////////////////////////////////
/**
* Takes one or more Features and creates a FeatureCollection.
* @param features Input features
* @returns A FeatureCollection of input features
*/
function featurecollection(features: Array<GeoJSON.Feature>): GeoJSON.FeatureCollection;
/**
* Creates a LineString based on a coordinate array. Properties can be added optionally.
* @param coordinates An array of Positions
* @param [properties] An Object of key-value pairs to add as properties
* @returns A LineString feature
*/
function linestring(coordinates: Array<Array<number>>, properties?: any): GeoJSON.Feature;
/**
* Takes coordinates and properties (optional) and returns a new Point feature.
* @param coordinates Longitude, latitude position (each in decimal degrees)
* @param [properties] An Object of key-value pairs to add as properties
* @returns A Point feature
*/
function point(coordinates: Array<number>, properties?: any): GeoJSON.Feature;
/**
* Takes an array of LinearRings and optionally an Object with properties and returns a Polygon feature.
* @param rings An array of LinearRings
* @param [properties] An Object of key-value pairs to add as properties
* @returns A Polygon feature
*/
function polygon(rings: Array<Array<Array<number>>>, properties?: any): GeoJSON.Feature;
//////////////////////////////////////////////////////
// Data
//////////////////////////////////////////////////////
/**
* Takes a FeatureCollection and filters it by a given property and value.
* @param features Input features
* @param key The property on which to filter
* @param value The value of that property on which to filter
* @returns A filtered collection with only features that match input key and value
*/
function filter(features: GeoJSON.FeatureCollection, key: string, value: string): GeoJSON.FeatureCollection;
/**
* Generates random GeoJSON data, including Points and Polygons, for testing and experimentation.
* @param [type='point'] Type of features desired: 'points' or 'polygons'
* @param [count=1] How many geometries should be generated.
* @param [options] Options relevant to the feature desired. Can include:
* - A bounding box inside of which geometries are placed. In the case of Point features, they are guaranteed to be within this bounds, while Polygon features have their centroid within the bounds.
* - The number of vertices added to polygon features. Default is 10;
* - The total number of decimal degrees longitude or latitude that a polygon can extent outwards to from its center. Default is 10.
* @returns Generated random features
*/
function random(type?: string, count?: number, options?: {bbox?: Array<number>; num_vertices?: number; max_radial_length?: number;}): GeoJSON.FeatureCollection;
/**
* Takes a FeatureCollection of any type, a property, and a value and returns a FeatureCollection with features matching that property-value pair removed.
* @param features Set of input features
* @param property The property to remove
* @param value The value to remove
* @returns The resulting FeatureCollection without features that match the property-value pair
*/
function remove(features: GeoJSON.FeatureCollection, property: string, value: string): GeoJSON.FeatureCollection;
/**
* Takes a FeatureCollection and returns a FeatureCollection with given number of features at random.
* @param features Set of input features
* @param n Number of features to select
* @returns A FeatureCollection with n features
*/
function sample(features: GeoJSON.FeatureCollection, n: number): GeoJSON.FeatureCollection;
//////////////////////////////////////////////////////
// Interpolation
//////////////////////////////////////////////////////
/**
* Takes a bounding box and a cell size in degrees and returns a FeatureCollection of flat-topped hexagons (Polygon features) aligned in an "odd-q" vertical grid as described in Hexagonal Grids.
* @param bbox Bounding box in [minX, minY, maxX, maxY] order
* @param cellWidth Width of cell in specified units
* @param units Used in calculating cellWidth ('miles' or 'kilometers')
* @returns A hexagonal grid
*/
function hexGrid(bbox: Array<number>, cellWidth: number, units: string): GeoJSON.FeatureCollection;
/**
* Takes points with z-values and an array of value breaks and generates isolines.
* @param points Input points
* @param z The property name in points from which z-values will be pulled
* @param resolution Resolution of the underlying grid
* @param breaks Where to draw contours
* @returns Isolines
*/
function isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array<number>): GeoJSON.FeatureCollection;
/**
* Takes a triangular plane as a Polygon and a Point within that triangle and returns the z-value at that point.
* The Polygon needs to have properties a, b, and c that define the values at its three corners.
* @param interpolatedPoint The Point for which a z-value will be calculated
* @param triangle A Polygon feature with three vertices
* @returns The z-value for interpolatedPoint
*/
function planepoint(interpolatedPoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number;
/**
* Takes a bounding box and a cell depth and returns a set of points in a grid.
* @param extent Extent in [minX, minY, maxX, maxY] order
* @param cellWidth The distance across each cell
* @param units Used in calculating cellWidth ('miles' or 'kilometers')
* @returns Grid of points
*/
function pointGrid(extent: Array<number>, cellWidth: number, units: string): GeoJSON.FeatureCollection;
/**
* Takes a bounding box and a cell depth and returns a set of square polygons in a grid.
* @param extent Extent in [minX, minY, maxX, maxY] order
* @param cellWidth Width of each cell
* @param units Used in calculating cellWidth ('miles' or 'kilometers')
* @returns Grid of polygons
*/
function squareGrid(extent: Array<number>, cellWidth: number, units: string): GeoJSON.FeatureCollection;
/**
* Takes a set of points and the name of a z-value property and creates a Triangulated Irregular Network, or a TIN for short, returned as a collection of Polygons.
* These are often used for developing elevation contour maps or stepped heat visualizations.
* This triangulates the points, as well as adds properties called a, b, and c representing the value of the given propertyName at each of the points that represent the corners of the triangle.
* @param points Input points
* @param [propertyName] Name of the property from which to pull z values This is optional: if not given, then there will be no extra data added to the derived triangles.
* @returns TIN output
*/
function tin(points: GeoJSON.FeatureCollection, propertyName?: string): GeoJSON.FeatureCollection;
/**
* Takes a bounding box and a cell depth and returns a set of triangular polygons in a grid.
* @param extent Extent in [minX, minY, maxX, maxY] order
* @param cellWidth Width of each cell
* @param units Used in calculating cellWidth ('miles' or 'kilometers')
* @returns Grid of triangles
*/
function triangleGrid(extent: Array<number>, cellWidth: number, units: string): GeoJSON.FeatureCollection;
//////////////////////////////////////////////////////
// Joins
//////////////////////////////////////////////////////
/**
* Takes a Point and a Polygon or MultiPolygon and determines if the point resides inside the polygon.
* The polygon can be convex or concave. The function accounts for holes.
* @param point Input point
* @param polygon Input polygon or multipolygon
* @returns true if the Point is inside the Polygon; false if the Point is not inside the Polygon
*/
function inside(point: GeoJSON.Feature, polygon: GeoJSON.Feature): boolean;
/**
* Takes a set of points and a set of polygons and performs a spatial join.
* @param points Input points
* @param polygons Input polygons
* @param polyId Property in polygons to add to joined Point features
* @param containingPolyId Property in points in which to store joined property from polygons
* @returns Points with containingPolyId property containing values from polyId
*/
function tag(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection, polyId: string, containingPolyId: string): GeoJSON.FeatureCollection;
/**
* Takes a set of points and a set of polygons and returns the points that fall within the polygons.
* @param points Input points
* @param polygons Input polygons
* @returns Points that land within at least one polygon
*/
function within(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection;
//////////////////////////////////////////////////////
// Classification
//////////////////////////////////////////////////////
/**
* Takes a set of features and returns an array of the Jenks Natural breaks for a given property.
* @param input Input features
* @param field The property in input on which to calculate Jenks natural breaks
* @param numberOfBreaks Number of classes in which to group the data
* @returns The break number for each class plus the minimum and maximum values
*/
function jenks(input: GeoJSON.FeatureCollection, field: string, numberOfBreaks: number): Array<number>;
/**
* Takes a reference point and a set of points and returns the point from the set closest to the reference.
* @param point The reference point
* @param against Input point set
* @returns The closest point in the set to the reference point
*/
function nearest(point: GeoJSON.Feature, against: GeoJSON.FeatureCollection): GeoJSON.Feature;
/**
* Takes a FeatureCollection, a property name, and a set of percentiles and returns a quantile array.
* @param input Set of features
* @param field The property in input from which to retrieve quantile values
* @param percentiles An Array of percentiles on which to calculate quantile values
* @returns An array of the break values
*/
function quantile(input: GeoJSON.FeatureCollection, field: string, percentiles: Array<number>): Array<number>;
/**
* Takes a FeatureCollection, an input field, an output field, and an array of translations and outputs an identical FeatureCollection with the output field property populated.
* @param input Set of input features
* @param inField The field to translate
* @param outField The field in which to store translated results
* @param translations An array of translations
* @returns A FeatureCollection with identical geometries to input but with outField populated.
*/
function reclass(input: GeoJSON.FeatureCollection, inField: string, outField: string, translations: Array<any>): GeoJSON.FeatureCollection;
}
+128
View File
@@ -0,0 +1,128 @@
/// <reference path="webdriverio.d.ts" />
/// <reference path="../mocha/mocha.d.ts" />
/// <reference path="../chai/chai.d.ts" />
import {assert} from "chai";
describe("webdriver.io page", function() {
it("should have the right title - the good old callback way", function(done) {
browser
.url("/")
.getTitle(function(err, title) {
assert.equal(err, undefined);
assert.equal(title, "WebdriverIO - Selenium 2.0 javascript bindings for nodejs");
})
.call(done);
});
it("should have the right title - the promise way", function() {
return browser
.url("/")
.getTitle().then(function(title) {
assert.equal(title, "WebdriverIO - Selenium 2.0 javascript bindings for nodejs");
});
});
});
import * as webdriverio from "webdriverio";
describe("my webdriverio tests", function(){
this.timeout(99999999);
var client: webdriverio.Client<void>;
before(function(done){
client = webdriverio.remote({ desiredCapabilities: {browserName: "phantomjs"} });
client.init(done);
});
it("Github test",function(done) {
client
.url("https://github.com/")
.getElementSize(".header-logo-wordmark", function(err: any, result: webdriverio.Size) {
assert.equal(undefined, err);
assert.strictEqual(result.height, 26);
assert.strictEqual(result.width, 89);
})
.getTitle(function(err: any, title: string) {
assert.equal(undefined, err);
assert.strictEqual(title,"GitHub · Where software is built");
})
.getCssProperty("a[href='/plans']", "color", function(err: any, result: webdriverio.CssProperty){
assert.equal(undefined, err);
assert.strictEqual(result.value, "rgba(64,120,192,1)");
})
.call(done);
});
after(function(done) {
client.end(done);
});
});
var matrix = webdriverio.multiremote({
browserA: {
desiredCapabilities: {
browserName: "chrome",
chromeOptions: {
args: [
"use-fake-device-for-media-stream",
"use-fake-ui-for-media-stream",
]
}
}
},
browserB: {
desiredCapabilities: {
browserName: "chrome",
chromeOptions: {
args: [
"use-fake-device-for-media-stream",
"use-fake-ui-for-media-stream",
]
}
}
}
});
var channel = Math.round(Math.random() * 100000000000);
matrix
.init()
.url("https://apprtc.appspot.com/r/" + channel)
.click("#confirm-join-button")
.pause(5000)
.end();
var options = {
desiredCapabilities: {
browserName: "chrome"
}
};
webdriverio
.remote(options)
.init()
.url("https://news.ycombinator.com/")
.selectorExecute("//div", function(inputs: HTMLElement[], message: string) {
return inputs.length + " " + message;
}, "divs on the page")
.then(function(res){
console.log(res);
})
.end();
webdriverio
.remote(options)
.init()
.url("http://www.google.com/")
.waitForVisible("//input[@type='submit']", 5000)
.then(function(visible){
console.log(visible); //Should return true
})
.end();
+1064
View File
File diff suppressed because it is too large Load Diff
+33 -33
View File
@@ -9,23 +9,23 @@
/// <reference path="../es6-promise/es6-promise.d.ts" />
interface ConstrainBooleanParameters {
exact: boolean;
ideal: boolean;
exact?: boolean;
ideal?: boolean;
}
interface NumberRange {
max: number;
min: number;
max?: number;
min?: number;
}
interface ConstrainNumberRange extends NumberRange {
exact: number;
ideal: number;
exact?: number;
ideal?: number;
}
interface ConstrainStringParameters {
exact: string | string[];
ideal: string | string[];
exact?: string | string[];
ideal?: string | string[];
}
interface MediaStreamConstraints {
@@ -63,38 +63,38 @@ interface MediaTrackConstraintSet {
}
interface MediaTrackSupportedConstraints {
width: boolean;
height: boolean;
aspectRatio: boolean;
frameRate: boolean;
facingMode: boolean;
volume: boolean;
sampleRate: boolean;
sampleSize: boolean;
echoCancellation: boolean;
latency: boolean;
deviceId: boolean;
groupId: boolean;
width?: boolean;
height?: boolean;
aspectRatio?: boolean;
frameRate?: boolean;
facingMode?: boolean;
volume?: boolean;
sampleRate?: boolean;
sampleSize?: boolean;
echoCancellation?: boolean;
latency?: boolean;
deviceId?: boolean;
groupId?: boolean;
}
interface MediaStream extends EventTarget {
id: string;
active: boolean;
onactive: EventListener;
oninactive: EventListener;
onaddtrack: (event: MediaStreamTrackEvent) => any;
onremovetrack: (event: MediaStreamTrackEvent) => any;
clone(): MediaStream;
stop(): void;
getAudioTracks(): MediaStreamTrack[];
getVideoTracks(): MediaStreamTrack[];
getTracks(): MediaStreamTrack[];
getTrackById(trackId: string): MediaStreamTrack;
addTrack(track: MediaStreamTrack): void;
removeTrack(track: MediaStreamTrack): void;
}
@@ -116,16 +116,16 @@ interface MediaStreamTrack extends EventTarget {
muted: boolean;
remote: boolean;
readyState: MediaStreamTrackState;
onmute: EventListener;
onunmute: EventListener;
onended: EventListener;
onoverconstrained: EventListener;
clone(): MediaStreamTrack;
stop(): void;
getCapabilities(): MediaTrackCapabilities;
getConstraints(): MediaTrackConstraints;
getSettings(): MediaTrackSettings;
@@ -176,13 +176,13 @@ interface NavigatorGetUserMedia {
interface Navigator {
getUserMedia: NavigatorGetUserMedia;
webkitGetUserMedia: NavigatorGetUserMedia;
mozGetUserMedia: NavigatorGetUserMedia;
msGetUserMedia: NavigatorGetUserMedia;
mediaDevices: MediaDevices;
}