This commit is contained in:
emmanuel
2015-12-14 18:16:21 +01:00
313 changed files with 35217 additions and 5549 deletions
+1
View File
@@ -13,6 +13,7 @@
*.map
*.swp
.DS_Store
npm-debug.log
_Resharper.DefinitelyTyped
bin
+1 -1
View File
@@ -1,6 +1,6 @@
language: node_js
node_js:
- "iojs-v2"
- 4
sudo: false
+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)
+5
View File
@@ -0,0 +1,5 @@
/// <reference path="./abs.d.ts" />
import Abs from 'abs';
const x: string = Abs('/foo');
+14
View File
@@ -0,0 +1,14 @@
// Type definitions for abs 1.1.0
// Project: https://github.com/IonicaBizau/node-abs
// Definitions by: Aya Morisawa <https://github.com/AyaMorisawa>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "abs" {
/**
* Compute the absolute path of an input.
* @param input The input path.
*/
function Abs(input: string): string;
export default Abs;
}
+5
View File
@@ -0,0 +1,5 @@
/// <reference path="./absolute.d.ts" />
import absolute from 'absolute';
const x: boolean = absolute('/home/foo');
+13
View File
@@ -0,0 +1,13 @@
// Type definitions for absolute 0.0.1
// Project: https://github.com/bahamas10/node-absolute
// Definitions by: Aya Morisawa <https://github.com/AyaMorisawa>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "absolute" {
/**
* Test if a path is absolute
*/
function absolute(path: string): boolean;
export default absolute;
}
+294 -294
View File
File diff suppressed because it is too large Load Diff
+30 -2
View File
@@ -1,10 +1,9 @@
/// <reference path="adm-zip.d.ts" />
import AdmZip = require("adm-zip");
// reading archives
var zip = new AdmZip("./my_file.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
var zipEntries: AdmZip.IZipEntry[] = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function (zipEntry) {
console.log(zipEntry.toString()); // outputs zip entries information
@@ -31,3 +30,32 @@ zip.addLocalFile("/home/me/some_picture.png");
var willSendthis = zip.toBuffer();
// or write everything to disk
zip.writeZip(/*target file name*/"/home/me/files.zip");
function processZipEntry(zipEntry: AdmZip.IZipEntry) {
console.log('comment', zipEntry.comment);
}
//tests taken from examples at https://github.com/cthackers/adm-zip/wiki/ADM-ZIP
import Zip = require("adm-zip");
// loads and parses existing zip file local_file.zip
var zip = new Zip("local_file.zip");
// creates new in memory zip
zip = new Zip();
// loads and parses existing zip file local_file.zip
zip = new Zip("local_file.zip");
// get all entries and iterate them
zip.getEntries().forEach((entry) => {
var entryName = entry.entryName;
var decompressedData = zip.readFile(entry); // decompressed buffer of the entry
console.log(zip.readAsText(entry)); // outputs the decompressed content of the entry
});
// will extract the file myfile.txt from the archive to /home/user/folder/subfolder/myfile.txt
zip.extractEntryTo("folder/subfolder/myfile.txt", "/home/user/", true, true);
// will extract the file myfile.txt from the archive to /home/user/myfile.txt
zip.extractEntryTo("folder/subfolder/myfile.txt", "/home/user/", false, true);
function isAdmZipEntry(obj: any): obj is AdmZip.IZipEntry {
return obj !== null && typeof obj === "object" && typeof obj['entryName'] === 'string';
}
+80 -81
View File
@@ -5,8 +5,8 @@
/// <reference path="../node/node.d.ts" />
declare module AdmZip {
class ZipFile {
declare module "adm-zip" {
class AdmZip {
/**
* Create a new, empty archive.
*/
@@ -28,7 +28,7 @@ declare module AdmZip {
* @param entry ZipEntry object
* @return Buffer or Null in case of error
*/
readFile(entry: IZipEntry): Buffer;
readFile(entry: AdmZip.IZipEntry): Buffer;
/**
* Asynchronous readFile
* @param entry String with the full path of the entry
@@ -41,7 +41,7 @@ declare module AdmZip {
* @param callback Called with a Buffer or Null in case of error
* @return Buffer or Null in case of error
*/
readFileAsync(entry: IZipEntry, callback: (data: Buffer, err: string) => any): void;
readFileAsync(entry: AdmZip.IZipEntry, callback: (data: Buffer, err: string) => any): void;
/**
* Extracts the given entry from the archive and returns the content as
* plain text in the given encoding
@@ -57,7 +57,7 @@ declare module AdmZip {
* @param encoding Optional. If no encoding is specified utf8 is used
* @return String
*/
readAsText(fileName: IZipEntry, encoding?: string): string;
readAsText(fileName: AdmZip.IZipEntry, encoding?: string): string;
/**
* Asynchronous readAsText
* @param entry String with the full path of the entry
@@ -71,7 +71,7 @@ declare module AdmZip {
* @param callback Called with the resulting string.
* @param encoding Optional. If no encoding is specified utf8 is used
*/
readAsTextAsync(fileName: IZipEntry, callback: (data: string) => any, encoding?: string): void;
readAsTextAsync(fileName: AdmZip.IZipEntry, callback: (data: string) => any, encoding?: string): void;
/**
* Remove the entry from the file or the entry and all its nested directories
* and files if the given entry is a directory
@@ -83,7 +83,7 @@ declare module AdmZip {
* and files if the given entry is a directory
* @param entry A ZipEntry object.
*/
deleteFile(entry: IZipEntry): void;
deleteFile(entry: AdmZip.IZipEntry): void;
/**
* Adds a comment to the zip. The zip must be rewritten after
* adding the comment.
@@ -110,7 +110,7 @@ declare module AdmZip {
* @param entry ZipEntry object.
* @param comment The comment to add to the entry.
*/
addZipEntryComment(entry: IZipEntry, comment: string): void;
addZipEntryComment(entry: AdmZip.IZipEntry, comment: string): void;
/**
* Returns the comment of the specified entry.
* @param entry String with the full path of the entry.
@@ -122,7 +122,7 @@ declare module AdmZip {
* @param entry ZipEntry object.
* @return String The comment of the specified entry.
*/
getZipEntryComment(entry: IZipEntry): string;
getZipEntryComment(entry: AdmZip.IZipEntry): string;
/**
* Updates the content of an existing entry inside the archive. The zip
* must be rewritten after updating the content
@@ -136,7 +136,7 @@ declare module AdmZip {
* @param entry ZipEntry object.
* @param content The entry's new contents.
*/
updateFile(entry: IZipEntry, content: Buffer): void;
updateFile(entry: AdmZip.IZipEntry, content: Buffer): void;
/**
* Adds a file from the disk to the archive.
* @param localPath Path to a file on disk.
@@ -167,14 +167,14 @@ declare module AdmZip {
* Returns an array of ZipEntry objects representing the files and folders
* inside the archive
*/
getEntries(): IZipEntry[];
getEntries(): AdmZip.IZipEntry[];
/**
* Returns a ZipEntry object representing the file or folder specified by
* ``name``.
* @param name Name of the file or folder to retrieve.
* @return ZipEntry The entry corresponding to the name.
*/
getEntry(name: string): IZipEntry;
getEntry(name: string): AdmZip.IZipEntry;
/**
* Extracts the given entry to the given targetPath.
* If the entry is a directory inside the archive, the entire directory and
@@ -203,7 +203,7 @@ declare module AdmZip {
* will be overwriten if this is true. Default is FALSE
* @return Boolean
*/
extractEntryTo(entryPath: IZipEntry, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean;
extractEntryTo(entryPath: AdmZip.IZipEntry, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean;
/**
* Extracts the entire archive to the given location
* @param targetPath Target location
@@ -225,76 +225,75 @@ declare module AdmZip {
toBuffer(): Buffer;
}
/**
* The ZipEntry is more than a structure representing the entry inside the
* zip file. Beside the normal attributes and headers a entry can have, the
* class contains a reference to the part of the file where the compressed
* data resides and decompresses it when requested. It also compresses the
* data and creates the headers required to write in the zip file.
*/
interface IZipEntry {
module AdmZip {
/**
* Represents the full name and path of the file
* The ZipEntry is more than a structure representing the entry inside the
* zip file. Beside the normal attributes and headers a entry can have, the
* class contains a reference to the part of the file where the compressed
* data resides and decompresses it when requested. It also compresses the
* data and creates the headers required to write in the zip file.
*/
entryName: string;
rawEntryName: Buffer;
/**
* Extra data associated with this entry.
*/
extra: Buffer;
/**
* Entry comment.
*/
comment: string;
name: string;
/**
* Read-Only property that indicates the type of the entry.
*/
isDirectory: boolean;
/**
* Get the header associated with this ZipEntry.
*/
header: Buffer;
/**
* Retrieve the compressed data for this entry. Note that this may trigger
* compression if any properties were modified.
*/
getCompressedData(): Buffer;
/**
* Asynchronously retrieve the compressed data for this entry. Note that
* this may trigger compression if any properties were modified.
*/
getCompressedDataAsync(callback: (data: Buffer) => void): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: string): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: Buffer): void;
/**
* Get the decompressed data associated with this entry.
*/
getData(): Buffer;
/**
* Asynchronously get the decompressed data associated with this entry.
*/
getDataAsync(callback: (data: Buffer) => void): void;
/**
* Returns the CEN Entry Header to be written to the output zip file, plus
* the extra data and the entry comment.
*/
packHeader(): Buffer;
/**
* Returns a nicely formatted string with the most important properties of
* the ZipEntry.
*/
toString(): string;
interface IZipEntry {
/**
* Represents the full name and path of the file
*/
entryName: string;
rawEntryName: Buffer;
/**
* Extra data associated with this entry.
*/
extra: Buffer;
/**
* Entry comment.
*/
comment: string;
name: string;
/**
* Read-Only property that indicates the type of the entry.
*/
isDirectory: boolean;
/**
* Get the header associated with this ZipEntry.
*/
header: Buffer;
/**
* Retrieve the compressed data for this entry. Note that this may trigger
* compression if any properties were modified.
*/
getCompressedData(): Buffer;
/**
* Asynchronously retrieve the compressed data for this entry. Note that
* this may trigger compression if any properties were modified.
*/
getCompressedDataAsync(callback: (data: Buffer) => void): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: string): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: Buffer): void;
/**
* Get the decompressed data associated with this entry.
*/
getData(): Buffer;
/**
* Asynchronously get the decompressed data associated with this entry.
*/
getDataAsync(callback: (data: Buffer) => void): void;
/**
* Returns the CEN Entry Header to be written to the output zip file, plus
* the extra data and the entry comment.
*/
packHeader(): Buffer;
/**
* Returns a nicely formatted string with the most important properties of
* the ZipEntry.
*/
toString(): string;
}
}
}
declare module "adm-zip" {
import zipFile = AdmZip.ZipFile;
export = zipFile;
export = AdmZip;
}
+1 -1
View File
@@ -25,6 +25,6 @@ declare module angular.jwt {
}
interface IJwtInterceptor {
tokenGetter(): string;
tokenGetter(...params : any[]): string;
}
}
+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;
}
+2 -2
View File
@@ -96,5 +96,5 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia
});
myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => {
$scope['openToast'] = () => $mdToast.show($mdToast.simple().content('Hello!'));
});
$scope['openToast'] = () => $mdToast.show($mdToast.simple().textContent('Hello!'));
});
+3 -3
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular Material 0.10.1-rc1+ (angular.material module)
// Type definitions for Angular Material 1.0.0-rc5+ (angular.material module)
// Project: https://github.com/angular/material
// Definitions by: Matt Traynham <https://github.com/mtraynham>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -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;
}
@@ -116,7 +116,7 @@ declare module angular.material {
}
interface IToastPreset<T> {
content(content: string): T;
textContent(content: string): T;
action(action: string): T;
highlightAction(highlightAction: boolean): T;
capsule(capsule: boolean): T;
+11 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for angular-notify 2.0.2
// Type definitions for angular-notify 2.5.0
// Project: https://github.com/cgross/angular-notify
// Definitions by: Suwato <https://github.com/Suwato/DefinitelyTyped>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -51,6 +51,11 @@ declare module angular.cgNotify {
* Optional. Currently center and right are the only acceptable values.
*/
position? : string;
/**
* Optional. The duration (in milliseconds) of the message. A duration of 0 will prevent the message from closing automatically.
*/
duration? : number;
/**
* Optional. Element that contains each notification. Defaults to document.body.
@@ -94,6 +99,11 @@ declare module angular.cgNotify {
* The default element that contains each notification. Defaults to document.body.
*/
container? : any;
/**
* The maximum number of total notifications that can be visible at one time. Older notifications will be closed when the maximum is reached.
*/
maximumOpen? : number;
}):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
///////////////////////////////////////
+4 -1
View File
@@ -136,12 +136,15 @@ 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;
}
}
/**
* Really just a regular Array object with $promise and $resolve attached to it
*/
interface IResourceArray<T> extends Array<T> {
interface IResourceArray<T> extends Array<T & IResource<T>> {
/** the promise of the original server interaction that created this collection. **/
$promise : angular.IPromise<IResourceArray<T>>;
$resolved : boolean;
+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;
}
+7 -1
View File
@@ -165,6 +165,12 @@ declare module angular {
dot: number;
codeName: string;
};
/**
* If window.name contains prefix NG_DEFER_BOOTSTRAP! when angular.bootstrap is called, the bootstrap process will be paused until angular.resumeBootstrap() is called.
* @param extraModules An optional array of modules that should be added to the original list of modules that the app was about to be bootstrapped with.
*/
resumeBootstrap?(extraModules?: string[]): ng.auto.IInjectorService;
}
///////////////////////////////////////////////////////////////////////////
@@ -615,7 +621,7 @@ declare module angular {
// see http://docs.angularjs.org/api/ng.$interval
///////////////////////////////////////////////////////////////////////////
interface IIntervalService {
(func: Function, delay: number, count?: number, invokeApply?: boolean): IPromise<any>;
(func: Function, delay: number, count?: number, invokeApply?: boolean, ...args: any[]): IPromise<any>;
cancel(promise: IPromise<any>): boolean;
}
+440 -241
View File
File diff suppressed because it is too large Load Diff
+66
View File
@@ -0,0 +1,66 @@
/// <reference path="async-writer.d.ts" />
import asyncWriter = require('async-writer');
import stream = require('stream');
class TestStream extends stream.Writable {
constructor(public output: string) {
super();
}
_write(data: string, encoding: string, callback: Function) {
this.output += data;
callback();
}
}
// Simple usage
function simpleUsage(callback: () => void) {
var output = '';
let testStream = new TestStream(output);
let out = asyncWriter.create(testStream)
.on('error', (err: Error) => {
console.error(err);
})
.on('finish', () => {
console.log(testStream.output);
callback();
})
out.write('A');
out.write('B');
out.write('C');
out.end();
}
// Asynchronous, out-of-order writing
function asyncUsage(callback: () => void) {
var output = '';
let testStream = new TestStream(output);
let out = asyncWriter.create(testStream)
.on('error', (err: Error) => {
console.error(err);
})
.on('finish', () => {
console.log(testStream.output);
callback();
})
out.write('A');
let asyncOut = out.beginAsync();
setTimeout(() => {
asyncOut.write('B');
asyncOut.end();
}, 1000);
out.write('C');
out.end();
}
// run test
simpleUsage(() => {
asyncUsage(() => {
console.log('DONE');
});
});
+78
View File
@@ -0,0 +1,78 @@
// Type definitions for async-writer 1.4.1
// Project: https://github.com/marko-js/async-writer
// Definitions by: Yuce Tekol <http://yuce.me/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module 'async-writer' {
import stream = require('stream');
import events = require('events');
module async_writer {
interface EventFunction {
(event: string, callback: Function): void;
}
class StringWriter {
constructor(events: events.EventEmitter);
end(): void;
write(what: string): StringWriter;
toString(): string;
}
class BufferedWriter {
constructor(wrappedStream: stream.Stream);
flush(): void;
on(event: string, callback: Function): BufferedWriter;
once(event: string, callback: Function): BufferedWriter;
clear(): void;
end(): void;
write(what: string): BufferedWriter;
}
interface BeginAsyncOptions {
last?: boolean;
timeout?: number;
name?: string;
}
class AsyncWriter {
static enableAsyncStackTrace():void;
constructor(writer?: any, global?: {[s: string]: any}, async?: boolean, buffer?: boolean);
isAsyncWriter: AsyncWriter;
sync(): void;
getAttributes(): {[s: string]: any};
getAttribute(): any;
write(str: string): AsyncWriter;
getOutput(): string;
captureString(func: Function, thisObj: Object): string;
swapWriter(newWriter: StringWriter | BufferedWriter, func: Function, thisObj: Object): void;
createNestedWriter(writer: StringWriter | BufferedWriter): AsyncWriter;
beginAsync(options?: number | BeginAsyncOptions): AsyncWriter;
handleBeginAsync(options: number | BeginAsyncOptions, parent: AsyncWriter): void;
on(event: string, callback: Function): AsyncWriter;
once(event: string, callback: Function): AsyncWriter;
onLast(callback: Function): AsyncWriter;
emit(arg: any): AsyncWriter;
removeListener(): AsyncWriter;
pipe(stream: stream.Stream): AsyncWriter;
error(e: Error): void;
end(data?: any): AsyncWriter;
handleEnd(isAsync: boolean): void;
_finish(): void;
flush(): void;
}
interface AsyncWriterOptions {
global?: {[s: string]: any};
buffer?: boolean;
}
function create(writer?: any, options?: AsyncWriterOptions): AsyncWriter;
function enableAsyncStackTrace(): void;
}
export = async_writer;
}
+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;
+2 -2
View File
@@ -131,7 +131,7 @@ declare class Promise<R> implements Promise.Thenable<R> {
* Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable.
*/
// TODO what to do with this?
cancel<U>(): Promise<U>;
cancel<U>(reason?: any): Promise<U>;
/**
* Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors.
@@ -394,7 +394,7 @@ declare class Promise<R> implements Promise.Thenable<R> {
* Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method.
*/
// TODO how to model promisifyAll?
static promisifyAll(target: Object): Object;
static promisifyAll(target: Object): any;
/**
* Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
+5 -5
View File
@@ -20,14 +20,14 @@ declare class Promise<R> implements Promise.Thenable<R>, Promise.Inspection<R> {
/**
* Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise.
*/
constructor(callback: (resolve: (thenableOrResult: R | Promise.Thenable<R>) => void, reject: (error: any) => void) => void);
constructor(callback: (resolve: (thenableOrResult?: R | Promise.Thenable<R>) => void, reject: (error: any) => void) => void);
/**
* Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise.
*/
then<U>(onFulfill: (value: R) => U|Promise.Thenable<U>, onReject?: (error: any) => U|Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill: (value: R) => U|Promise.Thenable<U>, onReject?: (error: any) => void|Promise.Thenable<void>, onProgress?: (note: any) => any): Promise<U>;
/**
* This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
*
@@ -117,7 +117,7 @@ declare class Promise<R> implements Promise.Thenable<R>, Promise.Inspection<R> {
* Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything.
*/
nodeify(callback: (err: any, value?: R) => void, options?: Promise.SpreadOption): Promise<R>;
nodeify(...sink: any[]): void;
nodeify(...sink: any[]): Promise<R>;
/**
* Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise.
@@ -134,7 +134,7 @@ declare class Promise<R> implements Promise.Thenable<R>, Promise.Inspection<R> {
* Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable.
*/
// TODO what to do with this?
cancel<U>(): Promise<U>;
cancel<U>(reason?: any): Promise<U>;
/**
* Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors.
@@ -421,7 +421,7 @@ declare class Promise<R> implements Promise.Thenable<R>, Promise.Inspection<R> {
* Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method.
*/
// TODO how to model promisifyAll?
static promisifyAll(target: Object, options?: Promise.PromisifyAllOptions): Object;
static promisifyAll(target: Object, options?: Promise.PromisifyAllOptions): any;
/**
@@ -6,17 +6,17 @@ function test_cases() {
$('#datetimepicker').datetimepicker({
pickDate: false
});
$('#datetimepicker').datetimepicker({
$('#datetimepicker').datetimepicker({
pickTime: false
});
$('#datetimepicker').datetimepicker({
$('#datetimepicker').datetimepicker({
minDate: '2012-12-31'
});
$('#datetimepicker').data("DateTimePicker").setMaxDate('2012-12-31');
var startDate = new Date(2012, 1, 20);
var endDate = new Date(2012, 1, 25);
$('#datetimepicker').data("DateTimePicker").maxDate('2012-12-31');
var startDate = moment(new Date(2012, 1, 20));
var endDate = moment(new Date(2012, 1, 25));
$('#datetimepicker2')
.datetimepicker()
.on("dp.change", function (ev) {
+20 -14
View File
@@ -10,15 +10,15 @@
*/
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="../moment/moment.d.ts"/>
declare module BootstrapV3DatetimePicker {
interface DatetimepickerChangeEventObject extends JQueryEventObject {
date: any;
oldDate: any;
interface DatetimepickerChangeEventObject extends DatetimepickerEventObject {
oldDate: moment.Moment;
}
interface DatetimepickerEventObject extends JQueryEventObject {
date: any;
date: moment.Moment;
}
interface DatetimepickerIcons {
@@ -35,33 +35,39 @@ declare module BootstrapV3DatetimePicker {
useSeconds?: boolean;
useCurrent?: boolean;
minuteStepping?: number;
minDate?: any;
maxDate?: any;
minDate?: moment.Moment | Date | string;
maxDate?: moment.Moment | Date | string;
showToday?: boolean;
collapse?: boolean;
language?: string;
defaultDate?: string;
disabledDates?: Array<any>;
enabledDates?: Array<any>;
defaultDate?: moment.Moment | Date | string;
disabledDates?: Array<moment.Moment | Date | string>;
enabledDates?: Array<moment.Moment | Date | string>;
icons?: DatetimepickerIcons;
useStrict?: boolean;
direction?: string;
sideBySide?: boolean;
daysOfWeekDisabled?: Array<any>;
daysOfWeekDisabled?: Array<number>;
calendarWeeks?: boolean;
format?: string | boolean;
locale?: string;
showTodayButton?: boolean;
viewMode?: string;
inline?: boolean;
toolbarPlacement?: string;
showClear?: boolean;
}
interface Datetimepicker {
setDate(date: any): void;
setMinDate(date: any): void;
setMaxDate(date: any): void;
date(date: moment.Moment | Date | string): void;
date(): moment.Moment;
minDate(date: moment.Moment | Date | string): void;
minDate(): moment.Moment | boolean;
maxDate(date: moment.Moment | Date | string): void;
maxDate(): moment.Moment | boolean;
show(): void;
disable(): void;
enable(): void;
getDate(): void;
}
}
+1 -1
View File
@@ -371,7 +371,7 @@ declare module "browser-sync" {
* The stream method returns a transform stream and can act once or on many files.
* @param opts Configuration for the stream method
*/
stream(opts: { once: boolean }): NodeJS.ReadWriteStream;
stream(opts?: { once: boolean }): NodeJS.ReadWriteStream;
/**
* Helper method for browser notifications
* @param message Can be a simple message such as 'Connected' or HTML
+44 -4
View File
@@ -2,11 +2,51 @@
import browserify = require("browserify");
import fs = require("fs");
import stream = require('stream');
var b: BrowserifyObject = browserify();
var bNoArg = browserify();
var b = browserify({
baseDir: 'somewhere'
});
b.add('./browser/main.js');
b.transform('deamdify');
b.bundle().pipe(fs.createWriteStream('bundle.js'));
b.transform('deamdify')
.transform(function (file) {
return new stream.Transform();
}).plugin((b, opts) => { return opts.l; }, {l: 3})
.require('foo', { expose: 'bar' })
.exclude('baz')
.ignore('bat')
.reset({ basedir: 'elsewhere' });
var customBrowsify: Browserify = require("browserify");
b.on('file', (file) => {
file += "";
});
b.external(bNoArg);
var b2 = new browserify(['/some/File', {file: '/some/file' }, fs.createReadStream('/somewhere')], { builtins: ['buffer']})
.reset({
builtins: {
'buffer': './customBuffer'
}
});
var customBrowsify = require("browserify");
customBrowsify({entries: []});
var b = browserify('./browser/main.js', {
noParse: ['jquery'],
debug: true,
foo: 'bar'
});
b.add('./browser/other.js');
b.transform(function(file: string): NodeJS.ReadWriteStream {
return new stream.PassThrough();
});
var record_pipeline = b.pipeline.get('record');
b.bundle().pipe(process.stdout);
+169 -28
View File
@@ -1,41 +1,182 @@
// Type definitions for Browserify
// Type definitions for Browserify v12.0.1
// Project: http://browserify.org/
// Definitions by: Andrew Gaspar <https://github.com/AndrewGaspar/>
// Definitions by: Andrew Gaspar <https://github.com/AndrewGaspar/>, John Vilk <https://github.com/jvilk>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
interface BrowserifyObject extends NodeJS.EventEmitter {
add(file:string, opts?:any): BrowserifyObject;
require(file:string, opts?:{
expose: string;
}): BrowserifyObject;
bundle(opts?:{
insertGlobals?: boolean;
detectGlobals?: boolean;
debug?: boolean;
standalone?: string;
insertGlobalVars?: any;
}, cb?:(err:any, src:any) => void): NodeJS.ReadableStream;
declare module Browserify {
/**
* Options pertaining to an individual file.
*/
interface FileOptions {
// If true, this is considered an entry point to your app.
entry?: boolean;
// Expose this file under a custom dependency name.
// require('./vendor/angular/angular.js', {expose: 'angular'}) enables require('angular')
expose?: string;
// Basedir to use to resolve this file's path.
basedir?: string;
// The name/path to the file.
file?: string;
// Forward file to external() to be externalized.
external?: boolean;
// Disable transforms on file if set to false.
transform?: boolean;
// The ID to use for require() statements.
id?: string;
}
external(file:string, opts?:any): BrowserifyObject;
ignore(file:string, opts?:any): BrowserifyObject;
transform(tr:string, opts?:any): BrowserifyObject;
transform(tr:Function, opts?:any): BrowserifyObject;
plugin(plugin:string, opts?:any): BrowserifyObject;
plugin(plugin:Function, opts?:any): BrowserifyObject;
}
interface Browserify {
(): BrowserifyObject;
(files:string[]): BrowserifyObject;
(opts:{
entries?: string[];
// Browserify accepts a filename, an input stream for file inputs, or a FileOptions configuration
// for each file in a bundle.
type InputFile = string | NodeJS.ReadableStream | FileOptions;
/**
* Options pertaining to a Browserify instance.
*/
interface Options {
// Custom properties can be defined on Options.
// These options are forwarded along to module-deps and browser-pack directly.
[propName: string]: any;
// String, file object, or array of those types (they may be mixed) specifying entry file(s).
entries?: InputFile | InputFile[];
// an array which will skip all require() and global parsing for each file in the array.
// Use this for giant libs like jquery or threejs that don't have any requires or node-style globals but take forever to parse.
noParse?: string[];
}): BrowserifyObject;
// an array of optional extra extensions for the module lookup machinery to use when the extension has not been specified.
// By default Browserify considers only .js and .json files in such cases.
extensions?: string[];
// the directory that Browserify starts bundling from for filenames that start with ..
basedir?: string;
// an array of directories that Browserify searches when looking for modules which are not referenced using relative path.
// Can be absolute or relative to basedir. Equivalent of setting NODE_PATH environmental variable when calling Browserify command.
paths?: string[];
// sets the algorithm used to parse out the common paths. Use false to turn this off, otherwise it uses the commondir module.
commondir?: boolean;
// disables converting module ids into numerical indexes. This is useful for preserving the original paths that a bundle was generated with.
fullPaths?: boolean;
// sets the list of built-ins to use, which by default is set in lib/builtins.js in this distribution.
builtins?: string[] | {[builtinName: string]: string} | boolean;
// set if external modules should be bundled. Defaults to true.
bundleExternal?: boolean;
// When true, always insert process, global, __filename, and __dirname without analyzing the AST for faster builds but larger output bundles. Default false.
insertGlobals?: boolean;
// When true, scan all files for process, global, __filename, and __dirname, defining as necessary.
// With this option npm modules are more likely to work but bundling takes longer. Default true.
detectGlobals?: boolean;
// When true, add a source map inline to the end of the bundle. This makes debugging easier because you can see all the original files if you are in a modern enough browser.
debug?: boolean;
// When a non-empty string, a standalone module is created with that name and a umd wrapper.
// You can use namespaces in the standalone global export using a . in the string name as a separator, for example 'A.B.C'.
// The global export will be sanitized and camel cased.
standalone?: string;
// will be passed to insert-module-globals as the opts.vars parameter.
insertGlobalVars?: {[globalName: string]: (file: string, basedir: string) => any};
// defaults to 'require' in expose mode but you can use another name.
externalRequireName?: string;
}
interface BrowserifyConstructor {
(files: InputFile[], opts?: Options): BrowserifyObject;
(file: InputFile, opts?: Options): BrowserifyObject;
(opts: Options): BrowserifyObject;
(): BrowserifyObject
new(files: InputFile[], opts?: Options): BrowserifyObject;
new(file: InputFile, opts?: Options): BrowserifyObject;
new(opts: Options): BrowserifyObject;
new(): BrowserifyObject
}
interface BrowserifyObject extends NodeJS.EventEmitter {
/**
* Add an entry file from file that will be executed when the bundle loads.
* If file is an array, each item in file will be added as an entry file.
*/
add(file: InputFile[], opts?: FileOptions): BrowserifyObject;
add(file: InputFile, opts?: FileOptions): BrowserifyObject;
/**
* Make file available from outside the bundle with require(file).
* The file param is anything that can be resolved by require.resolve().
* file can also be a stream, but you should also use opts.basedir so that relative requires will be resolvable.
* If file is an array, each item in file will be required. In file array form, you can use a string or object for each item. Object items should have a file property and the rest of the parameters will be used for the opts.
* Use the expose property of opts to specify a custom dependency name. require('./vendor/angular/angular.js', {expose: 'angular'}) enables require('angular')
*/
require(file: InputFile, opts?: FileOptions): BrowserifyObject;
/**
* Bundle the files and their dependencies into a single javascript file.
* Return a readable stream with the javascript file contents or optionally specify a cb(err, buf) to get the buffered results.
*/
bundle(cb?: (err: any, src: Buffer) => any): NodeJS.ReadableStream;
/**
* Prevent file from being loaded into the current bundle, instead referencing from another bundle.
* If file is an array, each item in file will be externalized.
* If file is another bundle, that bundle's contents will be read and excluded from the current bundle as the bundle in file gets bundled.
*/
external(file: string[], opts?: { basedir?: string }): BrowserifyObject;
external(file: string, opts?: { basedir?: string }): BrowserifyObject;
external(file: BrowserifyObject): BrowserifyObject;
/**
* Prevent the module name or file at file from showing up in the output bundle.
* Instead you will get a file with module.exports = {}.
*/
ignore(file: string, opts?: { basedir?: string }): BrowserifyObject;
/**
* Prevent the module name or file at file from showing up in the output bundle.
* If your code tries to require() that file it will throw unless you've provided another mechanism for loading it.
*/
exclude(file: string, opts?: { basedir?: string }): BrowserifyObject;
/**
* Transform source code before parsing it for require() calls with the transform function or module name tr.
* If tr is a function, it will be called with tr(file) and it should return a through-stream that takes the raw file contents and produces the transformed source.
* If tr is a string, it should be a module name or file path of a transform module
*/
transform<T extends { basedir?: string }>(tr: string, opts?: T): BrowserifyObject;
transform<T extends { basedir?: string }>(tr: (file: string, opts: T) => NodeJS.ReadWriteStream, opts?: T): BrowserifyObject;
/**
* Register a plugin with opts. Plugins can be a string module name or a function the same as transforms.
* plugin(b, opts) is called with the Browserify instance b.
*/
plugin<T extends { basedir?: string }>(plugin: string, opts?: T): BrowserifyObject;
plugin<T extends { basedir?: string }>(plugin: (b: BrowserifyObject, opts: T) => any, opts?: T): BrowserifyObject;
/**
* Reset the pipeline back to a normal state. This function is called automatically when bundle() is called multiple times.
* This function triggers a 'reset' event.
*/
reset(opts?: Options): void;
/**
* When a file is resolved for the bundle, the bundle emits a 'file' event with the full file path, the id string passed to require(), and the parent object used by browser-resolve.
* You could use the file event to implement a file watcher to regenerate bundles when files change.
*/
on(event: 'file', listener: (file: string, id: string, parent: any) => any): BrowserifyObject;
/**
* When a package.json file is read, this event fires with the contents.
* The package directory is available at pkg.__dirname.
*/
on(event: 'package', listener: (pkg: any) => any): BrowserifyObject;
/**
* When .bundle() is called, this event fires with the bundle output stream.
*/
on(event: 'bundle', listener: (bundle: NodeJS.ReadableStream) => any): BrowserifyObject;
/**
* When the .reset() method is called or implicitly called by another call to .bundle(), this event fires.
*/
on(event: 'reset', listener: () => any): BrowserifyObject;
/**
* When a transform is applied to a file, the 'transform' event fires on the bundle stream with the transform stream tr and the file that the transform is being applied to.
*/
on(event: 'transform', listener: (tr: NodeJS.ReadWriteStream, file: string) => any): BrowserifyObject;
on(event: string, listener: Function): BrowserifyObject;
/**
* Set to any until substack/labeled-stream-splicer is defined
*/
pipeline: any;
}
}
declare module "browserify" {
var browserify: Browserify;
var browserify: Browserify.BrowserifyConstructor;
export = browserify;
}
+27
View File
@@ -0,0 +1,27 @@
/// <reference path="./buffer-compare.d.ts" />
/// <reference path="../node/node.d.ts" />
import compare = require('buffer-compare');
let result: number;
result = compare(new Buffer(''), new Buffer(''));
result = compare([], []);
result = compare('', '');
result = compare(new Buffer(''), []);
result = compare([], '');
result = compare('', new Buffer(''));
result = compare<Buffer>(new Buffer(''), new Buffer(''));
result = compare<any[]>([], []);
result = compare<string>('', '');
result = compare<Buffer|any[]>(new Buffer(''), []);
result = compare<any[]|string>([], '');
result = compare<string|Buffer>('', new Buffer(''));
result = compare<Buffer, Buffer>(new Buffer(''), new Buffer(''));
result = compare<any[], any[]>([], []);
result = compare<string, string>('', '');
result = compare<Buffer, any[]>(new Buffer(''), []);
result = compare<any[], string>([], '');
result = compare<string, Buffer>('', new Buffer(''));
+17
View File
@@ -0,0 +1,17 @@
// Type definitions for buffer-compare
// Project: https://github.com/soldair/node-buffer-compare
// Definitions by: Ilya Mochalov <https://github.com/chrootsu>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "buffer-compare" {
interface List {
[index: number]: any;
length: number
}
function compare(cmp: List, to: List): number;
function compare<T>(cmp: T, to: T): number;
function compare<C, T>(cmp: C, to: T): number;
export = compare;
}
+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;
}
+8
View File
@@ -0,0 +1,8 @@
/// <reference path="bytebuffer.d.ts" />
import ByteBuffer = require("bytebuffer");
var bb = new ByteBuffer()
.writeIString("Hello world!")
.flip();
console.log(bb.readIString()+" from bytebuffer.js");
+615
View File
@@ -0,0 +1,615 @@
// Type definitions for bytebuffer.js 5.0.0
// Project: https://github.com/dcodeIO/bytebuffer.js
// Definitions by: Denis Cappellin <http://github.com/cappellin>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Definitions by: SINTEF-9012 <http://github.com/SINTEF-9012>
/// <reference path="../long/long.d.ts" />
declare class ByteBuffer
{
/**
* Constructs a new ByteBuffer.
*/
constructor( capacity?: number, littleEndian?: boolean, noAssert?: boolean );
/**
* Big endian constant that can be used instead of its boolean value. Evaluates to false.
*/
static BIG_ENDIAN: boolean;
/**
* Default initial capacity of 16.
*/
static DEFAULT_CAPACITY: number;
/**
* Default no assertions flag of false.
*/
static DEFAULT_NOASSERT: boolean;
/**
* Little endian constant that can be used instead of its boolean value. Evaluates to true.
*/
static LITTLE_ENDIAN: boolean;
/**
* Maximum number of bytes required to store a 32bit base 128 variable-length integer.
*/
static MAX_VARINT32_BYTES: number;
/**
* Maximum number of bytes required to store a 64bit base 128 variable-length integer.
*/
static MAX_VARINT64_BYTES: number;
/**
* Metrics representing number of bytes.Evaluates to 2.
*/
static METRICS_BYTES: number;
/**
* Metrics representing number of UTF8 characters.Evaluates to 1.
*/
static METRICS_CHARS: number;
/**
* ByteBuffer version.
*/
static VERSION: string;
/**
* Backing buffer.
*/
buffer: ArrayBuffer;
/**
* Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
*/
limit: number;
/**
* Whether to use little endian byte order, defaults to false for big endian.
*/
littleEndian: boolean;
/**
* Marked offset.
*/
markedOffset: number;
/**
* Whether to skip assertions of offsets and values, defaults to false.
*/
noAssert: boolean;
/**
* Absolute read/write offset.
*/
offset: number;
/**
* Data view to manipulate the backing buffer. Becomes null if the backing buffer has a capacity of 0.
*/
view: DataView;
/**
* Allocates a new ByteBuffer backed by a buffer of the specified capacity.
*/
static allocate( capacity?: number, littleEndian?: number, noAssert?: boolean ): ByteBuffer;
/**
* Decodes a base64 encoded string to binary like window.atob does.
*/
static atob( b64: string ): string;
/**
* Encodes a binary string to base64 like window.btoa does.
*/
static btoa( str: string ): string;
/**
* Calculates the number of UTF8 bytes of a string.
*/
static calculateUTF8Byte( str: string ): number;
/**
* Calculates the number of UTF8 characters of a string.JavaScript itself uses UTF- 16, so that a string's length property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
*/
static calculateUTF8Char( str: string ): number;
/**
* Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer.
*/
static calculateVariant32( value: number ): number;
/**
* Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer.
*/
static calculateVariant64( value: number | Long ): number;
/**
* Concatenates multiple ByteBuffers into one.
*/
static concat( buffers: Array<ByteBuffer | ArrayBuffer | Uint8Array | string>, encoding?: string | boolean, litteEndian?: boolean, noAssert?: boolean ): ByteBuffer;
/**
* Decodes a base64 encoded string to a ByteBuffer.
*/
static fromBase64( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer;
/**
* Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
*/
static fromBinary( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer;
/**
* Decodes a hex encoded string with marked offsets to a ByteBuffer.
*/
static fromDebug( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer;
/**
* Decodes a hex encoded string to a ByteBuffer.
*/
static fromHex( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer;
/**
* Decodes an UTF8 encoded string to a ByteBuffer.
*/
static fromUTF8( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer;
/**
* Gets the backing buffer type.
*/
static isByteBuffer( bb: any ): boolean;
/**
* Wraps a buffer or a string. Sets the allocated ByteBuffer's ByteBuffer#offset to 0 and its ByteBuffer#limit to the length of the wrapped data.
* @param buffer Anything that can be wrapped
* @param encoding String encoding if buffer is a string ("base64", "hex", "binary", defaults to "utf8")
* @param littleEndian Whether to use little or big endian byte order. Defaults to ByteBuffer.DEFAULT_ENDIAN.
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteBuffer.DEFAULT_NOASSERT.
*/
static wrap( buffer: ByteBuffer | ArrayBuffer | Uint8Array | string, enc?: string | boolean, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer;
/**
* Decodes a zigzag encoded signed 32bit integer.
*/
static zigZagDecode32( n: number ): number;
/**
* Decodes a zigzag encoded signed 64bit integer.
*/
static zigZagDecode64( n: number | Long ): Long;
/**
* Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding.
*/
static zigZagEncode32( n: number ): number;
/**
* Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding.
*/
static zigZagEncode64( n: number | Long ): Long;
/**
* Switches (to) big endian byte order.
*/
BE( bigEndian?: boolean ): ByteBuffer;
/**
* Switches (to) little endian byte order.
*/
LE( bigEndian?: boolean ): ByteBuffer;
/**
* Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended data's length.
*/
append( source: ByteBuffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer;
/**
* Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents behind the specified offset up to the length of this ByteBuffer's data.
*/
appendTo( target: ByteBuffer, offset?: number ): ByteBuffer;
/**
* Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to disable them if your code already makes sure that everything is valid.
*/
assert( assert: boolean ): ByteBuffer;
/**
* Gets the capacity of this ByteBuffer's backing buffer.
*/
capacity(): number;
/**
* Clears this ByteBuffer's offsets by setting ByteBuffer#offset to 0 and
* ByteBuffer#limit to the backing buffer's capacity. Discards ByteBuffer#markedOffset.
*/
clear(): ByteBuffer;
/**
* Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for ByteBuffer#offset, ByteBuffer#markedOffset and ByteBuffer#limit.
*/
clone( copy?: boolean ): ByteBuffer;
/**
* Compacts this ByteBuffer to be backed by a ByteBuffer#buffer of its contents' length. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will set offset = 0 and limit = capacity and adapt ByteBuffer#markedOffset to the same relative position if set.
*/
compact( begin?: number, end?: number ): ByteBuffer;
/**
* Creates a copy of this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit.
*/
copy( begin?: number, end?: number ): ByteBuffer;
/**
* Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit.
*/
copyTo( target: ByteBuffer, targetOffset?: number, sourceOffset?: number, sourceLimit?: number ): ByteBuffer;
/**
* Makes sure that this ByteBuffer is backed by a ByteBuffer#buffer of at least the specified capacity. If the current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity, the required capacity will be used instead.
*/
ensureCapacity( capacity: number ): ByteBuffer;
/**
* Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit.
*/
fill( value: number | string, begin?: number, end?: number ): ByteBuffer;
/**
* Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets limit = offset and offset = 0. Make sure always to flip a ByteBuffer when all relative read or write operations are complete.
*/
flip(): ByteBuffer;
/**
* Marks an offset on this ByteBuffer to be used later.
*/
mark( offset?: number ): ByteBuffer;
/**
* Sets the byte order.
*/
order( littleEndian: boolean ): ByteBuffer;
/**
* Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly.
*/
prepend( source: ByteBuffer | string | ArrayBuffer, encoding?: string | number, offset?: number ): ByteBuffer;
/**
* Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly.
*/
prependTo( target: ByteBuffer, offset?: number ): ByteBuffer;
/**
* Prints debug information about this ByteBuffer's contents.
*/
printDebug( out?: ( text: string ) => void ): void;
/**
* Reads an 8bit signed integer. This is an alias of ByteBuffer#readInt8.
*/
readByte( offset?: number ): number;
/**
* Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters itself.
*/
readCString( offset?: number ): string;
/**
* Reads a 64bit float. This is an alias of ByteBuffer#readFloat64.
*/
readDouble( offset?: number ): number;
/**
* Reads a 32bit float. This is an alias of ByteBuffer#readFloat32.
*/
readFloat( offset?: number ): number;
/**
* Reads a 32bit float.
*/
readFloat32( offset?: number ): number;
/**
* Reads a 64bit float.
*/
readFloat64( offset?: number ): number;
/**
* Reads a length as uint32 prefixed UTF8 encoded string.
*/
readIString( offset?: number ): string;
/**
* Reads a 32bit signed integer.This is an alias of ByteBuffer#readInt32.
*/
readInt( offset?: number ): number;
/**
* Reads a 16bit signed integer.
*/
readInt16( offset?: number ): number;
/**
* Reads a 32bit signed integer.
*/
readInt32( offset?: number ): number;
/**
* Reads a 64bit signed integer.
*/
readInt64( offset?: number ): Long;
/**
* Reads an 8bit signed integer.
*/
readInt8( offset?: number ): number;
/**
* Reads a 64bit signed integer. This is an alias of ByteBuffer#readInt64.
*/
readLong( offset?: number ): Long;
/**
* Reads a 16bit signed integer. This is an alias of ByteBuffer#readInt16.
*/
readShort( offset?: number ): number;
/**
* Reads an UTF8 encoded string. This is an alias of ByteBuffer#readUTF8String.
*/
readString( length: number, metrics?: number, offset?: number ): string;
/**
* Reads an UTF8 encoded string.
*/
readUTF8String( chars: number, offset?: number ): string;
/**
* Reads a 16bit unsigned integer.
*/
readUint16( offset?: number ): number;
/**
* Reads a 32bit unsigned integer.
*/
readUint32( offset?: number ): number;
/**
* Reads a 64bit unsigned integer.
*/
readUint64( offset?: number ): Long;
/**
* Reads an 8bit unsigned integer.
*/
readUint8( offset?: number ): number;
/**
* Reads a length as varint32 prefixed UTF8 encoded string.
*/
readVString( offset?: number ): string;
/**
* Reads a 32bit base 128 variable-length integer.
*/
readVarint32( offset?: number ): number;
/**
* Reads a zig-zag encoded 32bit base 128 variable-length integer.
*/
readVarint32ZiZag( offset?: number ): number;
/**
* Reads a 64bit base 128 variable-length integer. Requires Long.js.
*/
readVarint64( offset?: number ): Long;
/**
* Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js.
*/
readVarint64ZigZag( offset?: number ): Long;
/**
* Gets the number of remaining readable bytes. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit, so this returns limit - offset.
*/
remaining(): number;
/**
* Resets this ByteBuffer's ByteBuffer#offset. If an offset has been marked through ByteBuffer#mark before, offset will be set to ByteBuffer#markedOffset, which will then be discarded. If no offset has been marked, sets offset = 0.
*/
reset(): ByteBuffer;
/**
* Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that large or larger.
*/
resize( capacity: number ): ByteBuffer;
/**
* Reverses this ByteBuffer's contents
*/
reverse( begin?: number, end?: number ): ByteBuffer;
/**
* Skips the next length bytes. This will just advance
*/
skip( length: number ): ByteBuffer;
/**
* Slices this ByteBuffer by creating a cloned instance with offset = begin and limit = end.
*/
slice( begin?: number, end?: number ): ByteBuffer;
/**
* Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will transparently ByteBuffer#flip this ByteBuffer if offset > limit but the actual offsets remain untouched. This is an alias of ByteBuffer#toBuffer.
*/
toArrayBuffer( forceCopy?: boolean ): ArrayBuffer;
/**
* Encodes this ByteBuffer's contents to a base64 encoded string.
*/
toBase64( begin?: number, end?: number ): string;
/**
* Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
*/
toBinary( begin?: number, end?: number ): string;
/**
* Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will transparently ByteBuffer#flip this ByteBuffer if offset > limit but the actual offsets remain untouched.
*/
toBuffer( forceCopy?: boolean ): ArrayBuffer;
/**
*Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
* < : offset,
* ' : markedOffset,
* > : limit,
* | : offset and limit,
* [ : offset and markedOffset,
* ] : markedOffset and limit,
* ! : offset, markedOffset and limit
*/
toDebug( columns?: boolean ): string | Array<string>
/**
* Encodes this ByteBuffer's contents to a hex encoded string.
*/
toHex( begin?: number, end?: number ): string;
/**
* Converts the ByteBuffer's contents to a string.
*/
toString( encoding?: string ): string;
/**
* Encodes this ByteBuffer's contents between ByteBuffer#offset and ByteBuffer#limit to an UTF8 encoded string.
*/
toUTF8(): string;
/**
* Writes an 8bit signed integer. This is an alias of ByteBuffer#writeInt8.
*/
writeByte( value: number, offset?: number ): ByteBuffer;
/**
* Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL characters itself.
*/
writeCString( str: string, offset?: number ): ByteBuffer;
/**
* Writes a 64bit float. This is an alias of ByteBuffer#writeFloat64.
*/
writeDouble( value: number, offset?: number ): ByteBuffer;
/**
* Writes a 32bit float. This is an alias of ByteBuffer#writeFloat32.
*/
writeFloat( value: number, offset?: number ): ByteBuffer;
/**
* Writes a 32bit float.
*/
writeFloat32( value: number, offset?: number ): ByteBuffer;
/**
* Writes a 64bit float.
*/
writeFloat64( value: number, offset?: number ): ByteBuffer;
/**
* Writes a length as uint32 prefixed UTF8 encoded string.
*/
writeIString( str: string, offset?: number ): ByteBuffer;
/**
* Writes a 32bit signed integer. This is an alias of ByteBuffer#writeInt32.
*/
writeInt( value: number, offset?: number ): ByteBuffer;
/**
* Writes a 16bit signed integer.
*/
writeInt16( value: number, offset?: number ): ByteBuffer;
/**
* Writes a 32bit signed integer.
*/
writeInt32( value: number, offset?: number ): ByteBuffer;
/**
* Writes a 64bit signed integer.
*/
writeInt64( value: number | Long, offset?: number ): ByteBuffer;
/**
* Writes an 8bit signed integer.
*/
writeInt8( value: number, offset?: number ): ByteBuffer;
/**
* Writes a 16bit signed integer. This is an alias of ByteBuffer#writeInt16.
*/
writeShort( value: number, offset?: number ): ByteBuffer;
/**
* Writes an UTF8 encoded string.This is an alias of ByteBuffer#writeUTF8String.
*/
WriteString( str: string, offset?: number ): ByteBuffer | number;
/**
* Writes an UTF8 encoded string.
*/
writeUTF8String( str: string, offset?: number ): ByteBuffer | number;
/**
* Writes a 16bit unsigned integer.
*/
writeUint16( value: number, offset?: number ): ByteBuffer;
/**
* Writes a 32bit unsigned integer.
*/
writeUint32( value: number, offset?: number ): ByteBuffer;
/**
* Writes a 64bit unsigned integer.
*/
writeUint64( value: number | Long, offset?: number ): ByteBuffer;
/**
* Writes an 8bit unsigned integer.
*/
writeUint8( value: number, offset?: number ): ByteBuffer;
/**
* Writes a length as varint32 prefixed UTF8 encoded string.
*/
writeVString( str: string, offset?: number ): ByteBuffer | number;
/**
* Writes a 32bit base 128 variable-length integer.
*/
writeVarint32( value: number, offset?: number ): ByteBuffer | number;
/**
* Writes a zig-zag encoded 32bit base 128 variable-length integer.
*/
writeVarint32ZigZag( value: number, offset?: number ): ByteBuffer | number;
/**
* Writes a 64bit base 128 variable-length integer.
*/
writeVarint64( value: number | Long, offset?: number ): ByteBuffer;
/**
* Writes a zig-zag encoded 64bit base 128 variable-length integer.
*/
writeVarint64ZigZag( value: number | Long, offset?: number ): ByteBuffer | number;
}
declare module 'bytebuffer' {
export = ByteBuffer;
}
+723
View File
@@ -0,0 +1,723 @@
/// <reference path="cal-heatmap.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="../d3/d3.d.ts" />
var cal = new CalHeatMap();
cal.init();
cal.init({});
cal.init({ itemSelector: "div" });
cal.init({ itemSelector: "#id" });
cal.init({ itemSelector: ".class" });
cal.init({ itemSelector: "[title=hi]" });
cal.init({ itemSelector: "div > span + b" });
cal.init({ itemSelector: document.getElementById("myId") });
cal.init({ itemSelector: document.getElementsByClassName(".class")[0] });
cal.init({ itemSelector: document.querySelector(".class") });
cal.init({ itemSelector: $(".class")[0] });
cal.init({ itemSelector: d3.select(".class")[0][0] });
cal.init({
itemSelector: "#domain-a",
domain: "month",
subDomain: "day",
cellSize: 20,
subDomainTextFormat: "%d",
range: 1,
displayLegend: false
});
cal.init({
itemSelector: "#domain-b",
domain: "month",
subDomain: "x_day",
cellSize: 20, subDomainTextFormat: "%d",
range: 1,
displayLegend: false
});
cal.init({
itemSelector: "#cellSize-a",
domain: "day",
range: 1,
displayLegend: false
});
cal.init({
itemSelector: "#cellSize-b",
domain: "day",
range: 1,
cellSize: 15,
displayLegend: false
});
cal.init({
itemSelector: "#cellPadding-a",
domain: "day",
range: 1,
displayLegend: false
});
cal.init({
itemSelector: "#cellPadding-b",
domain: "day",
range: 1,
cellPadding: 5,
displayLegend: false
});
cal.init({
itemSelector: "#cellRadius-a",
cellSize: 15,
domain: "day",
range: 1,
displayLegend: false
});
cal.init({
itemSelector: "#cellRadius-b",
cellSize: 15,
domain: "day",
range: 1,
cellRadius: 10,
displayLegend: false
});
cal.init({
itemSelector: "#domainGutter-a",
domain: "day",
range: 2,
displayLegend: false
});
cal.init({
itemSelector: "#domainGutter-b",
domain: "day",
range: 2,
domainGutter: 10,
displayLegend: false
});
cal.init({
itemSelector: "#domainMargin-a",
domain: "day",
range: 2,
displayLegend: false
});
cal.init({
itemSelector: "#domainMargin-b",
domain: "day",
range: 2,
displayLegend: false,
domainMargin: 10
});
cal.init({
itemSelector: "#domainDynamicDimension-a",
domain: "month",
range: 5,
cellSize: 8,
displayLegend: false,
nextSelector: "#domainDynamicDimension-next",
previousSelector: "#domainDynamicDimension-previous"
});
cal.init({
itemSelector: "#domainDynamicDimension-b",
domain: "month",
range: 5,
cellSize: 8,
displayLegend: false,
domainDynamicDimension: false,
nextSelector: "#domainDynamicDimension-next",
previousSelector: "#domainDynamicDimension-previous",
itemNamespace: "domainDynamicDimension"
});
cal.init({
itemSelector: "#verticalOrientation-a",
domain: "day",
range: 2,
displayLegend: false
});
cal.init({
itemSelector: "#verticalOrientation-b",
domain: "day",
range: 2,
displayLegend: false,
verticalOrientation: true
});
cal.init({
itemSelector: "#label-a",
domain: "day",
range: 2,
displayLegend: false
});
cal.init({
itemSelector: "#label-b",
domain: "day",
range: 2,
displayLegend: false,
label: {
position: "top"
}
});
cal.init({
itemSelector: "#label-c",
domain: "day",
range: 2,
displayLegend: false,
label: {
position: "left",
width: 46
}
});
cal.init({
itemSelector: "#label-d",
domain: "day",
range: 2,
displayLegend: false,
label: {
position: "right",
width: 46,
offset: { x: 10, y: 30 }
}
});
cal.init({
itemSelector: "#label-e",
domain: "day",
range: 2,
displayLegend: false,
label: {
position: "left",
width: 46,
rotate: "left"
}
});
cal.init({
itemSelector: "#label-f",
domain: "day",
range: 2,
displayLegend: false,
label: {
position: "right",
width: 150,
rotate: "left"
}
});
cal.init({
itemSelector: "#label-g",
domain: "day",
range: 2,
displayLegend: false,
label: {
position: "right",
width: 46,
rotate: "left"
}
});
cal.init({
itemSelector: "#label-h",
domain: "day",
range: 2,
displayLegend: false,
label: {
position: "right",
width: 46,
rotate: "right",
align: "right"
}
});
cal.init({
itemSelector: "#colLimit-a",
domain: "day",
range: 1,
displayLegend: false
});
cal.init({
itemSelector: "#colLimit-b",
domain: "day",
colLimit: 24,
range: 1,
displayLegend: false
});
cal.init({
itemSelector: "#rowLimit-a",
domain: "month",
range: 1,
displayLegend: false
});
cal.init({
itemSelector: "#rowLimit-b",
domain: "month",
rowLimit: 10,
range: 1,
displayLegend: false
});
cal.init({
itemSelector: "#tooltip-a",
domain: "month",
range: 1,
displayLegend: false
});
cal.init({
itemSelector: "#tooltip-b",
domain: "month",
range: 1,
displayLegend: false,
tooltip: true
});
cal.init({
itemSelector: "#start-a",
domain: "day",
range: 2,
displayLegend: false
});
cal.init({
itemSelector: "#start-b",
domain: "day",
range: 2,
start: new Date(2000, 0, 15),
displayLegend: false
});
cal.init({
start: new Date(2000, 0), // January, 1st 2000
range: 12,
domain: "year",
subDomain: "month",
data: "http://localhost/api?start={{d:start}}&stop={{d:end}}"
});
cal.init({
data: "http://localhost/datas.csv",
dataType: "csv"
});
var dt = new Date();
dt.setDate(dt.getDate() + 1);
cal.init({
itemSelector: "#highlight-a",
domain: "day",
range: 2,
displayLegend: false,
highlight: ["now", dt]
});
cal.init({
itemSelector: "#weekStartOnMonday-a",
domain: "month",
subDomain: "x_day",
cellSize: 20,
subDomainTextFormat: "%d",
range: 1,
displayLegend: false
});
cal.init({
itemSelector: "#weekStartOnMonday-b",
domain: "month",
subDomain: "x_day",
cellSize: 20,
subDomainTextFormat: "%d",
range: 1,
weekStartOnMonday: false,
displayLegend: false
});
cal.init({
itemSelector: "#minDate-a",
domain: "month",
start: new Date(2000, 4),
minDate: new Date(2000, 1),
maxDate: new Date(2000, 8),
subDomain: "day",
range: 4,
displayLegend: false
});
cal.init({
itemSelector: "#legend-a",
domain: "day",
range: 2
});
cal.init({
itemSelector: "#legend-b",
domain: "day",
range: 2, legend: [-2.5, 0, 2.5]
});
cal.init({
itemSelector: "#displayLegend-a",
domain: "day",
range: 2
});
cal.init({
itemSelector: "#displayLegend-b",
domain: "day",
range: 2,
displayLegend: false
});
cal.init({
itemSelector: "#legendCellSize-a",
domain: "day",
range: 2
});
cal.init({
itemSelector: "#legendCellSize-b",
domain: "day",
range: 2, legendCellSize: 5
});
cal.init({
itemSelector: "#legendCellPadding-a",
domain: "day",
range: 3
});
cal.init({
itemSelector: "#legendCellPadding-b",
domain: "day",
range: 3, legendCellPadding: 5
});
cal.init({
itemSelector: "#legendMargin-a",
domain: "day",
range: 3
});
cal.init({
itemSelector: "#legendMargin-b",
domain: "day",
range: 3,
legendMargin: [50, 0, 0, 50]
});
cal.init({
itemSelector: "#legendVerticalPosition-a",
domain: "day",
range: 2
});
cal.init({
itemSelector: "#legendVerticalPosition-b",
domain: "day",
range: 2,
legendVerticalPosition: "top",
legendMargin: [0, 0, 10, 0]
});
cal.init({
itemSelector: "#legendVerticalPosition-c",
domain: "day",
range: 2,
legendVerticalPosition: "center",
legendMargin: [0, 10, 0, 0]
});
cal.init({
itemSelector: "#legendVerticalPosition-d",
domain: "day",
range: 2,
legendVerticalPosition: "center",
legendHorizontalPosition: "right",
legendMargin: [0, 0, 0, 10]
});
cal.init({
itemSelector: "#legendHorizontalPosition-a",
domain: "day",
range: 3
});
cal.init({
itemSelector: "#legendHorizontalPosition-b",
domain: "day",
range: 3,
legendHorizontalPosition: "right"
});
cal.init({
itemSelector: "#legendOrientation-a",
domain: "day",
range: 3,
legendVerticalPosition: "center",
legendOrientation: "vertical",
legendMargin: [0, 10, 0, 0]
});
cal.init({
itemSelector: "#legendOrientation-b",
domain: "month",
subDomain: "x_day",
range: 3,
verticalOrientation: true,
legendVerticalPosition: "center",
legendHorizontalPosition: "right",
legendOrientation: "vertical",
legendMargin: [0, 0, 0, 20]
});
cal.init({
legendColors: {
min: "#efefef",
max: "steelblue",
empty: "white"
// Will use the CSS for the missing keys
}
});
cal.init({
legendColors: ["#efefef", "steelblue"]
});
cal.init({
itemName: ["cat", "cats"]
});
cal.init({
itemName: "cat"
});
cal.init({
itemName: ["cat"]
});
cal.init({
subDomainDateFormat: function(date: Date): string
{
return date.toString();
}
});
cal.init({
itemSelector: "#subDomainTextFormat-a",
start: new Date(2000, 0, 1, 1),
domain: "month",
subDomain: "x_day",
cellSize: 20,
range: 1,
displayLegend: false,
subDomainTextFormat: "%d"
});
cal.init({
itemSelector: "#subDomainTextFormat-b",
start: new Date(2000, 0, 1, 1),
data: "datas-years.json",
domain: "month",
subDomain: "x_day",
cellSize: 20,
range: 1,
displayLegend: false,
subDomainTextFormat: function(date: Date, value: number): number
{
return value;
}
});
cal.init({
itemSelector: "#domainLabelFormat-a",
domain: "month",
subDomain: "day",
range: 1,
displayLegend: false
});
cal.init({
itemSelector: "#domainLabelFormat-b",
domain: "month",
subDomain: "day",
range: 1,
displayLegend: false,
domainLabelFormat: "%m-%Y"
});
cal.init({
itemSelector: "#legendTitleFormat-a",
domain: "day",
range: 3
});
cal.init({
itemSelector: "#animationDuration-a",
domain: "day",
range: 4,
previousSelector: "#animationDuration-previous",
nextSelector: "#animationDuration-next",
itemNamespace: "animationDuration-a"
});
cal.init({
itemSelector: "#animationDuration-b",
domain: "day",
range: 4, animationDuration: 1500,
previousSelector: "#animationDuration-previous",
nextSelector: "#animationDuration-next",
itemNamespace: "animationDuration-b"
});
cal.init({
itemSelector: "#previousSelector-a",
domain: "day",
range: 4,
previousSelector: "#previousSelector-a-previous",
nextSelector: "#previousSelector-a-next"
});
cal.init({
itemSelector: "#previousSelector-b",
domain: "day",
range: 4,
previousSelector: "#example-previousSelector ul + p > em",
nextSelector: "#example-previousSelector [title=next] li"
});
cal.init({
nextSelector: "#next" // Attach #next onClick event to cal.next()
});
cal.init({
nextSelector: "#next",
// Attach #next.cal onClick event to cal.next()
itemNamespace: "cal"
});
cal.previous();
cal.previous(5);
cal.next();
cal.next(5);
cal.jumpTo(new Date(2000, 4));
cal.jumpTo(new Date(2000, 4), true);
cal.rewind();
var randomData = {};
cal.update(randomData);
cal.update(randomData, () => { }, cal.RESET_ALL_ON_UPDATE);
cal.update(randomData, false, cal.APPEND_ON_UPDATE);
cal.update(randomData, false, cal.RESET_SINGLE_ON_UPDATE);
cal.highlight(new Date(2000, 0, 2));
// Add January 5th to already highlighted dates
cal.options.highlight.push(new Date(2000, 0, 5));
cal.highlight(cal.options.highlight);
var svg: string = cal.getSVG();
cal.options.legendVerticalPosition = "center";
cal.options.legendHorizontalPosition = "right";
cal.options.legendOrientation = "vertical";
cal.setLegend();
cal.removeLegend();
cal.showLegend();
cal = cal.destroy();
cal.init({
itemSelector: "#onClick-a",
domain: "day",
range: 5, data: "datas-years.json",
start: new Date(2000, 0),
onClick: function(date: Date, nb: number)
{
$("#onClick-placeholder").html("You just clicked <br/>on <b>" +
date + "</b> <br/>with <b>" +
(nb === null ? "unknown" : nb) + "</b> items"
);
}
});
cal.init({
itemSelector: "#afterLoad-a",
domain: "day",
range: 5,
afterLoad: function() { },
onComplete: function() { }
});
cal.init({
itemSelector: "#afterLoadPreviousDomain-a",
domain: "day",
range: 5, afterLoadPreviousDomain: function(date: Date) { },
previousSelector: "#afterLoadPreviousDomain-selector"
});
cal.init({
itemSelector: "#afterLoadNextDomain-a",
domain: "day",
range: 5, afterLoadNextDomain: function(date: Date) { },
nextSelector: "#afterLoadNextDomain-selector"
});
cal.init({
itemSelector: "#onComplete-a",
domain: "day",
range: 5,
onComplete: function() { }
});
var datas = [
{ date: 946702811, value: 15 },
{ date: 946702812, value: 25 },
{ date: 946702813, value: 10 }
]
cal.init({
data: datas,
afterLoadData: (data: any) =>
{
var stats: CalHeatMap.DataFormat = {};
for (var d in data)
{
stats[data[d].date] = data[d].value;
}
return stats;
}
});
cal.init({
itemSelector: "#onMinDomainReached-a",
domain: "month",
range: 5,
start: new Date(2000, 4),
minDate: new Date(2000, 3),
maxDate: new Date(2000, 11),
onMinDomainReached: function(hit: boolean) { },
onMaxDomainReached: function(hit: boolean) { },
nextSelector: "#onMinDomainReached-next",
previousSelector: "#onMinDomainReached-previous",
displayLegend: false
});
+514
View File
@@ -0,0 +1,514 @@
// Type definitions for cal-heatmap v3.5.4
// Project: https://github.com/wa0x6e/cal-heatmap
// Definitions by: Chris Baker <https://github.com/RetroChrisB/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../d3/d3.d.ts" />
declare module CalHeatMap
{
interface CalHeatMapStatic
{
new (): CalHeatMap;
}
interface CalHeatMap
{
/**
* Initialise the CalHeatMap with the specified options
* @param {InitOptions} options The CalHeatMap options
*/
init(options?: InitOptions): void;
options: RuntimeOptions;
// Various update mode when using the update() API
/** Reset the whole calendar data before inserting the new data. */
RESET_ALL_ON_UPDATE: number;
/**
* Update only the dates (subDomain) you pass in the data argument, replace their value by the new ones.
* All other dates are leaved untouched.
*/
RESET_SINGLE_ON_UPDATE: number;
/**
* Instead of replacing a date's value by a new one, increment it by the new value. All other dates are leaved untouched.
* That's the one you want to use of you're populating the calendar in realtime!
*/
APPEND_ON_UPDATE: number;
/**
* Shift the calendar n domains back
* @param {number} n The number of domains to shift back. The default is 1.
*/
previous(n?: number): void;
/**
* Shift the calendar n domains forward
* @param {number} n The number of domains to shift forward. The default is 1.
*/
next(n?: number): void;
/**
* Jump the calendar to the specified date
* This method will shift the calendar backward or forward, until the domain containing the specified date is visible.
* @param {Date} date The date to jump to.
* @param {boolean} reset Whether to set the domain with the specified as the calendar's first domain.
*/
jumpTo(date: Date, reset?: boolean): void;
/** Reset the calendar back to the start date */
rewind(): void;
/**
* Update the calendar with new data
* Use update() when you want to refresh the calendar with a new set of data.
* Particularly useful if you're filling the calendar in realtime, or if you want to display a subset of the current data.
* @param {string|Object} data Accept the same format as the data option.
* @param {} afterLoad Whether to execute the afterLoad() callback to convert your data into the json object, expected by cal-heatmap.
* It can also directly takes a function, in case your data can not be converted with the afterLoad() function you defined.
* @param {} updateMode Define how to insert the new data into the calendar.
* Accepted values are:
* Instance.RESET_ALL_ON_UPDATE (default) Reset the whole calendar data before inserting the new data.
* Instance.RESET_SINGLE_ON_UPDATE Update only the dates (subDomain) you pass in the data argument,
* replace their value by the new ones. All other dates are leaved untouched.
* Instance.APPEND_ON_UPDATE Instead of replacing a date's value by a new one, increment it by the new value.
* All other dates are leaved untouched. That's the one you want to use of you're
* populating the calendar in realtime!
*/
update(data: string | Object, afterLoad?: boolean | Function, updateMode?: number): void;
/**
* Change the highlighted dates.
* Takes an array of Date object. Can also accepts the now string, equivalent to Date.now().
* @param {string|Date|Date[]} dates The date or dates to highlight.
*/
highlight(dates: string | Date | Date[]): void;
/**
* Return the SVG source code with the appropriate CSS
* The returned string code is valid and ready to be placed in a .svg file.
* @returns SVG source code with the appropriate CSS.
*/
getSVG(): string;
/**
* Change the legend settings and/or threshold
* When called without arguments, setLegend() will just redraw the legend.
* @param {} legend Same as legend : an array of thresholds
* @param {} legendColor Same as legendColors : an object with the heatmap's colors, or an array of 2 colors
*/
setLegend(legend?: number[], legendColors?: LegendColor | string[]): void;
/**
* Remove the legend from the calendar
* Settings are kept and you can re-add the legend with the same settings using showLegend().
*/
removeLegend(): void;
/** Display the legend, if not already shown. */
showLegend(): void;
/**
* Remove the calendar from the DOM
* Remember to self-assign the result of destroy() to your calendar instance, or it'll lead to a memory leak.
* @param {Function} callback function that will be executed when the calendar is removed from the DOM, at the end of the animation.
* @returns always returns null.
*/
destroy(callback?: Function): CalHeatMap;
}
interface LegendColor
{
/** Color of the smallest value on the legend */
min: string;
/** Color of the highest value on the legend */
max: string;
/** Color for the dates with value == 0 */
empty?: string;
/** Base color of the date cells */
base?: string;
/** Color for the special value */
overflow?: string;
}
interface InitOptions
{
// ================================================
// Presentation
// ================================================
/** DOM node to insert the calendar in. Default: "#cal-heatmap" */
itemSelector?: string | HTMLElement | Element | EventTarget;
/**
* Type of domain. Default: "hour"
* Valid domains: {"hour", "day", "week", "month", "year"}
*/
domain?: string;
/**
* Type of subDomain. Default: "min"
* Valid subDomains: {"min", "x_min", "hour", "x_hour", "day", "x_day", "week", "x_week", "month", "x_month"}
*/
subDomain?: string;
/** Number of domain to display. Default: 12 */
range?: number;
/** Size of each subDomain cell, in pixels. Default: 10 */
cellSize?: number;
/** Space between each subDomain cell, in pixel. Default: 2 */
cellPadding?: number;
/** subDomain cell's border radius, for rounder corner, in pixel. Default: 0 */
cellRadius?: number;
/** Space between each domain, in pixel. Default: 2 */
domainGutter?: number;
/**
* Margin around each domain, in pixel. Default: [0,0,0,0]
* Ordered like in CSS (top, right, bottom, left), it also accepts CSS like values
*/
domainMargin?: number | number[];
/**
* Whether to enable domain dynamic width and height. Default: true
* Some domain>subdomain couple, like month>days, doesn't always have the same number of
* subDomain cells. Some months have 6 weeks, some only 4.
* With dynamic dimension enabled, the domain width and height will be adjusted to fit the
* domain content, whereas when it's disabled, all domains will have the same dimension : the biggest.
*/
domainDynamicDimension?: boolean;
/** To display the calendar vertically, with each domain one under the other. Default: false */
verticalOrientation?: boolean;
/** Position and alignment of the domain label. */
label?: Label;
/**
* Control the number of columns to split the domain dates into. Default: null
* Each domain is split into an arbitrary number of columns (or rows depending on the
* reading direction). You can overwrite that number with colLimit, and force all dates on the
* same line, or split them into more columns.
* That setting limit the maximum number of columns, and doesn't necessary means that each rows will
* contains that number of columns.
*/
colLimit?: number;
/** Control the number of rows to split the domain dates into. Default: null
* If rowLimit and colLimit are both used, rowLimit will be ignored. */
rowLimit?: number;
/** Whether to display a tooltip when hovering over a date. Default: false */
tooltip?: boolean;
// ================================================
// Data
// ================================================
/**
* Starting date of the calendar. Default: new Date()
* It doesn't have to be precise, the calendar will not start at that date, but at the first domain containing that date.
*/
start?: Date;
/**
* Data used to fill the calendar. Default: ""
* String is interpreted as a URL to an API, which should be returning the data used to fill the calendar.
*/
data?: string | Object;
/**
* Engine used to parse the data. Default: json
* Valid values:
* "json" - Interpret the data as json.
* "csv" - Interpret the data as csv.
* "tsv" - Interpret the data exactly like csv, but are delimited with a tab character, instead of comma.
* "txt" - Just return the data as a string.
*/
dataType?: string;
/**
* Highlight selected subDomain cells. Default: false
* Takes an array of Date object. Can also accepts the now string, equivalent to Date.now().
*/
highlight?: string | string[] | Date[] | any[];
/** Whether to start the week on Monday, instead of Sunday. Default: true */
weekStartOnMonday?: boolean;
/**
* Lower limit of the domain navigation, preventing navigating beyond a certain date. Default: null
* When set, calling previous() will only work only until the leftmost domain containing minDate.
* Like with start, minDate does not have to be precise, and just have to be a date inside the domain.
* previous() will always return true, unless the domain containing minDate is reached, in which case, it'll return false.
*/
minDate?: Date;
/** Upper limit of the domain navigation, preventing navigating beyond a certain date. Default: null */
maxDate?: Date;
/**
* Whether to consider missing date:value couple in the data source as equal to 0. Default: false
* By default, when the a date is not associated to a value, it's considered as null, and rendered as a no value cell.
* You should ask yourself, if the API is not returning result for a date, is it because there is really no value
* associated to this date, or because it's supposed to be equal to 0, and it's skipped in order to save bandwidth ?
*/
considerMissingDataAsZero?: boolean;
// ================================================
// Legend
// ================================================
/** Assign each range of values to a color. Default: [10, 20, 30, 40] */
legend?: number[];
/** Whether to display the legend. Default: true */
displayLegend?: boolean;
/** Size of the legend cells, in pixels. Default: 10 */
legendCellSize?: number;
/** Padding between each legend cell, in pixels. Default: 2 */
legendCellPadding?: number;
/** Margin around the legend, in pixels. Default: [10, 0, 0, 0] */
legendMargin?: number | number[];
/**
* Vertical position of the legend. Default: "bottom"
* Valid values:
* "top" - Place the legend above the calendar
* "center" - Place the legend on the calendar's side
* Use with legendHorizontalPosition, to position the legend on the left (default) or on the right.
* "bottom" - Place the legend on below the calendar
*/
legendVerticalPosition?: string;
/**
* Horizontal position of the legend. Default: "left"
* Valid values:
* "left" - Align the legend to the left
* "center" - Center the legend
* "right" - Align the legend to the right
*/
legendHorizontalPosition?: string;
/**
* Orientation of the legend. Default: "horizontal"
* legendOrientation is best used together with legendHorizontalPosition when the legend is positioned on the side.
* Valid values:
* "horizontal" - Legend is displayed horizontally, from left to right
* "vertical" - Legend is displayed vertically, from top to bottom
*/
legendOrientation?: string;
/**
* Set of colors to automagically compute the heatmap colors.
* Instead of relying on the CSS for your heatmap's colors, you can also set the heatmap's colors directly with
* cal-heatmap on initialization, or even dynamically change them after.
* All legend settings can be changed dynamically after calendar initialisation, with setLegend().
*/
legendColors?: LegendColor | string[];
// ================================================
// i18n
// ================================================
/**
* Name of the entity you're representing on the calendar.
* Takes an array of string, with the first index as the singular form, and the second index the plural form.
* For the lazy, you can also pass a simple string, ar a single element array, and it'll automatically guess
* the plural form, as long as it's the singular form plus the "s" suffix.
*/
itemName?: string | string[];
/**
* Format of the title displayed when hovering a subDomain.
* Some template strings are available, and enclosed in braces.
* {name} Name of the entity represented in the calendar (see itemName)
* {count} The value associated to the date.
* {date} The date of the cell. It's automatically formatted according to the type of subDomain.
* See subDomainDateFormat to further customize that date formatting.
* {connector} An English preposition placed before a datetime (on Monday, at 15:00, etc.). Each subDomain
* have their own default connector, corresponding to the default date format.
*/
subDomainTitleFormat?: SubDomainFormatTemplates;
/**
* Format of the {date} template string inside subDomainTitleFormat.
* {date} is by default formatted according to the subDomain type.
* subDomainFormat can accept any string with directive accepted by d3.time.format(), like "%Y-%m-%d".
* As d3.time.format() will only output English dates, subDomainDateFormat can also accept a function,
* with the subDomain date as the argument.
*/
subDomainDateFormat?: string | Function;
/**
* Format of the text inside a subDomain cell.
* Disabled by default, you can display a text inside each subDomain cell.
* Works exactly like subDomainDateFormat, except that the function takes the cell value as second argument.
*/
subDomainTextFormat?: string | Function;
/**
* Format of the domain label.
* Works exactly like subDomainDateFormat, and will format the domain label with any string accepted by d3.time.format(), or a function.
* To not display the domain label, set domainLabelFormat to "" (empty string).
*/
domainLabelFormat?: string | Function;
/**
* Formatting of the legend title, displayed when hovering a legend cell.
* Some template strings are available, and enclosed in braces.
* {name} Name of the entity represented in the calendar (see itemName)
* {min} The first value of the legend array.
* {max} The last value of the legend array.
* {down} The lower bound of a color
* {up} The upper bound of a color
*/
legendTitleFormat?: LegendTitleTemplates;
// ================================================
// Other
// ================================================
/** Animation duration, in milliseconds. Default value: 500 */
animationDuration?: number;
/**
* Will attach the previous() event to the specified element, on a mouse click, shifting the calendar one domain back. Default value: false
* If you want to shift by more than one domain, see the previous() method.
*/
previousSelector?: string | HTMLElement;
/**
* Will attach the next() event to the specified element, on a mouse click, shifting the calendar one domain forward. Default value: false
* If you want to shift by more than one domain, see the next() method.
*/
nextSelector?: string | HTMLElement;
/**
* The calendar instance namespace.
* If you have more than one instance of Cal-Heatmap, you should assign each instance its own namespace, in order to isolate each instance event handler.
*/
itemNamespace?: string;
// ================================================
// Events
// ================================================
/** Called after a mouse click event on a subDomain cell. */
onClick?: (date: Date, value: number) => void;
/** Called after drawing the empty calendar, and before filling it with data. */
afterLoad?: () => void;
/**
* Called after shifting the calendar one domain back.
* The date argument is the start date of the domain that was added.
*/
afterLoadPreviousDomain?: (date: Date) => void;
/**
* Called after shifting the calendar one domain forward.
* The date argument is the start date of the domain that was added.
*/
afterLoadNextDomain?: (date: Date) => void;
/**
* Called after drawing and filling the calendar.
* Useful in case you're loading data via ajax, as it's loading data asynchronously. This event will wait for the ajax
* request to complete before triggering.
* This event will only trigger once, on the initial setup. See afterLoadPreviousDomain and afterLoadNextDomain for
* callback events after a domain navigation.
*/
onComplete?: () => void;
/**
* Called after getting the data from source, but before filling the calendar.
* This callback must return a json object formatted in the expected data format.
* afterLoadData() is used to do some works on the data, especially when the data source is not returning data in the expected format.
*/
afterLoadData?: (data: any) => DataFormat;
/**
* Triggered after previous(), when the incoming domain is containing minDate.
* When the leftmost domain set by minDate is loaded into the calendar, onMinDomainReached() will be triggered with true as argument.
* This event is useful if you want to disable your previous button, since there is no more previous domains to load.
* In order to reverse the action, onMinDomainReached() will be called with false as argument afer next(), only once, and only if the
* leftmost domain is not the lower limit domain anymore.
*/
onMinDomainReached?: (reached: boolean) => void;
/**
* Triggered after next(), when the incoming domain is containing maxDate.
* See onMinDomainReached().
*/
onMaxDomainReached?: (reached: boolean) => void;
}
interface RuntimeOptions extends InitOptions
{
/** Margin around each domain, in pixels. Ordered like in CSS (top, right, bottom, left) */
domainMargin: number[];
/** Margin around the legend, in pixels. Ordered like in CSS (top, right, bottom, left) */
legendMargin: number[];
/** List of dates to highlight */
highlight: Date[];
/**
* Name of the items to represent in the calendar.
* First index is singular form, and the second index, the plural form.
*/
itemName: string[];
}
interface LegendTitleTemplates
{
/** Formatting of the smallest (leftmost) value of the legend. Default value: "less than {min} {name}" */
lower?: string;
/** Formatting of all the value but the first and the last. Default value: "between {down} and {up} {name}" */
inner?: string;
/** Formatting of the biggest (rightmost) value of the legend. Default value: "more than {max} {name}" */
upper?: string;
}
interface SubDomainFormatTemplates
{
/** Format of the title when there is no value associated to the date. Default value: "{date}" */
empty?: string;
/** Format of the title when it's associated to a value. Default value: "{count} {name} {connector} {date}" */
filled?: string;
}
interface DataFormat
{
/** timestamp are in seconds, value can be any number (integer or float) */
[timestamp: string]: number;
}
interface LabelOffset
{
x: number;
y: number;
}
/** Position and alignment of the domain label. */
interface Label
{
/**
* Position of the label, relative to the domain. Default: "bottom"
* Valid values: {"top", "right", "bottom", "left"}
*/
position?: string;
/**
* Horizontal align of the domain. Default: "center"
* Valid values: {"left", "center", "right"}
*/
align?: string;
/**
* Rotation for a vertical label. Default: null
* Valid values: {null, "left", "right"}
*/
rotate?: string;
/**
* Only used when label is rotated, defines the width of the label. Default: 100
* Valid values: any intger
*/
width?: number;
/**
* More control about label positioning, if the default value does not fit your need,
* especially when label is rotated, or when using a big font-size. Default: {x:0, y:0}
*/
offset?: LabelOffset;
/**
* Height of the domain label in pixels.
* By leaving it to null, the label will be set to 2 times the height of the subDomain cell.
* If you want to remove the label, set domainLabelFormat to "" (empty string), instead
* of setting the label height to 0. Default: null
* Valid values: any integer
*/
height?: number;
}
}
declare var CalHeatMap: CalHeatMap.CalHeatMapStatic;
+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 {
+30 -1
View File
@@ -325,7 +325,7 @@ var myDoughnutChart = new Chart(ctx).Doughnut(pieData, {
animateRotate: true,
animateScale: false,
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
});
});
var myDoughnutChartLegend: string = myDoughnutChart.generateLegend();
var myDoughnutChartImage: string = myDoughnutChart.toBase64Image();
@@ -341,3 +341,32 @@ myDoughnutChart.resize();
myDoughnutChart.update();
myDoughnutChart.stop();
myDoughnutChart.destroy();
// Test using charts with overrides of a subset of global options
var partialOpts: ChartSettings = {
showTooltips: true,
tooltipEvents: ["mousemove", "touchstart", "touchmove"],
tooltipFillColor: "rgba(0,0,0,0.8)",
tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
tooltipFontSize: 14,
tooltipFontStyle: "normal",
tooltipFontColor: "#fff",
tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
tooltipTitleFontSize: 14,
tooltipTitleFontStyle: "bold",
tooltipTitleFontColor: "#fff",
tooltipYPadding: 6,
tooltipXPadding: 6,
tooltipCaretSize: 8,
tooltipCornerRadius: 6,
tooltipXOffset: 10,
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>"
};
var my2ndLineChart = new Chart(ctx).Line(lineData, partialOpts);
var my2ndBarChart = new Chart(ctx).Bar(barData, partialOpts);
var my2ndRadarChart = new Chart(ctx).Radar(radarData, partialOpts);
var my2ndPolarAreaChart = new Chart(ctx).PolarArea(polarAreaData, partialOpts);
var my2ndPieChart = new Chart(ctx).Pie(pieData, partialOpts);
var my2ndDoughnutChart = new Chart(ctx).Doughnut(pieData, partialOpts);
+44 -44
View File
@@ -33,49 +33,49 @@ interface CircularChartData {
}
interface ChartSettings {
animation: boolean;
animationSteps: number;
animationEasing: string;
showScale: boolean;
scaleOverride: boolean;
scaleSteps: number;
scaleStepWidth: number;
scaleStartValue: number;
scaleLineColor: string;
scaleLineWidth: number;
scaleShowLabels: boolean;
scaleLabel: string;
scaleIntegersOnly: boolean;
scaleBeginAtZero: boolean;
scaleFontFamily: string;
scaleFontSize: number;
scaleFontStyle: string;
scaleFontColor: string;
responsive: boolean;
maintainAspectRatio: boolean;
showTooltips: boolean;
tooltipEvents: string[];
tooltipFillColor: string;
tooltipFontFamily: string;
tooltipFontSize: number;
tooltipFontStyle: string;
tooltipFontColor: string;
tooltipTitleFontFamily: string;
tooltipTitleFontSize: number;
tooltipTitleFontStyle: string;
tooltipTitleFontColor: string;
tooltipYPadding: number;
tooltipXPadding: number;
tooltipCaretSize: number;
tooltipCornerRadius: number;
tooltipXOffset: number;
tooltipTemplate: string;
multiTooltipTemplate: string;
onAnimationProgress: () => any;
onAnimationComplete: () => any;
animation?: boolean;
animationSteps?: number;
animationEasing?: string;
showScale?: boolean;
scaleOverride?: boolean;
scaleSteps?: number;
scaleStepWidth?: number;
scaleStartValue?: number;
scaleLineColor?: string;
scaleLineWidth?: number;
scaleShowLabels?: boolean;
scaleLabel?: string;
scaleIntegersOnly?: boolean;
scaleBeginAtZero?: boolean;
scaleFontFamily?: string;
scaleFontSize?: number;
scaleFontStyle?: string;
scaleFontColor?: string;
responsive?: boolean;
maintainAspectRatio?: boolean;
showTooltips?: boolean;
tooltipEvents?: string[];
tooltipFillColor?: string;
tooltipFontFamily?: string;
tooltipFontSize?: number;
tooltipFontStyle?: string;
tooltipFontColor?: string;
tooltipTitleFontFamily?: string;
tooltipTitleFontSize?: number;
tooltipTitleFontStyle?: string;
tooltipTitleFontColor?: string;
tooltipYPadding?: number;
tooltipXPadding?: number;
tooltipCaretSize?: number;
tooltipCornerRadius?: number;
tooltipXOffset?: number;
tooltipTemplate?: string;
multiTooltipTemplate?: string;
onAnimationProgress?: () => any;
onAnimationComplete?: () => any;
}
interface ChartOptions {
interface ChartOptions extends ChartSettings {
scaleShowGridLines?: boolean;
scaleGridLineColor?: string;
scaleGridLineWidth?: number;
@@ -138,7 +138,7 @@ interface BarChartOptions extends ChartOptions {
barDatasetSpacing?: number;
}
interface RadarChartOptions {
interface RadarChartOptions extends ChartSettings {
scaleShowLine?: boolean;
angleShowLineOut?: boolean;
scaleShowLabels?: boolean;
@@ -159,7 +159,7 @@ interface RadarChartOptions {
legendTemplate?: string;
}
interface PolarAreaChartOptions {
interface PolarAreaChartOptions extends ChartSettings {
scaleShowLabelBackdrop?: boolean;
scaleBackdropColor?: string;
scaleBeginAtZero?: boolean;
@@ -176,7 +176,7 @@ interface PolarAreaChartOptions {
legendTemplate?: string;
}
interface PieChartOptions {
interface PieChartOptions extends ChartSettings {
segmentShowStroke?: boolean;
segmentStrokeColor?: string;
segmentStrokeWidth?: number;
+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;
});
+30 -29
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'/>
@@ -5689,7 +5689,7 @@ declare module chrome.runtime {
* URL to be opened after the extension is uninstalled. This URL must have an http: or https: scheme. Set an empty string to not open a new tab upon uninstallation.
* @param callback Called when the uninstall URL is set. If the given URL is invalid, runtime.lastError will be set.
*/
export function setUninstallUrl(url: string, callback?: () => void): void;
export function setUninstallURL(url: string, callback?: () => void): void;
/**
* Open your Extension's options page, if possible.
* The precise behavior may depend on your manifest's options_ui or options_page key, or what Chrome happens to support at the time. For example, the page may be opened in a new tab, within chrome://extensions, within an App, or it may just focus an open options page. It will never cause the caller page to reload.
@@ -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;
}
////////////////////
+9 -1
View File
@@ -1139,4 +1139,12 @@ declare module CKEDITOR {
function isTabEnabled(editor: editor, dialogName: string, tabName: string): boolean;
function okButton(): void;
}
}
module lang {
var languages: any;
var rtl: any;
function load(languageCode: string, defaultLanguage: string, callback: Function): void;
function detect(defaultLanguage: string, probeLanguage: string): string;
}
}
-2
View File
@@ -41,9 +41,7 @@ declare module CodeMirror {
off(eventName: string, handler: (doc: CodeMirror.Doc, event: any) => void): void;
}
/** Extend CodeMirror.Doc with a state object, so that the Doc.state.completionActive property is reachable*/
interface Doc {
state: any;
showHint: (options: ShowHintOptions) => void;
}
+5
View File
@@ -390,6 +390,9 @@ declare module CodeMirror {
The handler may mess with the style of the resulting element, or add event handlers, but should not try to change the state of the editor. */
on(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void;
off(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void;
/** Expose the state object, so that the Editor.state.completionActive property is reachable*/
state: any;
}
interface EditorFromTextArea extends Editor {
@@ -589,6 +592,8 @@ declare module CodeMirror {
/** The reverse of posFromIndex. */
indexFromPos(object: CodeMirror.Position): number;
/** Expose the state object, so that the Doc.state.completionActive property is reachable*/
state: any;
}
interface LineHandle {
+44
View File
@@ -0,0 +1,44 @@
/// <reference path="./complex.d.ts" />
import Complex from 'complex';
var z: Complex = new Complex(2, 3);
var z: Complex = Complex.from(2, 3);
var z: Complex = Complex.from(2, 4);
var z: Complex = Complex.from(5);
var z: Complex = Complex.from('2+5i');
var z: Complex = Complex.fromPolar(3, Math.PI);
var z: Complex = Complex.i;
var z: Complex = Complex.one;
var z: Complex = z.fromRect(2, 3);
var z: Complex = z.fromPolar(3, Math.PI);
var z: Complex = z.toPrecision(3);
var z: Complex = z.toFixed(3);
var z: Complex = z.finalize();
var x: number = z.magnitude();
var x: number = z.abs();
var x: number = z.angle();
var x: number = z.arg();
var x: number = z.phase();
var z: Complex = z.conjugate();
var z: Complex = z.negate();
var z: Complex = z.multiply(z);
var z: Complex = z.mult(3);
var z: Complex = z.divide(z);
var z: Complex = z.div(3);
var z: Complex = z.add(z);
var z: Complex = z.subtract(z);
var z: Complex = z.sub(3);
var z: Complex = z.pow(z);
var z: Complex = z.sqrt();
var z: Complex = z.log(2);
var z: Complex = z.exp();
var z: Complex = z.sin();
var z: Complex = z.cos();
var z: Complex = z.tan();
var z: Complex = z.sinh();
var z: Complex = z.cosh();
var z: Complex = z.tanh();
var z: Complex = z.clone();
var s: string = z.toString();
var b: boolean = z.equals(z);
+238
View File
@@ -0,0 +1,238 @@
// Type definitions for Complex 3.0.1
// Project: https://github.com/arian/Complex
// Definitions by: Aya Morisawa <https://github.com/AyaMorisawa>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'complex' {
export default class Complex {
/**
* @param real The real part of the number
* @param im The imaginary part of the number
*/
constructor(real: number, im: number);
/**
* A in line function like Number.from.
*
* Examples:
* var z = Complex.from(2, 4);
* var z = Complex.from(5);
* var z = Complex.from('2+5i');
*
* @param real A string representation of the number, for example 1+4i
*/
static from(real: string): Complex;
/**
* A in line function like Number.from.
* @param real The real part of the number
* @param im The imaginary part of the number
*/
static from(real: number, im?: number): Complex;
/**
* Creates a complex instance from a polar representation
* @param r The radius/magnitude of the number
* @param phi The angle/phase of the number
*/
static fromPolar(r: number, phi: number): Complex;
/**
* A instance of the imaginary unit
*/
static i: Complex;
/**
* A instance for the real number
*/
static one: Complex;
/**
* Set the real and imaginary properties a and b from a + bi.
* @param real The real part of the number
* @param im The imaginary part of the number
*/
fromRect(real: number, im: number): Complex;
/**
* Set the a and b in a + bi from a polar representation.
* @param r The radius/magnitude of the number
* @param phi The angle/phase of the number
*/
fromPolar(r: number, phi: number): Complex;
/**
* Set the precision of the numbers. Similar to Number.prototype.toPrecision. Useful before printing the number with the toString method.
* @param k An integer specifying the number of significant digits
*/
toPrecision(k: number): Complex;
/**
* Format a number using fixed-point notation. Similar to Number.prototype.toFixed. Useful before printing the number with the toString method.
* @param k The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.
*/
toFixed(k: number): Complex;
/**
* Finalize the instance. The number will not change and any other method call will return a new instance. Very useful when a complex instance should stay constant. For example the Complex.i variable is a finalized instance.
*/
finalize(): Complex;
/**
* Calculate the magnitude of the complex number
*/
magnitude(): number;
/**
* Alias for magnitude(). Calculate the magnitude of the complex number.
*/
abs(): number;
/**
* Calculate the angle with respect to the real axis, in radians.
*/
angle(): number;
/**
* Alias for angle(). Calculate the angle with respect to the real axis, in radians.
*/
arg(): number;
/**
* Alias for angle(). Calculate the angle with respect to the real axis, in radians.
*/
phase(): number;
/**
* Calculate the conjugate of the complex number (multiplies the imaginary part with -1)
*/
conjugate(): Complex;
/**
* Negate the number (multiplies both the real and imaginary part with -1)
*/
negate(): Complex;
/**
* Multiply the number with a real or complex number
* @param z The number to multiply with
*/
multiply(z: number | Complex): Complex;
/**
* Alias for multiply(). Multiply the number with a real or complex number
* @param z The number to multiply with
*/
mult(z: number | Complex): Complex;
/**
* Divide the number by a real or complex number
* @param z The number to divide by
*/
divide(z: number | Complex): Complex;
/**
* Alias for divide(). Divide the number by a real or complex number
* @param z The number to divide by
*/
div(z: number | Complex): Complex;
/**
* Add a real or complex number
* @param z The number to add
*/
add(z: number | Complex): Complex;
/**
* Subtract a real or complex number
* @param z The number to subtract
*/
subtract(z: number | Complex): Complex;
/**
* Alias for subtract(). Subtract a real or complex number
* @param z The number to subtract
*/
sub(z: number | Complex): Complex;
/**
* Return the base to the exponent
* @param z The exponent
*/
pow(z: number | Complex): Complex;
/**
* Return the square root
*/
sqrt(): Complex;
/**
* Return the natural logarithm (base E)
* @param k The actual answer has a multiplicity (ln(z) = ln|z| + arg(z)) where arg(z) can return the same for different angles (every 2*pi), with this argument you can define which answer is required
*/
log(k?: number): Complex;
/**
* Calculate the e^z where the base is E and the exponential the complex number.
*/
exp(): Complex;
/**
* Calculate the sine of the complex number
*/
sin(): Complex;
/**
* Calculate the cosine of the complex number
*/
cos(): Complex;
/**
* Calculate the tangent of the complex number
*/
tan(): Complex;
/**
* Calculate the hyperbolic sine of the complex number
*/
sinh(): Complex
/**
* Calculate the hyperbolic cosine of the complex number
*/
cosh(): Complex
/**
* Calculate the hyperbolic tangent of the complex number
*/
tanh(): Complex
/**
* Return a new Complex instance with the same real and imaginary properties
*/
clone(): Complex;
/**
* Return a string representation of the complex number
*
* Examples:
* new Complex(1, 2).toString(); // 1+2i
* new Complex(0, 1).toString(); // i
* new Complex(4, 0).toString(); // 4
* new Complex(1, 1).toString(); // 1+i
* 'my Complex Number is: ' + (new Complex(3, 5)); // 'my Complex Number is: 3+5i
*/
toString(): string;
/**
* Check if the real and imaginary components are equal to the passed in compelex components.
*
* Examples:
* new Complex(1, 4).equals(new Complex(1, 4)); // true
* new Complex(1, 4).equals(new Complex(1, 3)); // false
*
* @param z The complex number to compare with
*/
equals(z: number | Complex): boolean;
}
}
@@ -0,0 +1,21 @@
/// <reference path="compose-function.d.ts" />
const numberToNumber = (a: number): number => a + 2;
const numberToString = (a: number): string => "foo";
const stringToNumber = (a: string): number => 5;
import composeFunction = require("compose-function");
const t1: number = composeFunction(numberToNumber, numberToNumber)(5);
const t2: string = composeFunction(numberToString, numberToNumber)(5);
const t3: string = composeFunction(numberToString, stringToNumber)("f");
const t4: (a: string) => number = composeFunction(
(f: (a: string) => number) => ((p: string) => 5),
(f: (a: number) => string) => ((p: string) => 4)
)(numberToString);
const t5: number = composeFunction(stringToNumber, numberToString, numberToNumber)(5);
const t6: string = composeFunction(numberToString, stringToNumber, numberToString, numberToNumber)(5);
const t7: string = composeFunction<string>(
numberToString, numberToNumber, stringToNumber, numberToString, stringToNumber)("fo");
+31
View File
@@ -0,0 +1,31 @@
// Type definitions for compose-function
// Project: https://github.com/stoeffel/compose-function
// Definitions by: Denis Sokolov <https://github.com/denis-sokolov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "compose-function" {
// Hardcoded signatures for 2-4 parameters
function f<A, B, C>(
f1: (b: B) => C,
f2: (a: A) => B
): (a: A) => C
function f<A, B, C, D>(
f1: (b: C) => D,
f2: (a: B) => C,
f3: (a: A) => B
): (a: A) => D
function f<A, B, C, D, E>(
f1: (b: D) => E,
f2: (a: C) => D,
f3: (a: B) => C,
f4: (a: A) => B
): (a: A) => E
// Minimal typing for more than 4 parameters
function f<Result>(
f1: (a: any) => Result,
...functions: Function[]
): (a: any) => Result
export = f;
}
+28
View File
@@ -0,0 +1,28 @@
/// <reference path="connect-timeout.d.ts" />
/// <reference path="../body-parser/body-parser.d.ts" />
/// <reference path="../cookie-parser/cookie-parser.d.ts" />
/// <reference path="../express/express.d.ts" />
import express = require("express");
import timeout = require("connect-timeout");
import bodyParser = require("body-parser");
import cookieParser = require("cookie-parser");
// example of using this top-level; note the use of haltOnTimedout
// after every middleware; it will stop the request flow on a timeout
var app = express();
app.use(timeout("5s", { respond: false }));
app.use(bodyParser());
app.use(haltOnTimedout);
app.use(cookieParser());
app.use(haltOnTimedout);
// Add your routes here, etc.
function haltOnTimedout(req: express.Request, res: express.Response, next: Function) {
if (!req.timedout) {
next();
}
}
app.listen(3000);
+36
View File
@@ -0,0 +1,36 @@
// Type definitions for connect-timeout
// Project: https://github.com/expressjs/timeout
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module Express {
export interface Request {
/**
* @summary Clears the timeout on the request.
*/
clearTimeout(): void;
/**
*
* @return {boolean} true if timeout fired; false otherwise.
*/
timedout(event: string, message: string): boolean;
}
}
declare module "connect-timeout" {
import express = require("express");
interface TimeoutOptions extends Object {
/**
* @summary Controls if this module will "respond" in the form of forwarding an error.
* @type {boolean}
*/
respond: boolean;
}
function timeout(timeout: string, options?: TimeoutOptions): express.RequestHandler;
export = timeout;
}
@@ -0,0 +1,10 @@
/// <reference path="cordova-plugin-spinner.d.ts" />
SpinnerPlugin.activityStart();
SpinnerPlugin.activityStart("a");
SpinnerPlugin.activityStart("a", () => {});
SpinnerPlugin.activityStart("a", () => {}, () => {});
SpinnerPlugin.activityStop();
SpinnerPlugin.activityStop(() => {});
SpinnerPlugin.activityStop(() => {}, () => {});
+31
View File
@@ -0,0 +1,31 @@
// Type definitions for cordova-plugin-spinner 1.0.0
// Project: https://github.com/Justin-Credible/cordova-plugin-spinner
// Definitions by: Justin Unterreiner <https://github.com/Justin-Credible>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module SpinnerPlugin {
interface SpinnerPluginStatic {
/**
* Blocks user input using an indeterminate spinner.
*
* An optional label can be shown below the spinner.
*
* @param labelText The optional value to show in a label.
* @param successCallback The success callback for this asynchronous function.
* @param failureCallback The failure callback for this asynchronous function; receives an error string.
*/
activityStart(labelText?: string, successCallback?: () => void, failureCallback?: (error: string) => void): void;
/**
* Allows user input by hiding the indeterminate spinner.
*
* @param successCallback The success callback for this asynchronous function.
* @param failureCallback The failure callback for this asynchronous function; receives an error string.
*/
activityStop(successCallback?: () => void, failureCallback?: (error: string) => void): void;
}
}
declare var SpinnerPlugin: SpinnerPlugin.SpinnerPluginStatic;
+4 -1
View File
@@ -26,6 +26,9 @@ interface Device {
version: string;
/** Get the device's manufacturer. */
manufacturer: string;
}
/** Whether the device is running on a simulator. */
isVirtual: boolean;
/** Get the device hardware serial number. */
serial: string;}
declare var device: Device;
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
+2 -2
View File
@@ -38,7 +38,7 @@ declare class Dexie {
static deepClone(obj: Object): Object;
version(versionNumber: number): Dexie.Version
version(versionNumber: number): Dexie.Version;
on: {
(eventName: string, subscriber: () => any): void;
@@ -48,7 +48,7 @@ declare class Dexie {
populate: Dexie.DexieEvent;
blocked: Dexie.DexieEvent;
versionchange: Dexie.DexieVersionChangeEvent;
}
};
open(): Dexie.Promise<void>;
+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);
+3 -1
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;
}
@@ -825,7 +827,7 @@ declare module createjs {
timeSlice: number;
// methods
addAnimation(name: string, frames: number[], next?: string, frequency?: number): void;
addAnimation(name: string, frames: number[], next?: string|boolean, frequency?: number): void;
addFrame(source: DisplayObject, sourceRect?: Rectangle, scale?: number, setupFunction?: () => any, setupData?: Object): number;
addMovieClip(source: MovieClip, sourceRect?: Rectangle, scale?: number, setupFunction?: () => any, setupData?: Object, labelFunction?: () => any): void;
build(): SpriteSheet;
+26
View File
@@ -0,0 +1,26 @@
///<reference path="email-templates.d.ts"/>
import EmailTemplates = require('email-templates');
var EmailTemplate = EmailTemplates.EmailTemplate;
var template = new EmailTemplate("./");
var users = [
{
email: 'pappa.pizza@spaghetti.com',
name: {
first: 'Pappa',
last: 'Pizza'
}
},
{
email: 'mister.geppetto@spaghetti.com',
name: {
first: 'Mister',
last: 'Geppetto'
}
}
]
var templates = users.map(function(user) {
return template.render(user);
})
+54
View File
@@ -0,0 +1,54 @@
// Type definitions for node-email-templates
// Project: https://github.com/niftylettuce/node-email-templates
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* @summary Interface for result of email template.
* @interface
*/
interface EmailTemplateResults {
/**
* @summary HTML result.
* @type {string}
*/
html: string;
/**
* @summary Text result.
* @type {string}
*/
text: string;
}
/**
* @summary Interface for callback of email callback.
* @interface
*/
interface EmailTemplateCallback {
/**
* @summary Callback signature.
*/
(err: Object, results: EmailTemplateResults): void;
}
declare module "email-templates" {
/**
* @summary Email template class.
* @class
*/
export class EmailTemplate {
/**
* @summary Constructor.
* @param {string} templateDir The template directory.
*/
constructor(templateDir: string);
/**
* @summary Render a single template.
* @param {EmailTemplateCallback|Object} locals The variables or callback function.
* @param {EmailTemplateCallback} callback The callback function.
*/
render(locals: EmailTemplateCallback|Object, callback?: EmailTemplateCallback): void;
}
}
+13
View File
@@ -0,0 +1,13 @@
/// <reference path="email-validator.d.ts" />
import emailValidator = require('email-validator');
import { validate } from 'email-validator';
var result: boolean;
// Trivial code requires trivial tests
result = validate('some email');
result = validate(null);
result = emailValidator.validate('some email');
result = emailValidator.validate(null);
+8
View File
@@ -0,0 +1,8 @@
// Type definitions for email-validator 1.0.3
// Project: https://github.com/Sembiance/email-validator
// Definitions by: Paul Lessing <https://github.com/paullessing>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "email-validator" {
export function validate(email: String): boolean;
}
+4 -2
View File
@@ -3,12 +3,14 @@
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "envify" {
var envify: Function;
var envify: (file: string, environment: { [name: string]: any }) => NodeJS.ReadWriteStream;
export = envify;
}
declare module "envify/custom" {
function envify(environment: { [name: string]: any }): Function;
function envify(environment: { [name: string]: any }): (file: string, environment: { [name: string]: any }) => NodeJS.ReadWriteStream;
export = envify;
}
@@ -0,0 +1,27 @@
/// <reference path="../express-brute/express-brute.d.ts"/>
/// <reference path="../mongodb/mongodb.d.ts"/>
/// <reference path="express-brute-mongo.d.ts"/>
import express = require("express");
import ExpressBrute = require("express-brute");
import MongoStore = require("express-brute-mongo");
import mongodb = require("mongodb");
var MongoClient = mongodb.MongoClient;
var store = new MongoStore(ready => {
MongoClient.connect("mongodb://127.0.0.1:27017/test", (err, db) => {
if (err) {
throw err;
}
var collection = db.collection("bruteforce-store");
ready(collection);
});
});
var app = express();
var bruteforce = new ExpressBrute(store);
app.post("/auth", bruteforce.prevent, (req, res, next) => {
res.send("Success!");
});
+22
View File
@@ -0,0 +1,22 @@
// Type definitions for express-brute-mongo
// Project: https://github.com/auth0/express-brute-mongo
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module "express-brute-mongo" {
/**
* @summary MongoDB store adapter.
* @class
*/
export = class MongoStore {
/**
* @summary Constructor.
* @constructor
* @param {Function} getCollection The collection.
* @param {Object} options The otpions.
*/
constructor(getCollection: (collection: any) => void, options?: Object);
}
}
+16
View File
@@ -0,0 +1,16 @@
/// <reference path="express-brute.d.ts"/>
import express = require("express");
import ExpressBrute = require("express-brute");
var store = new ExpressBrute.MemoryStore();
store = new ExpressBrute.MemoryStore({ prefix: "prefix" });
store.set("key", "value", 0, (error: any) => { });
store.get("key", (error: any, data: Object) => { });
store.reset("key", (error: any) => { });
var app = express();
var bruteforce = new ExpressBrute(store);
app.post("/auth", bruteforce.prevent, (req, res, next) => {
res.send("Success!");
});
+129
View File
@@ -0,0 +1,129 @@
// Type definitions for express-brute
// Project: https://github.com/AdamPflug/express-brute
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module "express-brute" {
import express = require("express");
/**
* @summary Options for {@link MemoryStore} class.
* @interface
*/
interface MemoryStoreOptions {
/**
* @summary Key prefix.
* @type {string}
*/
prefix: string;
}
/**
* @summary Options for {@link ExpressBrute#getMiddleware} class.
* @interface
*/
interface ExpressBruteMiddleware {
/**
* @summary Allows you to override the value of failCallback for this middleware.
* @type {Function}
*/
failCallback: Function;
/**
* @summary Disregard IP address when matching requests if set to true. Defaults to false.
* @type {boolean}
*/
ignoreIP: boolean;
/**
* @summary Key.
* @type {any}
*/
key: any;
}
/**
* @summary Middleware.
* @class
*/
class ExpressBrute {
/**
* @summary Constructor.
* @constructor
* @param {any} store The store.
*/
constructor(store: any);
/**
* @summary Generates middleware that will bounce requests with the same key and IP address that happen faster than the current wait time by calling failCallback.
* @param {Object} options The options.
*/
getMiddleware(options: ExpressBruteMiddleware): express.RequestHandler;
/**
* @summary Uses the current proxy trust settings to get the current IP from a request object.
* @param {Request} request The HTTP request.
* @return {RequestHandler} The Request handler.
*/
getIPFromRequest(request: express.Request): express.RequestHandler;
/**
* @summary Middleware that will bounce requests that happen faster than the current wait time by calling failCallback.
* @param {Request} request The HTTP request.
* @param {Response} response The HTTP response.
* @param {Function} next The next middleware.
* @return {RequestHandler} The Request handler.
*/
prevent(request: express.Request, response: express.Response, next: Function): express.RequestHandler;
/**
* @summary Resets the wait time between requests back to its initial value.
* @param {string} ip The IP address.
* @param {string} key The key. response.
* @param {Function} next The next middleware.
* @return {RequestHandler} The Request handler.
*/
reset(ip: string, key: string, next: Function): express.RequestHandler;
}
module ExpressBrute {
/**
* @summary In-memory store.
* @class
*/
export class MemoryStore {
/**
* @summary Constructor.
* @constructor
* @param {Object} options The options.
*/
constructor(options?: MemoryStoreOptions);
/**
* @summary Gets key value.
* @param {string} key The key name.
* @param {Function} callbck The callback.
*/
get(key: string, callback: (error: any, data: Object) => void): void;
/**
* @summary Sets the key value.
* @param {string} key The name.
* @param {string} value The value.
* @param {number} lifetime The lifetime.
* @param {Function} callback The callback.
*/
set(key: string, value: any, lifetime: number, callback: (error: any) => void): void;
/**
* @summary Deletes the key.
* @param {string} key The name.
* @param {Function} callback The callback.
*/
reset(key: string, callback: (error: any) => void): void;
}
}
export = ExpressBrute;
}
+1 -1
View File
@@ -21,7 +21,7 @@ interface ExphbsOptions {
handlebars?: any;
extname?: string;
layoutsDir?: string;
partialsDir?: string;
partialsDir?: any;
defaultLayout?: string;
helpers?: any;
compilerOptions?: any;
+2
View File
@@ -66,12 +66,14 @@ declare module ExpressValidator {
* Accepts http, https, ftp
*/
isUrl(): Validator;
/**
* Combines isIPv4 and isIPv6
*/
isIP(): Validator;
isIPv4(): Validator;
isIPv6(): Validator;
isMACAddress(): Validator;
isAlpha(): Validator;
isAlphanumeric(): Validator;
isNumeric(): Validator;
+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.
*/
@@ -0,0 +1,39 @@
/// <reference path="./fixed-data-table-0.4.7.d.ts"" />
/// <reference path="../react/react.d.ts"/>
/// <reference path="../react/react-dom.d.ts"/>
import * as React from "react";
import * as ReactDOM from "react-dom";
import * as FixedDataTable from "fixed-data-table";
var rows = [
['a1', 'b1', 'c1'],
['a2', 'b2', 'c2'],
['a3', 'b3', 'c3'],
// .... and more
];
function rowGetter(rowIndex: number) {
return rows[rowIndex];
}
var table = <FixedDataTable.Table
rowHeight={50}
rowGetter={rowGetter}
rowsCount={rows.length}
width={5000}
height={5000}
headerHeight={50}>
<FixedDataTable.Column
label="Col 1"
width={3000}
dataKey={0}
/>
<FixedDataTable.Column
label="Col 2"
width={2000}
dataKey={1}
/>
</FixedDataTable.Table>
ReactDOM.render(table, document.body);
+402
View File
@@ -0,0 +1,402 @@
// Type definitions for fixed-data-table 0.4.7
// Project: https://github.com/facebook/fixed-data-table
// Definitions by: Petar Paar <https://github.com/pepaar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../react/react.d.ts"/>
declare module FixedDataTable {
export var version: string;
export interface TableProps extends __React.Props<Table> {
/**
* Pixel width of table. If all columns do not fit,
* a horizontal scrollbar will appear.
*/
width: number;
/**
* Pixel height of table. If all rows do not fit,
* a vertical scrollbar will appear.
*
* Either `height` or `maxHeight` must be specified.
*/
height?: number;
/**
* Maximum pixel height of table. If all rows do not fit,
* a vertical scrollbar will appear.
*
* Either `height` or `maxHeight` must be specified.
*/
maxHeight?: number;
/**
* Pixel height of table's owner, this is used in a managed scrolling
* situation when you want to slide the table up from below the fold
* without having to constantly update the height on every scroll tick.
* Instead, vary this property on scroll. By using `ownerHeight`, we
* over-render the table while making sure the footer and horizontal
* scrollbar of the table are visible when the current space for the table
* in view is smaller than the final, over-flowing height of table. It
* allows us to avoid resizing and reflowing table when it is moving in the
* view.
*
* This is used if `ownerHeight < height` (or `maxHeight`).
*/
ownerHeight?: number;
/**
* hidden or auto
*/
overflowX?: string;
overflowY?: string;
/**
* Number of rows in the table.
*/
rowsCount: number;
/**
* Pixel height of rows unless `rowHeightGetter` is specified and returns
* different value.
*/
rowHeight: number;
/**
* If specified, `rowHeightGetter(index)` is called for each row and the
* returned value overrides `rowHeight` for particular row.
*/
rowHeightGetter?: Function;
/**
* To get rows to display in table, `rowGetter(index)`
* is called. `rowGetter` should be smart enough to handle async
* fetching of data and return temporary objects
* while data is being fetched.
*/
rowGetter: Function;
/**
* To get any additional CSS classes that should be added to a row,
* `rowClassNameGetter(index)` is called.
*/
rowClassNameGetter?: Function;
/**
* Pixel height of the column group header.
*/
groupHeaderHeight?: number;
/**
* Pixel height of header.
*/
headerHeight: number;
/**
* Function that is called to get the data for the header row.
* If the function returns null, the header will be set to the
* Column's label property.
*/
headerDataGetter?: Function;
/**
* Pixel height of footer.
*/
footerHeight?: number;
/**
* DEPRECATED - use footerDataGetter instead.
* Data that will be passed to footer cell renderers.
*/
footerData?: any;
/**
* Function that is called to get the data for the footer row.
*/
footerDataGetter?: Function;
/**
* Value of horizontal scroll.
*/
scrollLeft?: number;
/**
* Index of column to scroll to.
*/
scrollToColumn?: number;
/**
* Value of vertical scroll.
*/
scrollTop?: number;
/**
* Index of row to scroll to.
*/
scrollToRow?: number;
/**
* Callback that is called when scrolling starts with current horizontal
* and vertical scroll values.
*/
onScrollStart?: Function;
/**
* Callback that is called when scrolling ends or stops with new horizontal
* and vertical scroll values.
*/
onScrollEnd?: Function;
/**
* Callback that is called when `rowHeightGetter` returns a different height
* for a row than the `rowHeight` prop. This is necessary because initially
* table estimates heights of some parts of the content.
*/
onContentHeightChange?: Function;
/**
* Callback that is called when a row is clicked.
*/
onRowClick?: Function;
/**
* Callback that is called when a row is double clicked.
*/
onRowDoubleClick?: Function;
/**
* Callback that is called when a mouse-down event happens on a row.
*/
onRowMouseDown?: Function;
/**
* Callback that is called when a mouse-enter event happens on a row.
*/
onRowMouseEnter?: Function;
/**
* Callback that is called when a mouse-leave event happens on a row.
*/
onRowMouseLeave?: Function;
/**
* Callback that is called when resizer has been released
* and column needs to be updated.
*
* Required if the isResizable property is true on any column.
*
* ```
* function(
* newColumnWidth: number,
* dataKey: string,
* )
* ```
*/
onColumnResizeEndCallback?: Function;
/**
* Whether a column is currently being resized.
*/
isColumnResizing?: boolean
}
interface ColumnProps {
/**
* The horizontal alignment of the table cell content.
* 'left', 'center', 'right'
*/
align?: string;
/**
* className for this column's header cell.
*/
headerClassName?: string;
/**
* className for this column's footer cell.
*/
footerClassName?: string;
/**
* className for each of this column's data cells.
*/
cellClassName?: string;
/**
* The cell renderer that returns React-renderable content for table cell.
* ```
* function(
* cellData: any,
* cellDataKey: string,
* rowData: object,
* rowIndex: number,
* columnData: any,
* width: number
* ): ?$jsx
* ```
*/
cellRenderer?: Function;
/**
* The getter `function(string_cellDataKey, object_rowData)` that returns
* the cell data for the `cellRenderer`.
* If not provided, the cell data will be collected from
* `rowData[cellDataKey]` instead. The value that `cellDataGetter` returns
* will be used to determine whether the cell should re-render.
*/
cellDataGetter?: Function;
/**
* The key to retrieve the cell data from the data row. Provided key type
* must be either `string` or `number`. Since we use this
* for keys, it must be specified for each column.
*/
dataKey: string|number;
/**
* Controls if the column is fixed when scrolling in the X axis.
*/
fixed?: boolean;
/**
* The cell renderer that returns React-renderable content for table column
* header.
* ```
* function(
* label: ?string,
* cellDataKey: string,
* columnData: any,
* rowData: array<?object>,
* width: number
* ): ?$jsx
* ```
*/
headerRenderer?: Function;
/**
* The cell renderer that returns React-renderable content for table column
* footer.
* ```
* function(
* label: ?string,
* cellDataKey: string,
* columnData: any,
* rowData: array<?object>,
* width: number
* ): ?$jsx
* ```
*/
footerRenderer?: Function;
/**
* Bucket for any data to be passed into column renderer functions.
*/
columnData?: any;
/**
* The column's header label.
*/
label: string;
/**
* The pixel width of the column.
*/
width: number;
/**
* If this is a resizable column this is its minimum pixel width.
*/
minWidth?: number;
/**
* If this is a resizable column this is its maximum pixel width.
*/
maxWidth?: number;
/**
* The grow factor relative to other columns. Same as the flex-grow API
* from http://www.w3.org/TR/css3-flexbox/. Basically, take any available
* extra width and distribute it proportionally according to all columns'
* flexGrow values. Defaults to zero (no-flexing).
*/
flexGrow?: number;
/**
* Whether the column can be resized with the
* FixedDataTableColumnResizeHandle. Please note that if a column
* has a flex grow, once you resize the column this will be set to 0.
*
* This property only provides the UI for the column resizing. If this
* is set to true, you will need ot se the onColumnResizeEndCallback table
* property and render your columns appropriately.
*/
isResizable?: boolean;
/**
* Experimental feature
* Whether cells in this column can be removed from document when outside
* of viewport as a result of horizontal scrolling.
* Setting this property to true allows the table to not render cells in
* particular column that are outside of viewport for visible rows. This
* allows to create table with many columns and not have vertical scrolling
* performance drop.
* Setting the property to false will keep previous behaviour and keep
* cell rendered if the row it belongs to is visible.
*/
allowCellsRecycling?: boolean;
}
export interface ColumnGroupProps {
/**
* The horizontal alignment of the table cell content.
* 'left', 'center', 'right'
*/
align?: string;
/**
* Controls if the column group is fixed when scrolling in the X axis.
*/
fixed?: boolean;
/**
* Bucket for any data to be passed into column group renderer functions.
*/
columnGroupData?: any;
/**
* The column group's header label.
*/
label?: string;
/**
* The cell renderer that returns React-renderable content for a table
* column group header. If it's not specified, the label from props will
* be rendered as header content.
* ```
* function(
* label: ?string,
* cellDataKey: string,
* columnGroupData: any,
* rowData: array<?object>, // array of labels of all columnGroups
* width: number
* ): ?$jsx
* ```
*/
groupHeaderRenderer?: Function;
}
export class Table extends __React.Component<TableProps, {}> {
render(): __React.DOMElement<any>
}
export class Column extends __React.Component<ColumnProps, {}> {
render(): __React.DOMElement<any>
}
export class ColumnGroup extends __React.Component<ColumnGroupProps, {}> {
render(): __React.DOMElement<any>
}
}
declare module "fixed-data-table" {
export = FixedDataTable;
}
+161 -31
View File
@@ -1,39 +1,169 @@
///<reference path="./fixed-data-table.d.ts"" />
/// <reference path="./fixed-data-table.d.ts"" />
/// <reference path="../react/react.d.ts"/>
/// <reference path="../react/react-dom.d.ts"/>
import * as React from "react";
import * as ReactDOM from "react-dom";
import * as FixedDataTable from "fixed-data-table";
import {Table, Cell, Column, CellProps} from "fixed-data-table";
var rows = [
['a1', 'b1', 'c1'],
['a2', 'b2', 'c2'],
['a3', 'b3', 'c3'],
// .... and more
];
function rowGetter(rowIndex: number) {
return rows[rowIndex];
// create your Table
class MyTable1 extends React.Component<{}, {}> {
render(): React.ReactElement<any> {
return (
<Table
rowsCount={100}
rowHeight={50}
width={1000}
height={500}>
// add columns
</Table>
);
}
}
var table = <FixedDataTable.Table
// create your Columns
class MyTable2 extends React.Component<{}, {}> {
render(): React.ReactElement<any> {
return (
<Table
rowsCount={100}
rowHeight={50}
rowGetter={rowGetter}
rowsCount={rows.length}
width={5000}
height={5000}
headerHeight={50}>
<FixedDataTable.Column
label="Col 1"
width={3000}
dataKey={0}
/>
<FixedDataTable.Column
label="Col 2"
width={2000}
dataKey={1}
/>
</FixedDataTable.Table>
width={1000}
height={500}>
<Column
cell={<Cell>Basic content</Cell>}
width={200}
/>
</Table>
);
}
}
ReactDOM.render(table, document.body);
// provide Custom Data
interface MyTable3State {
myTableData: [{name: string}];
}
class MyTable3 extends React.Component<{}, MyTable3State> {
constructor(props: {}) {
super(props);
this.state = {
myTableData: [
{name: "Rylan"},
{name: "Amelia"},
{name: "Estevan"},
{name: "Florence"},
{name: "Tressa"},
]
};
}
render(): React.ReactElement<any> {
return (
<Table
rowsCount={this.state.myTableData.length}
rowHeight={50}
headerHeight={50}
width={1000}
height={500}>
<Column
header={<Cell>Name</Cell>}
cell={(props: CellProps) => (
<Cell {...props}>
{this.state.myTableData[props.rowIndex].name}
</Cell>
)}
width={200}
/>
</Table>
);
}
}
// Create Reusable Cells
interface RowData {
[field: string]: string;
}
interface MyCellProps extends CellProps {
rowIndex?: number;
field: string;
data: RowData[];
}
class MyTextCell extends React.Component<MyCellProps, {}> {
render(): React.ReactElement<any> {
const {rowIndex, field, data} = this.props;
return (
<Cell {...this.props}>
{data[rowIndex][field]}
</Cell>
);
}
}
class MyLinkCell extends React.Component<MyCellProps, {}> {
render(): React.ReactElement<any> {
const {rowIndex, field, data} = this.props;
const link: string = data[rowIndex][field];
return (
<Cell {...this.props}>
<a href={link}>{link}</a>
</Cell>
);
}
}
interface MyTable4State {
tableData: RowData[];
}
class MyTable4 extends React.Component<{}, MyTable4State> {
constructor(props: {}) {
super(props);
this.state = {
tableData: [
{name: "Rylan", email: "Angelita_Weimann42@gmail.com"},
{name: "Amelia", email: "Dexter.Trantow57@hotmail.com"},
{name: "Estevan", email: "Aimee7@hotmail.com"},
{name: "Florence", email: "Jarrod.Bernier13@yahoo.com"},
{name: "Tressa", email: "Yadira1@hotmail.com"}
]
};
}
render(): React.ReactElement<any> {
return (
<Table
rowsCount={this.state.tableData.length}
rowHeight={50}
headerHeight={50}
width={1000}
height={500}>
<Column
header={<Cell>Name</Cell>}
cell={
<MyTextCell
data={this.state.tableData}
field="name"
/>
}
width={200}/>
<Column
header={<Cell>Email</Cell>}
cell={
<MyLinkCell
data={this.state.tableData}
field="email"
/>
}
width={200}
/>
</Table>
);
}
}
+441 -342
View File
@@ -1,6 +1,6 @@
// Type definitions for fixed-data-table 0.4.7
// Type definitions for fixed-data-table 0.6.0
// Project: https://github.com/facebook/fixed-data-table
// Definitions by: Petar Paar <https://github.com/pepaar>
// Definitions by: Petar Paar <https://github.com/pepaar>, Stephen Jelfs <https://github.com/stephenjelfs>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../react/react.d.ts"/>
@@ -8,345 +8,396 @@
declare module FixedDataTable {
export var version: string;
/**
* Data grid component with fixed or scrollable header and columns.
*
* The layout of the data table is as follows:
*
*
* +---------------------------------------------------+
* | Fixed Column Group | Scrollable Column Group |
* | Header | Header |
* | | |
* +---------------------------------------------------+
* | | |
* | Fixed Header Columns | Scrollable Header Columns |
* | | |
* +-----------------------+---------------------------+
* | | |
* | Fixed Body Columns | Scrollable Body Columns |
* | | |
* +-----------------------+---------------------------+
* | | |
* | Fixed Footer Columns | Scrollable Footer Columns |
* | | |
* +-----------------------+---------------------------+
*
* Fixed Column Group Header:
*
* These are the headers for a group of columns if included in
* the table that do not scroll vertically or horizontally.
*
* Scrollable Column Group Header:
*
* The header for a group of columns that do not move while
* scrolling vertically, but move horizontally with the
* horizontal scrolling.
*
* Fixed Header Columns:
*
* The header columns that do not move while scrolling
* vertically or horizontally.
*
* Scrollable Header Columns:
*
* The header columns that do not move while scrolling
* vertically, but move horizontally with the horizontal scrolling.
*
* Fixed Body Columns:
*
* The body columns that do not move while scrolling
* horizontally, but move vertically with the vertical scrolling.
*
* Scrollable Body Columns:
*
* The body columns that move while scrolling vertically or
* horizontally.
*
*/
export interface TableProps extends __React.Props<Table> {
/**
* Pixel width of table. If all columns do not fit,
* a horizontal scrollbar will appear.
*/
width: number;
/**
* Pixel height of table. If all rows do not fit,
* a vertical scrollbar will appear.
*
* Either `height` or `maxHeight` must be specified.
*/
height?: number;
/**
* Maximum pixel height of table. If all rows do not fit,
* a vertical scrollbar will appear.
*
* Either `height` or `maxHeight` must be specified.
*/
maxHeight?: number;
/**
* Pixel height of table's owner, this is used in a managed scrolling
* situation when you want to slide the table up from below the fold
* without having to constantly update the height on every scroll tick.
* Instead, vary this property on scroll. By using `ownerHeight`, we
* over-render the table while making sure the footer and horizontal
* scrollbar of the table are visible when the current space for the table
* in view is smaller than the final, over-flowing height of table. It
* allows us to avoid resizing and reflowing table when it is moving in the
* view.
*
* This is used if `ownerHeight < height` (or `maxHeight`).
*/
ownerHeight?: number;
/**
* Pixel width of table. If all columns do not fit, a
* horizontal scrollbar will appear.
*/
width: number;
/**
* Pixel height of table. If all rows do not fit, a
* vertical scrollbar will appear.
*
* Either height or maxHeight must be specified.
*/
height?: number;
/**
* hidden or auto
*/
overflowX?: string;
overflowY?: string;
* Maximum pixel height of table. If all rows do not fit,
* a vertical scrollbar will appear.
*
* Either height or maxHeight must be specified.
*/
maxHeight?: number;
/**
* Pixel height of table's owner, this is used in a managed
* scrolling situation when you want to slide the table up
* from below the fold without having to constantly update
* the height on every scroll tick. Instead, vary this
* property on scroll. By using ownerHeight, we over-render
* the table while making sure the footer and horizontal
* scrollbar of the table are visible when the current space
* for the table in view is smaller than the final,
* over-flowing height of table. It allows us to avoid
* resizing and reflowing table when it is moving in the
* view.
*
* This is used if ownerHeight < height (or maxHeight).
*/
ownerHeight?: number;
/**
* Number of rows in the table.
*/
rowsCount: number;
/**
* 'hidden'|'auto'
*/
overflowX?: string;
/**
* 'hidden'|'auto'
*/
overflowY?: string;
/**
* Pixel height of rows unless `rowHeightGetter` is specified and returns
* different value.
*/
rowHeight: number;
/**
* Number of rows in the table.
*/
rowsCount: number;
/**
* If specified, `rowHeightGetter(index)` is called for each row and the
* returned value overrides `rowHeight` for particular row.
*/
rowHeightGetter?: Function;
/**
* Pixel height of rows unless rowHeightGetter is specified
* and returns different value.
*/
rowHeight: number;
/**
* If specified, rowHeightGetter(index) is called for each
* row and the returned value overrides rowHeight for
* particular row.
*/
rowHeightGetter?: (index: number) => number;
/**
* To get any additional CSS classes that should be added to
* a row, rowClassNameGetter(index) is called.
*/
rowClassNameGetter?: (index: number) => string;
/**
* To get rows to display in table, `rowGetter(index)`
* is called. `rowGetter` should be smart enough to handle async
* fetching of data and return temporary objects
* while data is being fetched.
*/
rowGetter: Function;
/**
* Pixel height of the column group header.
*
* defaultValue: 0
*/
groupHeaderHeight?: number;
/**
* To get any additional CSS classes that should be added to a row,
* `rowClassNameGetter(index)` is called.
*/
rowClassNameGetter?: Function;
/**
* Pixel height of the header.
*
* defaultValue: 0
*/
headerHeight?: number;
/**
* Pixel height of the column group header.
*/
groupHeaderHeight?: number;
/**
* Pixel height of header.
*/
headerHeight: number;
/**
* Function that is called to get the data for the header row.
* If the function returns null, the header will be set to the
* Column's label property.
*/
headerDataGetter?: Function;
/**
* Pixel height of footer.
*/
footerHeight?: number;
/**
* DEPRECATED - use footerDataGetter instead.
* Data that will be passed to footer cell renderers.
*/
footerData?: any;
/**
* Function that is called to get the data for the footer row.
*/
footerDataGetter?: Function;
/**
* Value of horizontal scroll.
*/
scrollLeft?: number;
/**
* Index of column to scroll to.
*/
scrollToColumn?: number;
/**
* Value of vertical scroll.
*/
scrollTop?: number;
/**
* Index of row to scroll to.
*/
scrollToRow?: number;
/**
* Callback that is called when scrolling starts with current horizontal
* and vertical scroll values.
*/
onScrollStart?: Function;
/**
* Callback that is called when scrolling ends or stops with new horizontal
* and vertical scroll values.
*/
onScrollEnd?: Function;
/**
* Callback that is called when `rowHeightGetter` returns a different height
* for a row than the `rowHeight` prop. This is necessary because initially
* table estimates heights of some parts of the content.
*/
onContentHeightChange?: Function;
/**
* Callback that is called when a row is clicked.
*/
onRowClick?: Function;
/**
* Callback that is called when a row is double clicked.
*/
onRowDoubleClick?: Function;
/**
* Callback that is called when a mouse-down event happens on a row.
*/
onRowMouseDown?: Function;
/**
* Callback that is called when a mouse-enter event happens on a row.
*/
onRowMouseEnter?: Function;
/**
* Callback that is called when a mouse-leave event happens on a row.
*/
onRowMouseLeave?: Function;
/**
* Callback that is called when resizer has been released
* and column needs to be updated.
*
* Required if the isResizable property is true on any column.
*
* ```
* function(
* newColumnWidth: number,
* dataKey: string,
* )
* ```
*/
onColumnResizeEndCallback?: Function;
/**
* Whether a column is currently being resized.
*/
isColumnResizing?: boolean
/**
* Pixel height of the footer.
*
* defaultValue: 0
*/
footerHeight?: number;
/**
* Value of horizontal scroll.
*
* defaultValue: 0
*/
scrollLeft?: number;
/**
* Index of column to scroll to.
*/
scrollToColumn?: number;
/**
* Value of vertical scroll.
*
* defaultValue: 0
*/
scrollTop?: number;
/**
* Index of row to scroll to.
*/
scrollToRow?: number;
/**
* Callback that is called when scrolling starts with
* current horizontal and vertical scroll values.
*/
onScrollStart?: (horizontalScroll: number, verticalScroll: number) => void;
/**
* Callback that is called when scrolling ends or stops with
* new horizontal and vertical scroll values.
*/
onScrollEnd?: (horizontalScroll: number, verticalScroll: number) => void;
/**
* Callback that is called when rowHeightGetter returns a
* different height for a row than the rowHeight prop. This
* is necessary because initially table estimates heights
* of some parts of the content.
*/
onContentHeightChange?: (height: number) => void;
/**
* Callback that is called when a row is clicked.
*/
onRowClick?: (index: number) => void;
/**
* Callback that is called when a row is double clicked.
*/
onRowDoubleClick?: (index: number) => void;
/**
* Callback that is called when a mouse-down event happens
* on a row.
*/
onRowMouseDown?: (index: number) => void;
/**
* Callback that is called when a mouse-enter event happens
* on a row.
*/
onRowMouseEnter?: (index: number) => void;
/**
* Callback that is called when a mouse-leave event happens
* on a row.
*/
onRowMouseLeave?: (index: number) => void;
/**
* Callback that is called when resizer has been released
* and column needs to be updated.
*
* Required if the isResizable property is true on any
* column.
*/
onColumnResizeEndCallback?: (newColumnWidth: number, columnKey: string) => void;
/**
* Whether a column is currently being resized.
*/
isColumnResizing?: boolean;
}
/**
* Component that defines the attributes of table column.
*/
interface ColumnProps {
/**
* The horizontal alignment of the table cell content.
* 'left', 'center', 'right'
*/
align?: string;
* The horizontal alignment of the table cell content.
*
* 'left'|'center'|'right'
*/
align?: string;
/**
* className for this column's header cell.
*/
headerClassName?: string;
/**
* Controls if the column is fixed when scrolling in the X
* axis.
*
* defaultValue: false
*/
fixed?: boolean;
/**
* className for this column's footer cell.
*/
footerClassName?: string;
/**
* The header cell for this column. This can either be a
* string. a React element, or a function that generates a
* React Element. Passing in a string will render a default
* header cell with that string. By default, the React
* element passed in can expect to receive the following
* props:
*
* props: {
* columnKey: string // (of the column, if given)
* height: number // (supplied from the Table or rowHeightGetter)
* width: number // (supplied from the Column)
* }
*
* Because you are passing in your own React element, you
* can feel free to pass in whatever props you may want or need.
*
* If you pass in a function, you will receive the same props object as the first argument.
*/
header?: string | __React.ReactElement<any> | ((props: CellProps) => (string | __React.ReactElement<any>));
/**
* This is the body cell that will be cloned for this
* column. This can either be a string a React element,
* or a function that generates a React Element. Passing
* in a string will render a default cell with that
* string. By default, the React element passed in can
* expect to receive the following props:
*
* props: {
* rowIndex; number // (the row index of the cell)
* columnKey: string // (of the column, if given)
* height: number // (supplied from the Table or rowHeightGetter)
* width: number // (supplied from the Column)
* }
*
* Because you are passing in your own React element, you
* can feel free to pass in whatever props you may want or
* need.
*
* If you pass in a function, you will receive the same
* props object as the first argument.
*/
cell?: string | __React.ReactElement<any> | ((props: CellProps) => (string | __React.ReactElement<any>));
/**
* The footer cell for this column. This can either be a
* string. a React element, or a function that generates a
* React Element. Passing in a string will render a default
* header cell with that string. By default, the React
* element passed in can expect to receive the following
* props:
*
* props: {
* columnKey: string // (of the column, if given)
* height: number // (supplied from the Table or rowHeightGetter)
* width: number // (supplied from the Column)
* }
*
* Because you are passing in your own React element, you
* can feel free to pass in whatever props you may want or
* need.
*
* If you pass in a function, you will receive the same
* props object as the first argument.
*/
footer?: string | __React.ReactElement<any> | ((props: CellProps) => (string | __React.ReactElement<any>));
/**
* className for each of this column's data cells.
*/
cellClassName?: string;
/**
* This is used to uniquely identify the column, and is not
* required unless you a resizing columns. This will be the
* key given in the onColumnResizeEndCallback on the Table.
*/
columnKey?: string | number;
/**
* The cell renderer that returns React-renderable content for table cell.
* ```
* function(
* cellData: any,
* cellDataKey: string,
* rowData: object,
* rowIndex: number,
* columnData: any,
* width: number
* ): ?$jsx
* ```
*/
cellRenderer?: Function;
/**
* The pixel width of the column.
*/
width: number;
/**
* The getter `function(string_cellDataKey, object_rowData)` that returns
* the cell data for the `cellRenderer`.
* If not provided, the cell data will be collected from
* `rowData[cellDataKey]` instead. The value that `cellDataGetter` returns
* will be used to determine whether the cell should re-render.
*/
cellDataGetter?: Function;
/**
* If this is a resizable column this is its minimum pixel
* width.
*/
minWidth?: number;
/**
* The key to retrieve the cell data from the data row. Provided key type
* must be either `string` or `number`. Since we use this
* for keys, it must be specified for each column.
*/
dataKey: string|number;
/**
* If this is a resizable column this is its maximum pixel
* width.
*/
maxWidth?: number;
/**
* Controls if the column is fixed when scrolling in the X axis.
*/
fixed?: boolean;
/**
* The grow factor relative to other columns. Same as the
* flex-grow API from http://www.w3.org/TR/css3-flexbox/.
* Basically, take any available extra width and distribute
* it proportionally according to all columns' flexGrow
* values. Defaults to zero (no-flexing).
*/
flexGrow?: number;
/**
* The cell renderer that returns React-renderable content for table column
* header.
* ```
* function(
* label: ?string,
* cellDataKey: string,
* columnData: any,
* rowData: array<?object>,
* width: number
* ): ?$jsx
* ```
*/
headerRenderer?: Function;
/**
* Whether the column can be resized with the
* FixedDataTableColumnResizeHandle. Please note that if a
* column has a flex grow, once you resize the column this
* will be set to 0.
*
* This property only provides the UI for the column
* resizing. If this is set to true, you will need to set the
* onColumnResizeEndCallback table property and render your
* columns appropriately.
*/
isResizable?: boolean;
/**
* The cell renderer that returns React-renderable content for table column
* footer.
* ```
* function(
* label: ?string,
* cellDataKey: string,
* columnData: any,
* rowData: array<?object>,
* width: number
* ): ?$jsx
* ```
*/
footerRenderer?: Function;
/**
* Bucket for any data to be passed into column renderer functions.
*/
columnData?: any;
/**
* The column's header label.
*/
label: string;
/**
* The pixel width of the column.
*/
width: number;
/**
* If this is a resizable column this is its minimum pixel width.
*/
minWidth?: number;
/**
* If this is a resizable column this is its maximum pixel width.
*/
maxWidth?: number;
/**
* The grow factor relative to other columns. Same as the flex-grow API
* from http://www.w3.org/TR/css3-flexbox/. Basically, take any available
* extra width and distribute it proportionally according to all columns'
* flexGrow values. Defaults to zero (no-flexing).
*/
flexGrow?: number;
/**
* Whether the column can be resized with the
* FixedDataTableColumnResizeHandle. Please note that if a column
* has a flex grow, once you resize the column this will be set to 0.
*
* This property only provides the UI for the column resizing. If this
* is set to true, you will need ot se the onColumnResizeEndCallback table
* property and render your columns appropriately.
*/
isResizable?: boolean;
/**
* Experimental feature
* Whether cells in this column can be removed from document when outside
* of viewport as a result of horizontal scrolling.
* Setting this property to true allows the table to not render cells in
* particular column that are outside of viewport for visible rows. This
* allows to create table with many columns and not have vertical scrolling
* performance drop.
* Setting the property to false will keep previous behaviour and keep
* cell rendered if the row it belongs to is visible.
*/
allowCellsRecycling?: boolean;
/**
* Whether cells in this column can be removed from document
* when outside of viewport as a result of horizontal
* scrolling. Setting this property to true allows the table
* to not render cells in particular column that are outside
* of viewport for visible rows. This allows to create table
* with many columns and not have vertical scrolling
* performance drop. Setting the property to false will keep
* previous behaviour and keep cell rendered if the row it
* belongs to is visible.
*
* defaultValue: false
*/
allowCellsRecycling?: boolean;
}
/**
* Component that defines the attributes of a table column group.
*/
export interface ColumnGroupProps {
/**
* The horizontal alignment of the table cell content.
@@ -355,35 +406,80 @@ declare module FixedDataTable {
align?: string;
/**
* Controls if the column group is fixed when scrolling in the X axis.
* Controls if the column group is fixed when scrolling in the X
* axis.
*
* defaultValue: false
*/
fixed?: boolean;
/**
* Bucket for any data to be passed into column group renderer functions.
*/
columnGroupData?: any;
/**
* The header cell for this column group. This can either be
* a string. a React element, or a function that generates a
* React Element. Passing in a string will render a default
* header cell with that string. By default, the React
* element passed in can expect to receive the following
* props:
*
* props: {
* height: number // (supplied from the groupHeaderHeight)
* width: number // (supplied from the Column)
* }
*
* Because you are passing in your own React element, you
* can feel free to pass in whatever props you may want or
* need.
*
* If you pass in a function, you will receive the same props
* object as the first argument.
*/
header: string | __React.ReactElement<any> | ((props: CellProps) => (string | __React.ReactElement<any>));
}
/**
* Component that handles default cell layout and styling.
*
* All props unless specified below will be set onto the top
* level div rendered by the cell.
*
* Example usage via from a Column:
*
* const MyColumn = (
* <Column
* cell={({rowIndex, width, height}) => (
* <Cell
* width={width}
* height={height}
* className="my-class">
* Cell number: <span>{rowIndex}</span>
* </Cell>
* )}
* width={100}
* />
* );
*/
export interface CellProps {
/**
* The row index of the cell.
*/
rowIndex?: number
/**
* The column group's header label.
*/
label?: string;
/**
* Outer height of the cell.
*/
height?: number;
/**
* The cell renderer that returns React-renderable content for a table
* column group header. If it's not specified, the label from props will
* be rendered as header content.
* ```
* function(
* label: ?string,
* cellDataKey: string,
* columnGroupData: any,
* rowData: array<?object>, // array of labels of all columnGroups
* width: number
* ): ?$jsx
* ```
*/
groupHeaderRenderer?: Function;
/**
* Outer width of the cell.
*/
width?: number;
/**
* Optional prop that if specified on the Column will be
* passed to the cell. It can be used to uniquely identify
* which column is the cell is in.
*/
columnKey?: string | number;
}
export class Table extends __React.Component<TableProps, {}> {
@@ -395,6 +491,9 @@ declare module FixedDataTable {
export class ColumnGroup extends __React.Component<ColumnGroupProps, {}> {
render(): __React.DOMElement<any>
}
export class Cell extends __React.Component<CellProps, {}> {
render(): __React.DOMElement<any>
}
}
declare module "fixed-data-table" {
+49 -1
View File
@@ -1,6 +1,12 @@
/// <reference path="flux.d.ts" />
/// <reference path="../react/react.d.ts" />
import flux = require('flux')
import FluxUtils = require('flux/utils')
import React = require('react')
var Component = React.Component
var Container = FluxUtils.Container
//
// Basic dispatcher usage
@@ -78,4 +84,46 @@ class CustomDispatcher extends flux.Dispatcher<Action> {
var customDispatcher = new CustomDispatcher()
export = customDispatcher
export = customDispatcher
// Sample Reduce Store
class CounterStore extends FluxUtils.ReduceStore<number> {
getInitialState(): number {
return 0;
}
reduce(state: number, action: any): number {
switch (action.type) {
case 'increment':
return state + 1;
case 'square':
return state * state;
default:
return state;
}
}
}
const Store = new CounterStore(basicDispatcher);
// Sample Flux container with CounterStore
class CounterContainer extends Component<any, any> {
static getStores() {
return [Store];
}
static calculateState(prevState: any) {
return {
counter: Store.getState(),
};
}
render() {
return this.state.counter;
}
}
const container = Container.create(CounterContainer);
+128 -1
View File
@@ -1,8 +1,10 @@
// Type definitions for Flux
// Project: http://facebook.github.io/flux/
// Definitions by: Steve Baker <https://github.com/stkb/>
// Definitions by: Steve Baker <https://github.com/stkb/>, Giedrius Grabauskas <https://github.com/QuatroDevOfficial/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../react/react.d.ts" />
declare module Flux {
/**
@@ -65,3 +67,128 @@ declare module Flux {
declare module "flux" {
export = Flux;
}
declare module FluxUtils {
import React = __React;
export class Container {
constructor();
/**
* Create is used to transform a react class into a container
* that updates its state when relevant stores change.
* The provided base class must have static methods getStores() and calculateState().
*/
static create(base: React.ComponentClass<any>, options?: any): React.ComponentClass<any>;
}
/**
* This class extends ReduceStore and defines the state as an immutable map.
*/
// TODO: Change <any> to <Immutable.Map<K, V>>
export class MapStore<K extends string | number, V> extends ReduceStore<any> {
/**
* Access the value at the given key.
* Throws an error if the key does not exist in the cache.
*/
at(key: K): V;
/**
* Check if the cache has a particular key
*/
has(key: K): boolean;
/**
* Get the value of a particular key.
* Returns undefined if the key does not exist in the cache.
*/
get(key: K): V;
/**
* Gets an array of keys and puts the values in a map if they exist,
* it allows providing a previous result to update instead of generating a new map.
* Providing a previous result allows the possibility of keeping the same reference if the keys did not change.
*/
// TODO: Update with Immutable interface.
// getAll(keys: Immutable.IndexedIterable<K>, prev?: Immutable.Map<K, V>): Immutable.Map<K, V>;
getAll(keys: any, prev?: any): any;
}
export class ReduceStore<T> extends Store {
/**
* Getter that exposes the entire state of this store.
* If your state is not immutable you should override this and not expose state directly.
*/
getState(): T;
/**
* Constructs the initial state for this store.
* This is called once during construction of the store.
*/
getInitialState(): T;
/**
* Reduces the current state, and an action to the new state of this store.
* All subclasses must implement this method.
* This method should be pure and have no side-effects.
*/
reduce(state: T, action: any): T;
/**
* Checks if two versions of state are the same.
* You do not need to override this if your state is immutable.
*/
areEqual(one: T, two: T): boolean;
}
export class Store {
/**
* Constructs and registers an instance of this store with the given dispatcher.
*/
constructor(dispatcher: Flux.Dispatcher<any>);
/**
* Adds a listener to the store, when the store changes the given callback will be called.
* A token is returned that can be used to remove the listener.
* Calling the remove() function on the returned token will remove the listener.
*/
addListener(callback: Function): { remove: Function };
/**
* Returns the dispatcher this store is registered with.
*/
getDispatcher(): Flux.Dispatcher<any>;
/**
* Returns the dispatch token that the dispatcher recognizes this store by.
* Can be used to waitFor() this store.
*/
getDispatchToken(): string;
/**
* Ask if a store has changed during the current dispatch.
* Can only be invoked while dispatching.
* This can be used for constructing derived stores that depend on data from other stores.
*/
hasChanged(): boolean;
/**
*Emit an event notifying all listeners that this store has changed.
* This can only be invoked when dispatching.
* Changes are de-duplicated and resolved at the end of this store's __onDispatch function.
*/
__emitChange(): void;
/**
* Subclasses must override this method.
* This is how the store receives actions from the dispatcher.
* All state mutation logic must be done during this method.
*/
__onDispatch(payload: any): void;
}
}
declare module 'flux/utils' {
export = FluxUtils;
}
+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;
};
}
}
+19 -1
View File
@@ -45,6 +45,7 @@ var openOpts: fs.OpenOptions;
var watcher: fs.FSWatcher;
var readStreeam: stream.Readable;
var writeStream: stream.Writable;
var outputStream: stream.Writable;
fs.copy(src, dest, errorCallback);
fs.copy(src, dest, (src: string) => {
@@ -150,7 +151,7 @@ strArr = fs.readdirSync(path);
fs.close(fd, errorCallback);
fs.closeSync(fd);
fs.open(path, flags, modeStr, (err: Error, fd: number) => {
});
num = fs.openSync(path, flags, modeStr);
fs.utimes(path, atime, mtime, errorCallback);
@@ -217,6 +218,17 @@ fs.exists(path, (exists: boolean) => {
});
bool = fs.existsSync(path);
fs.ensureDir(path, errorCallback);
fs.ensureDirSync(path);
fs.ensureFile(path, errorCallback);
fs.ensureFileSync(path);
fs.ensureLink(path, errorCallback);
fs.ensureLinkSync(path);
fs.ensureSymlink(path, errorCallback);
fs.ensureSymlinkSync(path);
fs.emptyDir(path, errorCallback);
fs.emptyDirSync(path);
readStreeam = fs.createReadStream(path);
readStreeam = fs.createReadStream(path, {
flags: str,
@@ -231,3 +243,9 @@ writeStream = fs.createWriteStream(path, {
encoding: str,
string: str
});
outputStream = fs.createOutputStream(path);
outputStream = fs.createOutputStream(path, {
flags: str,
encoding: str,
string: str
});
+10
View File
@@ -167,6 +167,15 @@ declare module "fs-extra" {
export function exists(path: string, callback?: (exists: boolean) => void ): void;
export function existsSync(path: string): boolean;
export function ensureDir(path: string, cb: (err: Error) => void): void;
export function ensureDirSync(path: string): void;
export function ensureFile(path: string, cb: (err: Error) => void): void;
export function ensureFileSync(path: string): void;
export function ensureLink(path: string, cb: (err: Error) => void): void;
export function ensureLinkSync(path: string): void;
export function ensureSymlink(path: string, cb: (err: Error) => void): void;
export function ensureSymlinkSync(path: string): void;
export function emptyDir(path: string, callback?: (err: Error) => void): void;
export function emptyDirSync(path: string): boolean;
export interface OpenOptions {
encoding?: string;
@@ -192,4 +201,5 @@ declare module "fs-extra" {
}
export function createReadStream(path: string, options?: ReadStreamOptions): ReadStream;
export function createWriteStream(path: string, options?: WriteStreamOptions): WriteStream;
export function createOutputStream(path: string, options?: WriteStreamOptions): WriteStream;
}

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