Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Chris Barker
2017-01-18 13:46:40 +00:00
164 changed files with 9920 additions and 2552 deletions
+59
View File
@@ -0,0 +1,59 @@
import events = require('events');
import { Replies, Options, Message } from './properties';
export * from './properties';
export interface Connection extends events.EventEmitter {
close(callback?: (err: any) => void): void;
createChannel(callback: (err: any, channel: Channel) => void): void;
createConfirmChannel(callback: (err: any, confirmChannel: ConfirmChannel) => void): void;
}
export interface Channel extends events.EventEmitter {
close(callback: (err: any) => void): void;
assertQueue(queue?: string, options?: Options.AssertQueue, callback?: (err: any, ok: Replies.AssertQueue) => void): void;
checkQueue(queue: string, callback?: (err: any, ok: Replies.AssertQueue) => void): void;
deleteQueue(queue: string, options?: Options.DeleteQueue, callback?: (err: any, ok: Replies.DeleteQueue) => void): void;
purgeQueue(queue: string, callback?: (err: any, ok: Replies.PurgeQueue) => void): void;
bindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
unbindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
assertExchange(exchange: string, type: string, options?: Options.AssertExchange, callback?: (err: any, ok: Replies.AssertExchange) => void): void;
checkExchange(exchange: string, callback?: (err: any, ok: Replies.Empty) => void): void;
deleteExchange(exchange: string, options?: Options.DeleteExchange, callback?: (err: any, ok: Replies.Empty) => void): void;
bindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
unbindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume, callback?: (err: any, ok: Replies.Consume) => void): void;
cancel(consumerTag: string, callback?: (err: any, ok: Replies.Empty) => void): void;
get(queue: string, options?: Options.Get, callback?: (err: any, ok: Message | boolean) => void): void;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
nack(message: Message, allUpTo?: boolean, requeue?: boolean): void;
nackAll(requeue?: boolean): void;
reject(message: Message, requeue?: boolean): void;
prefetch(count: number, global?: boolean): void;
recover(callback?: (err: any, ok: Replies.Empty) => void): void;
}
export interface ConfirmChannel extends Channel {
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean;
waitForConfirms(callback?: (err: any) => void): void;
}
export function connect(callback: (err: any, connection: Connection) => void): void;
export function connect(url: string, callback: (err: any, connection: Connection) => void): void;
export function connect(url: string, socketOptions: any, callback: (err: any, connection: Connection) => void): void;
+48 -209
View File
@@ -1,226 +1,65 @@
// Type definitions for amqplib 0.5.x
// Type definitions for amqplib 0.5
// Project: https://github.com/squaremo/amqp.node
// Definitions by: Michael Nahkies <https://github.com/mnahkies>, Ab Reitsma <https://github.com/abreits>, Nicolás Fantone <https://github.com/nfantone>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
declare module 'amqplib' {
import * as Promise from 'bluebird';
import * as events from 'events';
import shared = require('amqplib/properties');
import * as Promise from 'bluebird';
import * as events from 'events';
import { Replies, Options, Message } from './properties';
export * from './properties';
export import Replies = shared.Replies;
export import Options = shared.Options;
export import Message = shared.Message;
export interface Connection extends events.EventEmitter {
close(): Promise<void>;
createChannel(): Promise<Channel>;
createConfirmChannel(): Promise<ConfirmChannel>;
}
export interface Channel extends events.EventEmitter {
close(): Promise<void>;
assertQueue(queue: string, options?: Options.AssertQueue): Promise<Replies.AssertQueue>;
checkQueue(queue: string): Promise<Replies.AssertQueue>;
deleteQueue(queue: string, options?: Options.DeleteQueue): Promise<Replies.DeleteQueue>;
purgeQueue(queue: string): Promise<Replies.PurgeQueue>;
bindQueue(queue: string, source: string, pattern: string, args?: any): Promise<Replies.Empty>;
unbindQueue(queue: string, source: string, pattern: string, args?: any): Promise<Replies.Empty>;
assertExchange(exchange: string, type: string, options?: Options.AssertExchange): Promise<Replies.AssertExchange>;
checkExchange(exchange: string): Promise<Replies.Empty>;
deleteExchange(exchange: string, options?: Options.DeleteExchange): Promise<Replies.Empty>;
bindExchange(destination: string, source: string, pattern: string, args?: any): Promise<Replies.Empty>;
unbindExchange(destination: string, source: string, pattern: string, args?: any): Promise<Replies.Empty>;
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): Promise<Replies.Consume>;
cancel(consumerTag: string): Promise<Replies.Empty>;
get(queue: string, options?: Options.Get): Promise<Message | boolean>;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
nack(message: Message, allUpTo?: boolean, requeue?: boolean): void;
nackAll(requeue?: boolean): void;
reject(message: Message, requeue?: boolean): void;
prefetch(count: number, global?: boolean): Promise<Replies.Empty>;
recover(): Promise<Replies.Empty>;
}
export interface ConfirmChannel extends Channel {
publish(exchange:string, routingKey:string, content:Buffer, options?:Options.Publish, callback?:(err:any, ok:Replies.Empty) => void):boolean;
sendToQueue(queue:string, content:Buffer, options?:Options.Publish, callback?:(err:any, ok:Replies.Empty) => void):boolean;
waitForConfirms(): Promise<void>;
}
export function connect(url: string, socketOptions?: any): Promise<Connection>;
export interface Connection extends events.EventEmitter {
close(): Promise<void>;
createChannel(): Promise<Channel>;
createConfirmChannel(): Promise<ConfirmChannel>;
}
declare module 'amqplib/properties' {
export namespace Replies {
interface Empty {
}
interface AssertQueue {
queue: string;
messageCount: number;
consumerCount: number;
}
interface PurgeQueue {
messageCount: number;
}
interface DeleteQueue {
messageCount: number;
}
interface AssertExchange {
exchange: string;
}
interface Consume {
consumerTag: string;
}
}
export interface Channel extends events.EventEmitter {
close(): Promise<void>;
export namespace Options {
interface AssertQueue {
exclusive?: boolean;
durable?: boolean;
autoDelete?: boolean;
arguments?: any;
messageTtl?: number;
expires?: number;
deadLetterExchange?: string;
deadLetterRoutingKey?: string;
maxLength?: number;
maxPriority?: number;
}
interface DeleteQueue {
ifUnused?: boolean;
ifEmpty?: boolean;
}
interface AssertExchange {
durable?: boolean;
internal?: boolean;
autoDelete?: boolean;
alternateExchange?: string;
arguments?: any;
}
interface DeleteExchange {
ifUnused?: boolean;
}
interface Publish {
expiration?: string | number;
userId?: string;
CC?: string | string[];
assertQueue(queue: string, options?: Options.AssertQueue): Promise<Replies.AssertQueue>;
checkQueue(queue: string): Promise<Replies.AssertQueue>;
mandatory?: boolean;
persistent?: boolean;
deliveryMode?: boolean | number;
BCC?: string | string[];
deleteQueue(queue: string, options?: Options.DeleteQueue): Promise<Replies.DeleteQueue>;
purgeQueue(queue: string): Promise<Replies.PurgeQueue>;
contentType?: string;
contentEncoding?: string;
headers?: any;
priority?: number;
correlationId?: string;
replyTo?: string;
messageId?: string;
timestamp?: number;
type?: string;
appId?: string;
}
interface Consume {
consumerTag?: string;
noLocal?: boolean;
noAck?: boolean;
exclusive?: boolean;
priority?: number;
arguments?: any;
}
interface Get {
noAck?: boolean;
}
}
bindQueue(queue: string, source: string, pattern: string, args?: any): Promise<Replies.Empty>;
unbindQueue(queue: string, source: string, pattern: string, args?: any): Promise<Replies.Empty>;
export interface Message {
content: Buffer;
fields: any;
properties: any;
}
assertExchange(exchange: string, type: string, options?: Options.AssertExchange): Promise<Replies.AssertExchange>;
checkExchange(exchange: string): Promise<Replies.Empty>;
deleteExchange(exchange: string, options?: Options.DeleteExchange): Promise<Replies.Empty>;
bindExchange(destination: string, source: string, pattern: string, args?: any): Promise<Replies.Empty>;
unbindExchange(destination: string, source: string, pattern: string, args?: any): Promise<Replies.Empty>;
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): Promise<Replies.Consume>;
cancel(consumerTag: string): Promise<Replies.Empty>;
get(queue: string, options?: Options.Get): Promise<Message | boolean>;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
nack(message: Message, allUpTo?: boolean, requeue?: boolean): void;
nackAll(requeue?: boolean): void;
reject(message: Message, requeue?: boolean): void;
prefetch(count: number, global?: boolean): Promise<Replies.Empty>;
recover(): Promise<Replies.Empty>;
}
declare module 'amqplib/callback_api' {
import events = require('events');
import shared = require('amqplib/properties')
export interface ConfirmChannel extends Channel {
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean;
export import Replies = shared.Replies;
export import Options = shared.Options;
export import Message = shared.Message;
export interface Connection extends events.EventEmitter {
close(callback?: (err: any) => void): void;
createChannel(callback: (err: any, channel: Channel) => void): void;
createConfirmChannel(callback: (err: any, confirmChannel: ConfirmChannel) => void): void;
}
export interface Channel extends events.EventEmitter {
close(callback: (err: any) => void): void;
assertQueue(queue?: string, options?: Options.AssertQueue, callback?: (err: any, ok: Replies.AssertQueue) => void): void;
checkQueue(queue: string, callback?: (err: any, ok: Replies.AssertQueue) => void): void;
deleteQueue(queue: string, options?: Options.DeleteQueue, callback?: (err: any, ok: Replies.DeleteQueue) => void): void;
purgeQueue(queue: string, callback?: (err: any, ok: Replies.PurgeQueue) => void): void;
bindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
unbindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
assertExchange(exchange: string, type: string, options?: Options.AssertExchange, callback?: (err: any, ok: Replies.AssertExchange) => void): void;
checkExchange(exchange: string, callback?: (err: any, ok: Replies.Empty) => void): void;
deleteExchange(exchange: string, options?: Options.DeleteExchange, callback?: (err: any, ok: Replies.Empty) => void): void;
bindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
unbindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void;
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume, callback?: (err: any, ok: Replies.Consume) => void): void;
cancel(consumerTag: string, callback?: (err: any, ok: Replies.Empty) => void): void;
get(queue: string, options?: Options.Get, callback?: (err: any, ok: Message | boolean) => void): void;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
nack(message: Message, allUpTo?: boolean, requeue?: boolean): void;
nackAll(requeue?: boolean): void;
reject(message: Message, requeue?: boolean): void;
prefetch(count: number, global?: boolean): void;
recover(callback?: (err: any, ok: Replies.Empty) => void): void;
}
export interface ConfirmChannel extends Channel {
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean;
waitForConfirms(callback?: (err: any) => void): void;
}
export function connect(callback: (err: any, connection: Connection) => void): void;
export function connect(url: string, callback: (err: any, connection: Connection) => void): void;
export function connect(url: string, socketOptions: any, callback: (err: any, connection: Connection) => void): void;
waitForConfirms(): Promise<void>;
}
export function connect(url: string, socketOptions?: any): Promise<Connection>;
+88
View File
@@ -0,0 +1,88 @@
export namespace Replies {
interface Empty {
}
interface AssertQueue {
queue: string;
messageCount: number;
consumerCount: number;
}
interface PurgeQueue {
messageCount: number;
}
interface DeleteQueue {
messageCount: number;
}
interface AssertExchange {
exchange: string;
}
interface Consume {
consumerTag: string;
}
}
export namespace Options {
interface AssertQueue {
exclusive?: boolean;
durable?: boolean;
autoDelete?: boolean;
arguments?: any;
messageTtl?: number;
expires?: number;
deadLetterExchange?: string;
deadLetterRoutingKey?: string;
maxLength?: number;
maxPriority?: number;
}
interface DeleteQueue {
ifUnused?: boolean;
ifEmpty?: boolean;
}
interface AssertExchange {
durable?: boolean;
internal?: boolean;
autoDelete?: boolean;
alternateExchange?: string;
arguments?: any;
}
interface DeleteExchange {
ifUnused?: boolean;
}
interface Publish {
expiration?: string | number;
userId?: string;
CC?: string | string[];
mandatory?: boolean;
persistent?: boolean;
deliveryMode?: boolean | number;
BCC?: string | string[];
contentType?: string;
contentEncoding?: string;
headers?: any;
priority?: number;
correlationId?: string;
replyTo?: string;
messageId?: string;
timestamp?: number;
type?: string;
appId?: string;
}
interface Consume {
consumerTag?: string;
noLocal?: boolean;
noAck?: boolean;
exclusive?: boolean;
priority?: number;
arguments?: any;
}
interface Get {
noAck?: boolean;
}
}
export interface Message {
content: Buffer;
fields: any;
properties: any;
}
+1
View File
@@ -15,6 +15,7 @@
},
"files": [
"index.d.ts",
"callback_api.d.ts",
"amqplib-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "../tslint.json",
"rules": {
"no-empty-interface": false
}
}
+9 -1
View File
@@ -1280,7 +1280,15 @@ declare namespace angular {
// This corresponds to the "publicLinkFn" returned by $compile.
interface ITemplateLinkingFunction {
(scope: IScope, cloneAttachFn?: ICloneAttachFunction): JQuery;
(scope: IScope, cloneAttachFn?: ICloneAttachFunction, options?: ITemplateLinkingFunctionOptions): JQuery;
}
interface ITemplateLinkingFunctionOptions {
parentBoundTranscludeFn?: ITranscludeFunction,
transcludeControllers?: {
[controller: string]: { instance: IController }
},
futureParentElement?: JQuery
}
/**
+32
View File
@@ -0,0 +1,32 @@
import artyomjs = require('artyom.js');
// Get an unique ArtyomJS instance
let artyom = artyomjs.ArtyomBuilder.getInstance();
// Add a command (not smart)
artyom.addCommands({
description: 'Test command',
indexes: ['hello', 'hi'],
action: (i: number) => {
console.log('hello action');
}
});
// Add a smart command
artyom.addCommands({
description: 'Test command 2',
smart: true,
indexes: ['test *'],
action: (i: number, wildcard: string) => {
console.log('wildcard: ', wildcard);
}
});
// Get the browser voices
artyom.getVoices();
// Get all supported languages for Artyom
artyom.getLanguage();
// Get the artyom.js version
artyom.getVersion();
+513
View File
@@ -0,0 +1,513 @@
// Type definitions for artyom.js 1.0
// Project: https://github.com/sdkcarlos/artyom.js
// Definitions by: Sema García (José Manuel García) <https://github.com/semagarcia>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Extension of Window interface
*/
interface ArtyomWindow extends Window {
webkitSpeechRecognition: any;
SpeechRecognition: any;
SpeechSynthesisUtterance: any;
}
interface SpeechRecognition extends EventTarget {
grammars: SpeechGrammarList;
lang: string;
continuous: boolean;
interimResults: boolean;
maxAlternatives: number;
serviceURI: string;
start(): void;
stop(): void;
abort(): void;
onaudiostart: (ev: Event) => any;
onsoundstart: (ev: Event) => any;
onspeechstart: (ev: Event) => any;
onspeechend: (ev: Event) => any;
onsoundend: (ev: Event) => any;
onresult: (ev: SpeechRecognitionEvent) => any;
onnomatch: (ev: SpeechRecognitionEvent) => any;
onerror: (ev: SpeechRecognitionError) => any;
onstart: (ev: Event) => any;
onend: (ev: Event) => any;
}
interface SpeechRecognitionStatic {
prototype: SpeechRecognition;
new (): SpeechRecognition;
}
declare var SpeechRecognition: SpeechRecognitionStatic;
declare var webkitSpeechRecognition: SpeechRecognitionStatic;
interface SpeechRecognitionError extends Event {
error: string;
message: string;
}
interface SpeechRecognitionAlternative {
transcript: string;
confidence: number;
}
interface SpeechRecognitionResult {
length: number;
item(index: number): SpeechRecognitionAlternative;
[index: number]: SpeechRecognitionAlternative;
isFinal: boolean;
}
interface SpeechRecognitionResultList {
length: number;
item(index: number): SpeechRecognitionResult;
[index: number]: SpeechRecognitionResult;
}
interface SpeechRecognitionEvent extends Event {
resultIndex: number;
results: SpeechRecognitionResultList;
interpretation: any;
emma: Document;
}
interface SpeechGrammar {
src: string;
weight: number;
}
interface SpeechGrammarStatic {
prototype: SpeechGrammar;
new (): SpeechGrammar;
}
declare var SpeechGrammar: SpeechGrammarStatic;
declare var webkitSpeechGrammar: SpeechGrammarStatic;
interface SpeechGrammarList {
length: number;
item(index: number): SpeechGrammar;
[index: number]: SpeechGrammar;
addFromURI(src: string, weight: number): void;
addFromString(string: string, weight: number): void;
}
interface SpeechGrammarListStatic {
prototype: SpeechGrammarList;
new (): SpeechGrammarList;
}
declare var SpeechGrammarList: SpeechGrammarListStatic;
declare var webkitSpeechGrammarList: SpeechGrammarListStatic;
interface SpeechSynthesis extends EventTarget {
pending: boolean;
speaking: boolean;
paused: boolean;
onvoiceschanged: (ev: Event) => any;
speak(utterance: SpeechSynthesisUtterance): void;
cancel(): void;
pause(): void;
resume(): void;
getVoices(): SpeechSynthesisVoice[];
}
interface SpeechSynthesisGetter {
speechSynthesis: SpeechSynthesis;
}
declare var speechSynthesis: SpeechSynthesis;
interface SpeechSynthesisUtterance extends EventTarget {
text: string;
lang: string;
voice: SpeechSynthesisVoice;
volume: number;
rate: number;
pitch: number;
onstart: (ev: SpeechSynthesisEvent) => any;
onend: (ev: SpeechSynthesisEvent) => any;
onerror: (ev: SpeechSynthesisErrorEvent) => any;
onpause: (ev: SpeechSynthesisEvent) => any;
onresume: (ev: SpeechSynthesisEvent) => any;
onmark: (ev: SpeechSynthesisEvent) => any;
onboundary: (ev: SpeechSynthesisEvent) => any;
}
interface SpeechSynthesisUtteranceStatic {
prototype: SpeechSynthesisUtterance;
new (text?: string): SpeechSynthesisUtterance;
}
declare var SpeechSynthesisUtterance: SpeechSynthesisUtteranceStatic;
interface SpeechSynthesisEvent extends Event {
utterance: SpeechSynthesisUtterance;
charIndex: number;
elapsedTime: number;
name: string;
}
interface SpeechSynthesisErrorEvent extends SpeechSynthesisEvent {
error: string;
}
interface SpeechSynthesisVoice {
voiceURI: string;
name: string;
lang: string;
localService: boolean;
default: boolean;
}
declare namespace Artyom {
interface ArtyomDevice {
isChrome(): boolean;
isMobile(): boolean;
}
interface ArtyomBrowserVoiceObject {
default: boolean;
lang: string;
localService: false;
name: string;
voiceURI: string;
}
interface ArtyomConfigProperties {
/** Set the default language of artyom with this property */
lang?: string;
recognizing?: boolean;
/** Choose if should listen one command and then stops, or listening forever */
continuous?: boolean;
/** Moderates the speed with which Artyom talks (0 ~ 1) */
speed?: number;
/** Adjust the volume of the voice of artyom */
volume?: number;
/** If listen is equal to true the voice recognition will be started otherwise this property can be ignored */
listen: boolean;
/** Recognition mode: normal, quick, remote */
mode?: string;
/** Displays all the grammars recognized in the console */
debug: boolean;
helpers?: {
redirectRecognizedTextOutput: any;
remoteProcessorHandler: any;
lastSay: any;
};
/** Set a keyword that allows your command to be executed immediately when you say this word (Useful in noisy environments) */
executionKeyword?: string;
/** Set a keyword that allows to enable the command recognition automatically if this word is recognized while artyom is paused (artyom.dontObey) */
obeyKeyword?: string;
speaking?: boolean;
obeying?: boolean;
soundex?: boolean;
}
interface ArtyomCommand {
/** Triggers of the command */
indexes: string[];
/** Logic to execute when the command is triggered */
action: (i: number, wildcard?: string, full?: string) => void;
/** Description of the command */
description?: string;
/** Flag to specify is a command is either normal or smart */
smart?: boolean;
}
interface ArtyomFlags {
restartRecognition: boolean;
}
interface ArtyomRecognizer {
lang: string;
continuous: boolean;
interimResults: boolean;
start(): void;
stop(): void;
onstart(): void;
onresult(event: any): void;
onerror(event: any): void;
onend(): void;
}
export interface ArtyomJS {
/**
* Contains some basic information that artyom needs to know as the type of device and browser
* @see http://ourcodeworld.com/projects/projects-documentation/6/read-doc/artyom-device/artyom-js
*/
device: ArtyomDevice;
/**
* Object which provides the speech interface, and set some of its attributes and event handlers
*/
artyomWSR: ArtyomRecognizer;
/**
* Artyom can return inmediately the voices available in your browser.
* @see http://ourcodeworld.com/projects/projects-documentation/14/read-doc/artyom-getvoices/artyom-js
* @returns {Array}
*/
getVoices(): SpeechSynthesisVoice[];
/**
* Returns an array with all the available commands for artyom.
* @see http://ourcodeworld.com/projects/projects-documentation/10/read-doc/artyom-getavailablecommands/artyom-js
* @returns {Array}
*/
getAvailableCommands(): ArtyomCommand[];
/**
* Set up artyom for the application. This function will set the default language used by artyom
* or notice the user if artyom is not supported in the actual browser.
* @see http://ourcodeworld.com/projects/projects-documentation/15/read-doc/artyom-initialize/artyom-js
* @param {ArtyomConfigProperties} config
* @returns {Boolean}
*/
initialize(config: ArtyomConfigProperties): boolean;
/**
* Force artyom to stop listen even if is in continuos mode.
* @see http://ourcodeworld.com/projects/projects-documentation/9/read-doc/artyom-fatality/artyom-js
* @returns {Boolean}
*/
fatality(): boolean;
/**
* Add dinamically commands to artyom using. You can even add commands while artyom is active.
* @see http://ourcodeworld.com/projects/projects-documentation/4/read-doc/artyom-addcommands/artyom-js
* @param {ArtyomCommand | Array[ArtyomCommand]} newCommand
* @returns {Boolean}
*/
addCommands(newCommand: ArtyomCommand | ArtyomCommand[]): boolean;
/**
* Remove the commands of artyom with indexes that matches with the given text.
* @see http://ourcodeworld.com/projects/projects-documentation/19/read-doc/artyom-removecommands/artyom-js
* @param {string} identifier
* @returns {Array}
*/
removeCommands(identifier: string): number[];
/**
* Removes all the added commands of artyom.
* @see http://ourcodeworld.com/projects/projects-documentation/7/read-doc/artyom-emptycommands/artyom-js
* @returns {Array}
*/
emptyCommands(): ArtyomCommand[];
/**
* Stops the actual and pendings messages that artyom have to say.
* @see http://ourcodeworld.com/projects/projects-documentation/23/read-doc/artyom-shutup/artyom-js
*/
shutUp(): void;
/**
* Returns an object with the actual properties of artyom.
* @see http://ourcodeworld.com/projects/projects-documentation/12/read-doc/artyom-getproperties/artyom-js
* @returns {ArtyomConfigProperties}
*/
getProperties(): ArtyomConfigProperties;
/**
* Create a listener when an artyom action is called.
* @see http://ourcodeworld.com/projects/projects-documentation/24/read-doc/artyom-when/artyom-js
*/
when(event: any, action: any): any;
/**
* Returns the code language of artyom according to initialize function.
* @see http://ourcodeworld.com/projects/projects-documentation/11/read-doc/artyom-getlanguage/artyom-js
* @returns {String} Language
*/
getLanguage(): string;
/**
* Talks a text according to the given parameters (private function).
* @param {String} text Text to be spoken
* @param {Int} actualChunk Number of chunk of the
* @param {Int} totalChunks
* @param {any} callbacks
*/
artyomTalk(text: any, actualChunk: any, totalChunks: any, callbacks: any): any;
/**
* Splits a string into an array of strings with a limited size (chunk_length).
* @param {String} input text to split into chunks
* @param {Integer} chunk_length limit of characters in every chunk
*/
splitStringByChunks(input: any, chunk_length: any): string[];
/**
* Process the given text into chunks and execute the private function artyom_talk.
* @param {String} message Text to be spoken
* @param {Object} callbacks { onStart, onEnd }
* @see http://ourcodeworld.com/projects/projects-documentation/20/read-doc/artyom-say/artyom-js
*/
say(message: any, callbacks: any): void;
/**
* Repeats the last sentence that artyom said. Useful in noisy environments.
* @param {Boolean} returnObject If set to true, an object with the text and the timestamp when was executed will be returned.
* @see http://ourcodeworld.com/projects/projects-documentation/25/read-doc/artyom-repeatlastsay/artyom-js
*/
repeatLastSay(returnObject: any): void;
/**
* Verify if the browser supports speechSynthesis.
* @see http://ourcodeworld.com/projects/projects-documentation/40/read-doc/artyom-speechsupported/artyom-js
* @returns {Boolean}
*/
speechSupported(): boolean;
/**
* Verify if the browser supports webkitSpeechRecognition.
* @see http://ourcodeworld.com/projects/projects-documentation/39/read-doc/artyom-recognizingsupported/artyom-js
* @returns {Boolean}
*/
recognizingSupported(): boolean;
/**
* Simulate a voice command via JS.
* @see http://ourcodeworld.com/projects/projects-documentation/22/read-doc/artyom-simulateinstruction/artyom-js
* @param {string} sentence
* @returns {Boolean}
*/
simulateInstruction(sentence: string): boolean;
/**
* Returns an object with data of the matched element.
* @param {string} voiceCommand
* @returns {Object | Function}. There is a result field when the function should return a boolean value.
*/
artyomExecute(voiceCommand: string): any;
/**
* Displays a message in the console if the artyom propery DEBUG is set to true.
* @param {string} error The error to be debugged
* @param {string} traceLevel Error level: { error | warn | info }
* @see http://ourcodeworld.com/projects/projects-documentation/38/read-doc/artyom-debug/artyom-js
*/
debug(stringEvent: string, traceLevel: string): void;
/**
* Allows to retrieve the recognized spoken text of artyom and do something with it everytime something is recognized.
* @param {Function} action
* @returns {Boolean}
*/
redirectRecognizedTextOutput(action: () => void): boolean;
/**
* Says a random quote and returns it's object.
* @param data
*/
sayRandom(data: any): any;
/**
* Artyom provide an easy way to create a dictation for your user. Just create an instance and start and stop when you want.
*/
newDictation(settings: any): any;
/**
* A voice prompt will be executed.
*/
newPrompt(config: any): any;
/**
* Artyom awaits for orders when this function is executed. If artyom gets a first parameter the instance will be stopped.
*/
artyomHey(): any;
/**
* This function will return the webkitSpeechRecognition object used by artyom retrieve it only to debug on it or get some
* values, do not make changes directly.
*/
getNativeApi(): any;
/**
* This function returns a boolean according to the SpeechRecognition status if artyom is listening, will return true.
* Note: This is not a feature of SpeechRecognition, therefore this value hangs on the fiability of the onStart and onEnd
* events of the SpeechRecognition
* @returns {Boolean}
*/
isRecognizing(): boolean;
/**
* This function returns a boolean according to the speechSynthesis status if artyom is speaking, will return true.
* Note: This is not a feature of speechSynthesis, therefore this value hangs on the fiability of the onStart and onEnd
* events of the speechSynthesis.
* @returns {Boolean}
*/
isSpeaking(): boolean;
/**
* The SpeechSynthesisUtterance objects are stored in the artyom_garbage_collector variable to prevent the wrong behaviour
* of artyom.say. Use this method to clear all spoken SpeechSynthesisUtterance unused objects.
* @returns {Boolean}
*/
clearGarbageCollection(): any;
/**
* Returns the SpeechSynthesisUtterance garbageobjects.
*/
getGarbageCollection(): any;
/**
* Pause the processing of commands. Artyom still listening in the background and it can be resumed after a couple of seconds.
* @returns {Boolean}
*/
dontObey(): any;
/**
* Allow artyom to obey commands again.
* @returns {Boolean}
*/
obey(): any;
/**
* A boolean to check if artyom is obeying commands or not.
* @returns {Boolean}
*/
isObeying(): boolean;
/**
* Process the recognized text if artyom is active in remote mode.
* @returns {Boolean}
*/
remoteProcessorService(action: any): any;
/**
* Returns a string with the actual version of Artyom script.
* @returns {String}
*/
getVersion(): string;
/**
* Add commands like an artisan. If you use artyom for simple
* tasks then probably you don't like to write a lot to achieve it.
* Use the artisan syntax to write less, but with the same accuracy.
* @disclaimer Not a promise-based implementation, just syntax.
* @returns {Object}
*/
on(indexes: any, smart: any): any;
}
/**
* ArtyomBuilder bla, bla...
*/
export class ArtyomBuilder {
/**
* Method to bla, bla, bla...
*/
static getInstance(): ArtyomJS
}
}
//tslint:disable-next-line:export-just-namespace
export = Artyom;
export as namespace Artyom;
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"noImplicitThis": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"artyom.js-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+2
View File
@@ -35,6 +35,7 @@ interface Auth0ClientOptions {
clientID: string;
callbackURL: string;
callbackOnLocationHash?: boolean;
responseType?: string;
domain: string;
forceJSONP?: boolean;
}
@@ -87,6 +88,7 @@ interface Auth0DecodedHash {
idToken: string;
profile: Auth0UserProfile;
state: any;
error: string;
}
interface Auth0PopupOptions {
+4 -1
View File
@@ -62,4 +62,7 @@ context.succeed(str);
context.succeed(anyObj);
context.succeed(str, anyObj);
context.fail(error);
context.fail(str);
context.fail(str);
/* Handler */
let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => {};
+14 -4
View File
@@ -1,6 +1,6 @@
// Type definitions for AWS Lambda
// Project: http://docs.aws.amazon.com/lambda
// Definitions by: James Darbyshire <https://github.com/darbio/aws-lambda-typescript>, Michael Skarum <https://github.com/skarum>, Stef Heyenrath <https://github.com/StefH/DefinitelyTyped>
// Definitions by: James Darbyshire <https://github.com/darbio/aws-lambda-typescript>, Michael Skarum <https://github.com/skarum>, Stef Heyenrath <https://github.com/StefH/DefinitelyTyped>, Toby Hede <https://github.com/tobyhede>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Context
@@ -17,7 +17,7 @@ interface Context {
logStreamName: string;
identity?: CognitoIdentity;
clientContext?: ClientContext;
// Functions
getRemainingTimeInMillis(): number;
@@ -28,7 +28,7 @@ interface Context {
fail(message: string): void;
succeed(message: string): void;
succeed(object: any): void;
succeed(message: string, object: any): void;
succeed(message: string, object: any): void;
}
interface CognitoIdentity {
@@ -58,6 +58,16 @@ interface ClientContextEnv {
locale: string;
}
/**
* AWS Lambda handler function.
* http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
*
* @param event – event data.
* @param context – runtime information of the Lambda function that is executing.
* @param callback – optional callback to return information to the caller, otherwise return value is null.
*/
export type Handler = (event: any, context: Context, callback?: Callback) => void;
/**
* Optional callback parameter.
* http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
@@ -67,4 +77,4 @@ interface ClientContextEnv {
*/
export type Callback = (error?: Error, result?: any) => void;
export as namespace AWSLambda;
export as namespace AWSLambda;
+1
View File
@@ -5,3 +5,4 @@ import Boom = require('boom');
Boom.create(500, 'Internal server error', { timestamp: Date.now() });
Boom.wrap(new Error('test'), 400);
Boom.badRequest('Invalid cookies');
Boom.unauthorized() as Error;
+1
View File
@@ -16,6 +16,7 @@ declare namespace Boom {
isServer: boolean;
message: string;
output: Output;
name: string;
}
export interface Output {
+3 -6
View File
@@ -1,7 +1,7 @@
import * as bson from 'bson';
let BSON = new bson.BSONPure.BSON();
let Long = bson.BSONPure.Long;
let BSON = new bson.BSON();
let Long = bson.Long;
let doc = {long: Long.fromNumber(100)}
@@ -13,9 +13,6 @@ console.log("data:", data);
let doc_2 = BSON.deserialize(data);
console.log("doc_2:", doc_2);
BSON = new bson.BSONNative.BSON();
BSON = new bson.BSON();
data = BSON.serialize(doc);
doc_2 = BSON.deserialize(data);
+77 -87
View File
@@ -1,96 +1,86 @@
// Type definitions for bson 0.4
// Type definitions for bson 1.0
// Project: https://github.com/mongodb/js-bson
// Definitions by: Hiroki Horiuchi <https://github.com/horiuchi/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node"/>
declare namespace bson {
export namespace BSONPure {
export interface DeserializeOptions {
/** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. */
evalFunctions?: boolean;
/** {Boolean, default:false}, cache evaluated functions for reuse. */
cacheFunctions?: boolean;
/** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. */
cacheFunctionsCrc32?: boolean;
/** {Boolean, default:false}, deserialize Binary data directly into node.js Buffer object. */
promoteBuffers?: boolean;
}
export class BSON {
/**
* @param {Object} object the Javascript object to serialize.
* @param {Boolean} checkKeys the serializer will check if keys are valid.
* @param {Boolean} asBuffer return the serialized object as a Buffer object (ignore).
* @param {Boolean} serializeFunctions serialize the javascript functions (default:false)
* @return {Buffer} returns a TypedArray or Array depending on what your browser supports
*/
serialize(object: any, checkKeys?: boolean, asBuffer?: boolean, serializeFunctions?: boolean): Buffer;
deserialize(buffer: Buffer, options?: DeserializeOptions, isArray?: boolean): any;
}
export class Binary {
static SUBTYPE_DEFAULT: number;
static SUBTYPE_FUNCTION: number;
static SUBTYPE_BYTE_ARRAY: number;
static SUBTYPE_UUID_OLD: number;
static SUBTYPE_UUID: number;
static SUBTYPE_MD5: number;
static SUBTYPE_USER_DEFINED: number;
constructor(buffer: Buffer, subType?: number);
}
export class Code {
constructor(code: string | Function, scope?: any);
}
export class DBRef {
constructor(namespace: string, oid: ObjectID, db?: string);
}
export class Double {
constructor (value: number);
}
export class Long {
static fromInt(i: number): Long;
static fromNumber(n: number): Long;
static fromBits(lowBits: number, highBits: number): Long;
static fromString(s: string, opt_radix?: number): Long;
constructor(low: number, high: number);
}
export class MaxKey {
constructor();
}
export class MinKey {
constructor();
}
export class ObjectId {
static createPk(): ObjectId;
static createFromTime(time: number): ObjectId;
static createFromHexString(hexString: string): ObjectId;
static isValid(id: number | string | ObjectId): boolean;
constructor(id?: number | string | ObjectId);
}
export type ObjectID = ObjectId;
export class BSONRegExp {
constructor(pattern: string, options: string);
}
export class Symbol {
constructor(value: string);
}
export class Timestamp {
static fromInt(i: number): Timestamp;
static fromNumber(n: number): Timestamp;
static fromBits(lowBits: number, highBits: number): Timestamp;
static fromString(s: string, opt_radix?: number): Timestamp;
constructor(low: number, high: number);
}
}
export let BSONNative: typeof BSONPure;
export interface DeserializeOptions {
/** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. */
evalFunctions?: boolean;
/** {Boolean, default:false}, cache evaluated functions for reuse. */
cacheFunctions?: boolean;
/** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. */
cacheFunctionsCrc32?: boolean;
/** {Boolean, default:false}, deserialize Binary data directly into node.js Buffer object. */
promoteBuffers?: boolean;
}
export class BSON {
/**
* @param {Object} object the Javascript object to serialize.
* @param {Boolean} checkKeys the serializer will check if keys are valid.
* @param {Boolean} asBuffer return the serialized object as a Buffer object (ignore).
* @param {Boolean} serializeFunctions serialize the javascript functions (default:false)
* @return {Buffer} returns a TypedArray or Array depending on what your browser supports
*/
serialize(object: any, checkKeys?: boolean, asBuffer?: boolean, serializeFunctions?: boolean): Buffer;
deserialize(buffer: Buffer, options?: DeserializeOptions, isArray?: boolean): any;
}
export = bson;
export class Binary {
static SUBTYPE_DEFAULT: number;
static SUBTYPE_FUNCTION: number;
static SUBTYPE_BYTE_ARRAY: number;
static SUBTYPE_UUID_OLD: number;
static SUBTYPE_UUID: number;
static SUBTYPE_MD5: number;
static SUBTYPE_USER_DEFINED: number;
constructor(buffer: Buffer, subType?: number);
}
export class Code {
constructor(code: string | Function, scope?: any);
}
export class DBRef {
constructor(namespace: string, oid: ObjectID, db?: string);
}
export class Double {
constructor (value: number);
}
export class Long {
static fromInt(i: number): Long;
static fromNumber(n: number): Long;
static fromBits(lowBits: number, highBits: number): Long;
static fromString(s: string, opt_radix?: number): Long;
constructor(low: number, high: number);
}
export class MaxKey {
constructor();
}
export class MinKey {
constructor();
}
export class ObjectId {
static createPk(): ObjectId;
static createFromTime(time: number): ObjectId;
static createFromHexString(hexString: string): ObjectId;
static isValid(id: number | string | ObjectId): boolean;
constructor(id?: number | string | ObjectId);
}
export type ObjectID = ObjectId;
export class BSONRegExp {
constructor(pattern: string, options: string);
}
export class Symbol {
constructor(value: string);
}
export class Timestamp {
static fromInt(i: number): Timestamp;
static fromNumber(n: number): Timestamp;
static fromBits(lowBits: number, highBits: number): Timestamp;
static fromString(s: string, opt_radix?: number): Timestamp;
constructor(low: number, high: number);
}
+66 -96
View File
@@ -1,119 +1,89 @@
// Type definitions for bufferstream v0.6.2
// Type definitions for bufferstream 0.6
// Project: https://github.com/dodo/node-bufferstream
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
declare module 'bufferstream' {
import stream = require('stream');
import stream = require('stream');
export = BufferStream;
export = BufferStream;
class BufferStream extends stream.Duplex {
constructor(options?: BufferStream.Opts);
declare class BufferStream extends stream.Duplex {
constructor(options?: BufferStream.Opts);
/*
different buffer behaviors can be triggered by size:
/*
different buffer behaviors can be triggered by size:
none when output drains, bufferstream drains too
flexible buffers everthing that it gets and not piping out
<number> TODO buffer has given size. buffers everthing until buffer is full. when buffer is full then the stream will drain
*/
setSize(size: string): void; // can be one of ['none', 'flexible', <number>]
setSize(size: number): void; // can be one of ['none', 'flexible', <number>]
/*
enables stream buffering default
*/
enable(): void;
/*
flushes buffer and disables stream buffering. BufferStream now pipes all data as long as the output accepting data. when the output is draining BufferStream will buffer all input temporary.
none when output drains, bufferstream drains too
flexible buffers everthing that it gets and not piping out
<number> TODO buffer has given size. buffers everthing until buffer is full. when buffer is full then the stream will drain
*/
setSize(size: string | number): void; // can be one of ['none', 'flexible', <number>]
/*
enables stream buffering default
*/
enable(): void;
/*
flushes buffer and disables stream buffering. BufferStream now pipes all data as long as the output accepting data. when the output is draining BufferStream will buffer all input temporary.
token[s] buffer splitters (should be String or Buffer)
token[s] buffer splitters (should be String or Buffer)
disables given tokens. wont flush until no splitter tokens are left.
*/
disable(): void;
disable(token: string, ...tokens: string[]): void;
disable(tokens: string[]): void; // Array
disable(token: Buffer, ...tokens: Buffer[]): void;
disable(tokens: Buffer[]): void; // Array
/*
each time BufferStream finds a splitter token in the input data it will emit a split event. this also works for binary data.
disables given tokens. wont flush until no splitter tokens are left.
*/
disable(tokens?: string[] | Buffer[]): void;
disable(token: string, ...tokens: string[]): void;
disable(token: Buffer, ...tokens: Buffer[]): void;
/*
each time BufferStream finds a splitter token in the input data it will emit a split event. this also works for binary data.
token[s] buffer splitters (should be String or Buffer)
*/
split(token: string, ...tokens: string[]): void;
split(tokens: string[]): void; // Array
split(token: Buffer, ...tokens: Buffer[]): void;
split(tokens: Buffer[]): void; // Array
/*
returns Buffer.
*/
getBuffer(): Buffer;
/*
returns Buffer.
*/
buffer: Buffer;
/*
shortcut for buffer.toString()
*/
toString(): string;
/*
shortcut for buffer.length
*/
length: number;
}
namespace BufferStream {
export interface Opts {
/*
default encoding for writing strings
*/
encoding?: string;
/*
if true and the source is a child_process the stream will block the entire process (timeouts wont work anymore, but splitting and listening on data still works, because they work sync)
*/
blocking?: boolean;
/*
defines buffer level or sets buffer to given size (see ↓setSize for more)
*/
size?: any;
/*
immediately call disable
*/
disabled?: boolean;
/*
short form for:
split(token, function (chunk) {emit('data', chunk)})
*/
// String or Buffer
split?: any;
}
export var fn: {warn: boolean};
}
token[s] buffer splitters (should be String or Buffer)
*/
split(tokens: string[] | Buffer[]): void;
split(token: string, ...tokens: string[]): void;
split(token: Buffer, ...tokens: Buffer[]): void;
/*
returns Buffer.
*/
getBuffer(): Buffer;
/*
returns Buffer.
*/
buffer: Buffer;
/*
shortcut for buffer.toString()
*/
toString(): string;
/*
shortcut for buffer.length
*/
length: number;
}
declare namespace BufferStream {
declare module 'bufferstream/postbuffer' {
import http = require('http');
import BufferStream = require('bufferstream');
class PostBuffer extends BufferStream {
export interface Opts {
/*
for if you want to get all the post data from a http server request and do some db reqeust before.
http client buffer
default encoding for writing strings
*/
constructor(req: http.IncomingMessage);
encoding?: string;
/*
set a callback to get all post data from a http server request
if true and the source is a child_process the stream will block the entire process (timeouts wont work anymore, but splitting and listening on data still works, because they work sync)
*/
onEnd(callback: (data: any) => void): void;
blocking?: boolean;
/*
pumps data into another stream to allow incoming streams given options will be passed to Stream.pipe
defines buffer level or sets buffer to given size (see ↓setSize for more)
*/
pipe(stream: NodeJS.WritableStream, options?: BufferStream.Opts): NodeJS.ReadableStream;
size?: any;
/*
immediately call disable
*/
disabled?: boolean;
/*
short form for:
split(token, function (chunk) {emit('data', chunk)})
*/
// String or Buffer
split?: any;
}
export = PostBuffer;
export var fn: {warn: boolean};
}
+12
View File
@@ -0,0 +1,12 @@
import http = require('http');
import BufferStream = require('./index');
export = PostBuffer;
declare class PostBuffer extends BufferStream {
/** for if you want to get all the post data from a http server request and do some db request before. */
constructor(req: http.IncomingMessage);
/** set a callback to get all post data from a http server request */
onEnd(callback: (data: any) => void): void;
/** pumps data into another stream to allow incoming streams given options will be passed to Stream.pipe */
pipe(stream: NodeJS.WritableStream, options?: BufferStream.Opts): NodeJS.ReadableStream;
}
+1
View File
@@ -15,6 +15,7 @@
},
"files": [
"index.d.ts",
"postbuffer.d.ts",
"bufferstream-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+18
View File
@@ -389,3 +389,21 @@ function test_htmlWriter() {
writer.lineBreak();
writer.setRules('img', {breakBeforeOpen: true, breakAfterOpen: true});
}
function test_sharedSpace() {
CKEDITOR.inline('content', {
removePlugins: 'maximize,resize',
sharedSpaces: {
top: 'someElementId',
bottom: document.getElementById('anotherId')
}
});
CKEDITOR.inline('content', {
sharedSpaces: { }
});
}
function test_specifying_editor_path() {
window.CKEDITOR_BASEPATH = '/ckeditor/';
}
+11 -1
View File
@@ -5,6 +5,10 @@
// WORK-IN-PROGRESS: Any contribution support welcomed.
// See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/1827 for more informations.
interface Window {
CKEDITOR_BASEPATH: string;
}
declare namespace CKEDITOR {
// Config options
@@ -784,7 +788,7 @@ declare namespace CKEDITOR {
scayt_uiTabs?: string;
scayt_userDictionaryName?: string;
sharedSpaces?: Object;
sharedSpaces?: CKEDITOR.sharedSpace;
shiftEnterMode?: number;
skin?: string;
smiley_columns?: number;
@@ -834,6 +838,12 @@ declare namespace CKEDITOR {
}
interface sharedSpace {
top?: string | HTMLElement;
bottom?: string | HTMLElement;
}
interface style {
}
+28
View File
@@ -0,0 +1,28 @@
import * as clamp from 'clamp-js';
const lineElement: HTMLElement = document.createElement('div');
lineElement.style.setProperty('font-size', '3px');
lineElement.style.setProperty('line-height', '5px');
lineElement.style.setProperty('height', '11px');
lineElement.style.setProperty('width', '15px');
const newtext: Text = document.createTextNode('Lorem ipsum, dolor sit amet.');
lineElement.appendChild(newtext);
const clampFromElement = clamp(lineElement);
const clampFromDefaults = clamp(lineElement, {
clamp: 'auto',
useNativeClamp: true,
splitOnChars: ['.', '-', '–', '—', ' '],
animate: false,
truncationChar: '…',
truncationHTML: null
});
const clampWithOptions = clamp(lineElement, {
clamp: 1,
useNativeClamp: false,
splitOnChars: [','],
animate: true,
truncationChar: '--',
truncationHTML: '<span></span>'
});
Vendored Executable
+25
View File
@@ -0,0 +1,25 @@
// Type definitions for clamp-js 0.7
// Project: https://github.com/xavi160/Clamp.js
// Definitions by: Sebastiaan de Rooij <https://github.com/Hikariii/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace clamp {
export interface ClampOptions {
clamp?: number|string;
useNativeClamp?: boolean;
splitOnChars?: string[];
animate?: boolean;
truncationChar?: string;
truncationHTML?: string | null;
}
export interface ClampResponse {
'original': string;
'clamped': string;
}
}
declare function clamp(element: HTMLElement, options?: clamp.ClampOptions): clamp.ClampResponse;
export = clamp;
export as namespace clamp;
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"clamp-js-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+10
View File
@@ -55,5 +55,15 @@ function tests_simple() {
}
}, cb);
$('#reportrange').daterangepicker({
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()]
},
showCustomRangeLabel: false
}, cb);
});
}
+4
View File
@@ -125,6 +125,10 @@ declare namespace daterangepicker {
* Normally, if you use the ranges option to specify pre- defined date ranges, calendars for choosing a custom date range are not shown until the user clicks "Custom Range".When this option is set to true, the calendars for choosing a custom date range are always shown instead.
*/
alwaysShowCalendars?: boolean;
/**
* Whether to show the 'Custom Range' label or just pre-defined ranges
*/
showCustomRangeLabel?: boolean;
}
interface Locale {
+2 -2
View File
@@ -22,9 +22,9 @@ declare namespace deepDiff {
(path: string[], key: string): boolean;
}
interface IDeepDiff {
diff(): IDiff;
interface IDeepDiff {
diff(lhs: Object, rhs: Object, prefilter?: IPrefilter, acc?: IAccumulator): IDiff[];
diff(): IDiff;
observableDiff(lhs: Object, rhs: Object, changes: Function, prefilter?: IPrefilter, path?: string[], key?: string, stack?: Object[]): void;
applyDiff(target: Object, source: Object, filter: Function): void;
applyChange(target: Object, source: Object, change: IDiff): void;
+5 -12
View File
@@ -1,21 +1,14 @@
// Type definitions for del v2.2.0
// Type definitions for del 2.2
// Project: https://github.com/sindresorhus/del
// Definitions by: Asana <https://asana.com>, Aya Morisawa <https://github.com/AyaMorisawa>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="glob" />
import glob = require("glob");
declare function Del(pattern: string): Promise<string[]>;
declare function Del(pattern: string, options: Del.Options): Promise<string[]>;
declare function del(patterns: string | string[], options?: del.Options): Promise<string[]>;
declare function Del(patterns: string[]): Promise<string[]>;
declare function Del(patterns: string[], options: Del.Options): Promise<string[]>;
declare namespace Del {
function sync(pattern: string, options?: Options): string[];
function sync(patterns: string[], options?: Options): string[];
declare namespace del {
function sync(patterns: string | string[], options?: Options): string[];
interface Options extends glob.IOptions {
force?: boolean;
@@ -23,4 +16,4 @@ declare namespace Del {
}
}
export = Del;
export = del;
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+11
View File
@@ -32,6 +32,17 @@ client.indices.delete({
}, function (error) {
});
client.deleteByQuery({
index: 'test_index',
type: 'test_type',
body: {
query: {
}
}
}).then(function (response) {
}, function (error) {
});
client.create({
index: 'index',
type: 'type'
+36 -11
View File
@@ -1,6 +1,6 @@
// Type definitions for elasticsearch 5.0
// Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html
// Definitions by: Casper Skydt <https://github.com/CasperSkydt>, Blake Smith <https://github.com/bfsmith>, Dave Dunkin <https://github.com/ddunkin>, Jeffery Grajkowski <https://github.com/pushplay>
// Definitions by: Casper Skydt <https://github.com/CasperSkydt>, Blake Smith <https://github.com/bfsmith>, Dave Dunkin <https://github.com/ddunkin>, Jeffery Grajkowski <https://github.com/pushplay>, Margus Lamp <https://github.com/mlamp>, Ahmad Ferdous Bin Alam <https://github.com/ahmadferdous>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module Elasticsearch {
@@ -143,6 +143,7 @@ declare module Elasticsearch {
export type VersionType = "internal" | "external" | "external_gte" | "force";
export type ExpandWildcards = "open" | "closed" | "none" | "all";
export type DefaultOperator = "AND" | "OR";
export type Conflicts = "abort" | "proceed";
export interface BulkIndexDocumentsParams extends GenericParams {
waitForActiveShards?: string;
@@ -234,16 +235,40 @@ declare module Elasticsearch {
}
export interface DeleteDocumentByQueryParams extends GenericParams {
waitForActiveShards?: string;
parent?: string;
refresh?: Refresh;
routing?: string;
timeout?: TimeSpan;
analyzer?: string;
analyzeWildcard?: boolean;
defaultOperator?: DefaultOperator;
df?: string;
from?: number;
ignoreUnavailable?: boolean;
allowNoIndices?: boolean;
conflicts?: Conflicts;
expandWildcards?: ExpandWildcards;
lenient?: boolean;
lowercaseExpandedTerms?: boolean;
preference?: string;
q?: string;
routing?: string | string[] | boolean;
scroll?: string;
searchType?: "query_then_fetch" | "dfs_query_then_fetch";
searchTimeout?: TimeSpan;
size?: number;
sort?: NameList;
_source?: NameList;
_sourceExclude?: NameList;
_sourceInclude?: NameList;
terminateAfter?: number;
stats?: string | string[] | boolean;
version?: number;
versionType?: VersionType;
index: string;
type: string;
id: string;
requestCache?: boolean;
refresh?: Refresh;
timeout?: TimeSpan;
waitForActiveShards?: string;
scrollSize?: number;
waitForCompletion?: boolean;
requestsPerSecond?: number;
index?: string;
type?: string;
}
export interface DeleteDocumentByQueryResponse {
@@ -710,7 +735,7 @@ declare module Elasticsearch {
from?: number;
ignoreUnavailable?: boolean;
allowNoIndices?: boolean;
conflicts?: "abort" | "proceed";
conflicts?: Conflicts;
expandWildcards?: ExpandWildcards;
lenient?: boolean;
lowercaseExpandedTerms?: boolean;
+1
View File
@@ -59,6 +59,7 @@ declare namespace e {
interface Handler extends core.Handler { }
interface IRoute extends core.IRoute { }
interface IRouter<T> extends core.IRouter { }
interface IRouterHandler<T> extends core.IRouterHandler<T> { }
interface IRouterMatcher<T> extends core.IRouterMatcher<T> { }
interface MediaType extends core.MediaType { }
interface NextFunction extends core.NextFunction { }
+3 -2
View File
@@ -9,6 +9,7 @@ interface MyTaskData {
interface MyOptions {
sourceRoot: string;
repeat: number;
}
// exports should work same as module.exports
@@ -35,8 +36,8 @@ exports = (grunt: IGrunt) => {
grunt.registerTask('default', ['uglify']);
grunt.registerMultiTask('mytask', "short description", function() {
var currenttask: grunt.task.IMultiTask<MyTaskData> = this;
var options = currenttask.options<MyOptions>({
var currenttask = this;
var options = currenttask.options({
sourceRoot: "default"
});
var valid = false;
+203 -203
View File
File diff suppressed because it is too large Load Diff
+5 -1
View File
@@ -716,7 +716,11 @@ export interface IRouteAdditionalConfigurationOptions {
/** ONLY WHEN ADDING NEW ROUTES (not when setting defaults).
*route tags used for generating documentation (array of strings).
*/
tags?: string[]
tags?: string[];
/** Enable logging of routes
*/
log?: boolean;
}
/**
+6
View File
@@ -805,6 +805,12 @@ declare namespace Highcharts {
* @since 1.2.0
*/
startOnTick?: boolean;
/**
* Solid gauge series only. Color stops for the solid gauge.
* Use this in cases where a linear gradient between a minColor and maxColor is not sufficient.
* The stops is an array of tuples, where the first item is a float between 0 and 1 assigning the relative position in the gradient, and the second item is the color.
*/
stops?: [number, string][];
/**
* The amount of ticks to draw on the axis. This opens up for aligning the ticks of multiple charts or panes within
* a chart. This option overrides the tickPixelInterval option.
+13
View File
@@ -0,0 +1,13 @@
import { Reader, Config, createConnection } from "hiredis";
const socket = createConnection(6379, "localhost");
socket.write("INFO");
const reader = new Reader({ return_buffers: false });
// Data comes in
reader.feed("$5\r\nhello\r\n");
// Reply comes out
reader.get(); // => "hello"
+20
View File
@@ -0,0 +1,20 @@
// Type definitions for hiredis 0.5
// Project: http://github.com/redis/hiredis-node
// Definitions by: Titan <https://github.com/titan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import * as net from "net";
export interface Config {
return_buffers: boolean;
}
export class Reader {
constructor(config?: Config);
feed(reply: string | Buffer): void;
get(): string | Buffer;
}
export function createConnection(port: number, host: string): net.Socket;
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"strictNullChecks": true,
"noImplicitThis": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"hiredis-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
@@ -21,6 +21,7 @@ isBool(has);
const get = link.get('title', 'Example Website');
isReference(get);
const rel = link.rel('alternate');
rel['title'] !== 'bar';
isReference(rel);
const set = link.set({ rel: 'next', uri: 'http://example.com/next' });
isReference(set);
+1 -1
View File
@@ -6,7 +6,7 @@
export interface Reference {
uri: string;
rel: string;
title?: string;
[index: string]: string;
}
export interface Link {
refs: Reference[];
+13 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for intro.js 2.0
// Type definitions for intro.js 2.4
// Project: https://github.com/usablica/intro.js
// Definitions by: Maxime Fabre <https://github.com/anahkiasen/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -10,6 +10,12 @@ declare namespace IntroJs {
position?: string;
}
interface Hint {
hint: string;
element?: string|HTMLElement|Element;
hintPosition?: string;
}
interface Options {
nextLabel?: string;
prevLabel?: string;
@@ -32,6 +38,7 @@ declare namespace IntroJs {
hintPosition?: string;
hintButtonLabel?: string;
steps?: Step[];
hints?: Hint[];
}
interface IntroJs {
@@ -56,6 +63,11 @@ declare namespace IntroJs {
addHints(): IntroJs;
showHint(stepId: number): IntroJs;
showHints(): IntroJs;
hideHint(stepId: number): IntroJs;
hideHints(): IntroJs;
onhintsadded(callback: Function): IntroJs;
onhintclick(callback: (hintElement: HTMLElement, item: Step, stepId: number) => any): IntroJs;
onhintclose(callback: (stepId: number) => any): IntroJs;
+16
View File
@@ -35,6 +35,18 @@ intro.setOptions({
element: '#step5',
intro : 'Get it, use it.'
}
],
hints: [
{
element: '#step1',
hint: 'This is a hint',
hintPosition: 'middle-right'
},
{
element: document.querySelectorAll('#step2')[0] as HTMLElement,
hint: 'This is another hint',
hintPosition: 'top-left'
}
]
});
@@ -69,6 +81,10 @@ intro.start()
alert('Hint close for Step ID ' + stepId);
})
.addHints()
.showHint(1)
.showHints()
.hideHint(1)
.hideHints()
.clone();
introWithElement.start()
+12
View File
@@ -0,0 +1,12 @@
// Type definitions for ip-regex 2.0
// Project: https://github.com/sindresorhus/ip-regex
// Definitions by: Daniel Perez Alvarez <https://github.com/unindented>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/** Regular expression for matching IP addresses (IPv4 & IPv6). */
declare function ipRegex(options?: {
/** Only match an exact string. Useful with RegExp#test to check if a string is an IP address. */
exact?: boolean;
}): RegExp;
export = ipRegex;
+7
View File
@@ -0,0 +1,7 @@
import ipRegex = require('ip-regex');
ipRegex().test('unicorn 192.168.0.1');
ipRegex({exact: true}).test('unicorn 192.168.0.1');
'unicorn 192.168.0.1 cake 1:2:3:4:5:6:7:8 rainbow'.match(ipRegex());
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"ip-regex-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+14 -12
View File
@@ -370,13 +370,18 @@ declare namespace jasmine {
}
interface CustomReporterResult {
description: string,
failedExpectations?: FailedExpectation[],
fullName: string,
id: string;
passedExpectations?: PassedExpectation[],
pendingReason?: string;
status?: string;
description: string,
failedExpectations?: FailedExpectation[],
fullName: string,
id: string;
passedExpectations?: PassedExpectation[],
pendingReason?: string;
status?: string;
}
interface RunDetails {
failedExpectations: ExpectationResult[];
order: jasmine.Order
}
interface CustomReporter {
@@ -385,7 +390,7 @@ declare namespace jasmine {
specStarted?(result: CustomReporterResult): void;
specDone?(result: CustomReporterResult): void;
suiteDone?(result: CustomReporterResult): void;
jasmineDone?(): any;
jasmineDone?(runDetails: RunDetails): void;
}
interface Runner {
@@ -549,10 +554,7 @@ declare namespace jasmine {
finished: boolean;
result: any;
messages: any;
runDetails: {
failedExpectations: ExpectationResult[];
order: jasmine.Order
}
runDetails: RunDetails
new (): any;
+11 -18
View File
@@ -872,6 +872,14 @@ var customMatchers: jasmine.CustomMatcherFactories = {
}
};
// add the custom matchers to interface jasmine.Matchers via TypeScript declaration merging
// if your test files import or export anything, you'll want to use:
// declare global {
// namespace jasmine {
// interface Matchers {
// ...
// }
// }
// }
declare namespace jasmine {
interface Matchers {
toBeGoofy(expected?: any): boolean;
@@ -926,7 +934,7 @@ var myReporter: jasmine.CustomReporter = {
}
console.log(result.passedExpectations.length);
},
suiteDone: function (result: jasmine.CustomReporterResult) {
console.log('Suite: ' + result.description + ' was ' + result.status);
for (var i = 0; i < result.failedExpectations.length; i++) {
@@ -935,29 +943,14 @@ var myReporter: jasmine.CustomReporter = {
}
},
jasmineDone: function() {
jasmineDone: function(runDetails: jasmine.RunDetails) {
console.log('Finished suite');
console.log('Random:', runDetails.order.random);
}
};
jasmine.getEnv().addReporter(myReporter);
// test for custom reporter which return ES6 Promise in jasmineDone():
var myShortReporter: jasmine.CustomReporter = {
jasmineDone: function() {
return new Promise<void>(function(resolve, reject) {
setTimeout(() => resolve(), 10000);
});
}
}
var jasmineDoneResolved: Promise<void> = myShortReporter.jasmineDone();
jasmineDoneResolved.then(() => {
console.log("[ShortReporter] : jasmineDone Resolved");
});
jasmine.getEnv().addReporter(myShortReporter);
describe("Randomize Tests", function() {
it("should allow randomization of the order of tests", function() {
expect(function() {
+143
View File
@@ -0,0 +1,143 @@
// Type definitions for jenkins 0.20
// Project: https://github.com/silas/node-jenkins
// Definitions by: rhysd <https://rhysd.github.io>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
declare namespace create {
interface JenkinsAPI {
info(callback: (err: Error, data: any) => void): void;
build: {
get(name: string, n: number, callback: (err: Error, data: any) => void): void;
log(name: string, callback: (err: Error, data: any) => void): void;
log(name: string, n: number, callback: (err: Error, data: any) => void): void;
log(name: string, n: number, start: number, callback: (err: Error, data: any) => void): void;
log(name: string, n: number, start: number, type: 'text' | 'html', callback: (err: Error, data: any) => void): void;
log(name: string, n: number, start: number, type: 'text' | 'html', meta: boolean, callback: (err: Error, data: any) => void): void;
logStream(name: string, n: number, type?: 'text' | 'html', delay?: number): NodeJS.ReadableStream;
stop(name: string, n: number, callback: (err: Error) => void): void;
};
job: {
build(name: string | JobBuildOptions, callback: (err: Error, data: any) => void): void;
build(name: string, parameters: any, callback: (err: Error, data: any) => void): void;
build(name: string, parameters: any, token: string, callback: (err: Error, data: any) => void): void;
config(name: string, callback: (err: Error, data: any) => void): void;
config(name: string, xml: string, callback: (err: Error, data: any) => void): void;
copy(name: string, from: string, callback: (err: Error) => void): void;
create(name: string, xml: string, callback: (err: Error) => void): void;
destroy(name: string, callback: (err: Error) => void): void;
disable(name: string, callback: (err: Error) => void): void;
enable(name: string, callback: (err: Error) => void): void;
exists(name: string, callback: (err: Error, exists: boolean) => void): void;
get(name: string, callback: (err: Error, data: any) => void): void;
list(callback: (err: Error, data: any) => void): void;
};
node: {
config(name: string, callback: (err: Error, data: any) => void): void;
create(name: string, callback: (err: Error) => void): void;
destroy(name: string, callback: (err: Error) => void): void;
disconnect(name: string, callback: (err: Error) => void): void;
disconnect(name: string, message: string, callback: (err: Error) => void): void;
disable(name: string, callback: (err: Error) => void): void;
disable(name: string, message: string, callback: (err: Error) => void): void;
enable(name: string, callback: (err: Error) => void): void;
exists(name: string, callback: (err: Error, data: boolean) => void): void;
get(name: string, callback: (err: Error, data: any) => void): void;
list(callback: (err: Error, data: any) => void): void;
list(full: boolean, callback: (err: Error, data: any) => void): void;
};
queue: {
list(callback: (err: Error, data: any) => void): void;
item(n: number, callback: (err: Error, data: any) => void): void;
cancel(n: number, callback: (err: Error) => void): void;
};
view: {
config(name: string, callback: (err: Error, data: any) => void): void;
config(name: string, xml: string, callback: (err: Error, data: any) => void): void;
create(name: string, type: 'list' | 'my', callback: (err: Error) => void): void;
destroy(name: string, callback: (err: Error) => void): void;
exists(name: string, callback: (err: Error, exists: boolean) => void): void;
get(name: string, callback: (err: Error, data: any) => void): void;
list(callback: (err: Error, data: any) => void): void;
add(name: string, job: string, callback: (err: Error) => void): void;
remove(name: string, job: string, callback: (err: Error) => void): void;
};
}
export interface JenkinsPromisifiedAPI {
info(): Promise<any>;
build: {
get(name: string, n: number): Promise<any>;
log(name: string, n: number, start?: number, type?: 'text' | 'html', meta?: boolean): Promise<any>;
logStream(name: string, n: number, type?: 'text' | 'html', delay?: number): Promise<any>;
stop(name: string, n: number): Promise<void>;
};
job: {
build(name: string, parameters?: any, token?: string): Promise<any>;
build(opts: JobBuildOptions): Promise<any>;
config(name: string, xml?: string): Promise<any>;
copy(name: string, from: string): Promise<void>;
create(name: string, xml: string): Promise<void>;
destroy(name: string): Promise<void>;
disable(name: string): Promise<void>;
enable(name: string): Promise<void>;
exists(name: string): Promise<boolean>;
get(name: string): Promise<any>;
list(): Promise<any>;
};
node: {
config(name: string): Promise<any>;
create(name: string): Promise<void>;
destroy(name: string): Promise<void>;
disconnect(name: string, message?: string): Promise<void>;
disable(name: string, message?: string): Promise<void>;
enable(name: string): Promise<void>;
exists(name: string): Promise<boolean>;
get(name: string): Promise<any>;
list(full?: boolean): Promise<any>;
};
queue: {
list(): Promise<any>;
item(n: number): Promise<any>;
cancel(n: number): Promise<void>;
};
view: {
config(name: string, xml?: string): Promise<any>;
create(name: string, type: 'list' | 'my'): Promise<void>;
destroy(name: string): Promise<void>;
exists(name: string): Promise<boolean>;
get(name: string): Promise<any>;
list(): Promise<any>;
add(name: string, job: string): Promise<void>;
remove(name: string, job: string): Promise<void>;
};
}
interface JobBuildOptions {
name: string;
parameters?: any;
token?: string;
}
interface JenkinsClientOptions {
baseUrl?: string;
crumbIssuer?: boolean;
headers?: any;
promisify?: boolean | ((...args: any[]) => any);
}
}
declare function create(opts?: {
baseUrl?: string;
crumbIssuer?: boolean;
headers?: any;
promisify?: false;
}): create.JenkinsAPI;
declare function create(opts: {
baseUrl?: string;
crumbIssuer?: boolean;
headers?: any;
promisify: true;
}): create.JenkinsPromisifiedAPI;
export = create;
+205
View File
@@ -0,0 +1,205 @@
import * as J from 'jenkins';
const jenkins = J({ baseUrl: 'http://user:pass@localhost:8080', crumbIssuer: true });
jenkins.info(function(err, data) {
if (err) throw err;
console.log('info', data);
});
jenkins.build.get('example', 1, function(err, data) {
if (err) throw err;
console.log('build', data);
});
jenkins.build.log('example', 1, function(err, data) {
if (err) throw err;
console.log('log', data);
});
var log = jenkins.build.logStream('example', 1);
log.on('data', function(text: string) {
process.stdout.write(text);
});
log.on('error', function(err: Error) {
console.log('error', err);
});
log.on('end', function() {
console.log('end');
});
jenkins.build.stop('example', 1, function(err) {
if (err) throw err;
});
jenkins.job.build('example', function(err, data) {
if (err) throw err;
console.log('queue item number', data);
});
jenkins.job.build({ name: 'example', parameters: { name: 'value' } }, function(err) {
if (err) throw err;
});
jenkins.job.config('example', function(err, data) {
if (err) throw err;
console.log('xml', data);
});
jenkins.job.config('example', '<xml></xml>', function(err) {
if (err) throw err;
});
jenkins.job.copy('fromJob', 'example', function(err) {
if (err) throw err;
});
jenkins.job.create('example', '<xml></xml>', function(err) {
if (err) throw err;
});
jenkins.job.destroy('example', function(err) {
if (err) throw err;
});
jenkins.job.disable('example', function(err) {
if (err) throw err;
});
jenkins.job.enable('example', function(err) {
if (err) throw err;
});
jenkins.job.exists('example', function(err, exists) {
if (err) throw err;
console.log('exists', exists);
});
jenkins.job.get('example', function(err, data) {
if (err) throw err;
console.log('job', data);
});
jenkins.job.list(function(err, data) {
if (err) throw err;
console.log('jobs', data);
});
jenkins.node.config('example', function(err, data) {
if (err) throw err;
console.log('xml', data);
});
jenkins.node.create('slave', function(err) {
if (err) throw err;
});
jenkins.node.destroy('slave', function(err) {
if (err) throw err;
});
jenkins.node.disconnect('slave', 'no longer used', function(err) {
if (err) throw err;
});
jenkins.node.disable('slave', 'network failure', function(err) {
if (err) throw err;
});
jenkins.node.enable('slave', function(err) {
if (err) throw err;
});
jenkins.node.exists('slave', function(err, exists) {
if (err) throw err;
console.log('exists', exists);
});
jenkins.node.get('slave', function(err, data) {
if (err) throw err;
console.log('node', data);
});
jenkins.node.list(function(err, data) {
if (err) throw err;
console.log('nodes', data);
});
jenkins.queue.list(function(err, data) {
if (err) throw err;
console.log('queues', data);
});
jenkins.queue.item(130, function(err, data) {
if (err) throw err;
console.log('item', data);
});
jenkins.queue.cancel(23, function(err) {
if (err) throw err;
});
jenkins.view.config('example', function(err, data) {
if (err) throw err;
console.log('xml', data);
});
jenkins.view.config('example', '<xml></xml>', function(err) {
if (err) throw err;
});
jenkins.view.create('example', 'list', function(err) {
if (err) throw err;
});
jenkins.view.destroy('example', function(err) {
if (err) throw err;
});
jenkins.view.exists('example', function(err, exists) {
if (err) throw err;
console.log('exists', exists);
});
jenkins.view.get('example', function(err, data) {
if (err) throw err;
console.log('view', data);
});
jenkins.view.list(function(err, data) {
if (err) throw err;
console.log('views', data);
});
jenkins.view.add('example', 'jobExample', function(err) {
if (err) throw err;
});
jenkins.view.remove('example', 'jobExample', function(err) {
if (err) throw err;
});
const jenkins2 = J({ baseUrl: 'http://user:pass@localhost:8080', crumbIssuer: true, promisify: true });
jenkins2.info().then(info => console.log(info));
jenkins2.job.exists('example').then(exists => { var b: boolean = exists; });
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"jenkins-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+824
View File
@@ -0,0 +1,824 @@
// Type definitions for jui-core 2.0
// Project: https://github.com/juijs/jui-core
// Definitions by: JinHo Park <https://github.com/easylogic>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="jquery"/>
declare var jui: JuiStatic;
interface UtilBase {
/**
* @property browser check browser agent
* @property {Boolean} browser.webkit Webkit 브라우저 체크
* @property {Boolean} browser.mozilla Mozilla 브라우저 체크
* @property {Boolean} browser.msie IE 브라우저 체크 */
browser: {
webkit: boolean,
mozilla: boolean,
msie: boolean
};
/**
* @property {Boolean} isTouch
* check touch device
*/
isTouch: boolean;
/**
* @method inherit
*
* 프로토타입 기반의 상속 제공
*
* @param {Function} ctor base Class
* @param {Function} superCtor super Class
*/
inherit( ctor: ((...args: any[]) => any), superCtor: ((...args: any[]) => any) ): void;
/**
* @method extend
*
* implements object extend
*
* @param {Object|Function} origin
* @param {Object|Function} add
* @param {Boolean} skip
* @return {Object}
*/
extend(origin: any, add: any, skip: boolean): any;
/**
* convert px to integer
* @param {String or Number} px
* @return {Number}
*/
pxToInt(px: string| number): number;
/**
* @method clone
* implements object clone
* @param {Array/Object} obj 복사할 객체
* @return {Array}
*/
clone(obj: any): any[];
/**
* @method deepClone
* implements object deep clone
* @param obj
* @param emit
* @return {*}
*/
deepClone(obj: any, emit: any): any[];
/**
* @method sort
* use QuickSort
* @param {Array} array
* @return {QuickSort}
*/
sort(array: any[]): UtilQuickSort;
/**
* @method runtime
*
* caculate callback runtime
*
* @param {String} name
* @param {Function} callback
*/
runtime(name: string, callback: ((...args: any[]) => void)): void;
/**
* @method template
* parsing template string
* @param html
* @param obj
*/
template(html: string, obj?: any): ((obj: any) => string) | string;
/**
* @method resize
* add event in window resize event
* @param {Function} callback
* @param {Number} ms delay time
*/
resize(callback: ((...args: any[]) => void), ms: number): void;
/**
* @method index
*
* IndexParser 객체 생성
*
* @return {KeyParser}
*/
index(): UtilKeyParser;
/**
* @method chunk
* split array by length
* @param {Array} arr
* @param {Number} len
* @return {Array}
*/
chunk(arr: any[], len: number): any[];
/**
* @method typeCheck
* check data type
* @param {String} t type string
* @param {Object} v value object
* @return {Boolean}
*/
typeCheck(typeName: string, value: any): boolean;
typeCheckObj(uiObj: any, list: any): void;
/**
* @method dataToCsv
*
* data 를 csv 로 변환한다.
*
* @param {Array} keys
* @param {Array} dataList
* @param {Number} dataSize
* @return {String} 변환된 csv 문자열
*/
dataToCsv(keys: string[] , dataList: any[], dataSize: number): string;
/**
* @method dataToCsv2
*
* @param {Object} options
* @return {String}
*/
dataToCsv2(options: any): string;
/**
* @method fileToCsv
*
* file 에서 csv 컨텐츠 로드
*
* @param {File} file
* @param {Function} callback
*/
fileToCsv(fileText: string, callback: ((data: any) => void)): void;
/**
* @method csvToBase64
*
* csv 다운로드 링크로 변환
*
* @param {String} csv
* @return {String} data uri string
*/
csvToBase64(csv: string): string;
/**
* @method csvToData
*
* @param {Array} keys
* @param {String} csv
* @param {Number} csvNumber
* @return {Array}
*/
csvToData(keys: string[], csv: string, csvNumber: number): any[];
/**
* @method getCsvFields
*
* csv 에서 필드 얻어오기
*
* @param {Array} fields
* @param {Array} csvFields
* @return {Array}
*/
getCsvFields(fields: string[], csvFields: string[]): string[];
/**
* @method svgToBase64
*
* xml 문자열로 svg datauri 생성
*
* @param {String} xml
* @return {String} 변환된 data uri 링크
*/
svgToBase64(xml: string): string;
/**
* @method dateFormat
*
* implements date format function
*
* yyyy : 4 digits year
* yy : 2 digits year
* y : 1 digit year
*
* @param {Date} date
* @param {String} format date format string
* @param {Boolean} utc
* @return {string}
*/
dateFormat(date: Date, format: string, utc?: boolean): string;
/**
* @method createId
*
* 유니크 아이디 생성
*
* @param {String} key prefix string
* @return {String} 생성된 아이디 문자열
*/
createId(key: string): string;
/**
* @method btoa
*
* Base64 인코딩
*
* @return {String}
*/
btoa(input: any): string;
/**
* @method atob
*
* Base64 디코딩
*
* @return {Any}
*/
atob(input: string): any;
/**
* implement async loop without blocking ui
*
* @param {Number} total loop count
* @param {Object} context
* @returns {Function}
*/
timeLoop(total: number, context?: any): ((index: number) => void);
/**
* @method loop
*
* 최적화된 루프 생성 (5단계로 나눔)
*
* @param {Number} total loop count
* @param {Object} [context=null]
* @return {Function} 최적화된 루프 콜백 (index, groupIndex 2가지 파라미터를 받는다.)
*/
loop(total: number, context?: any): ((index: number, groupIndex: number) => void );
/**
* @method loopArray
*
* 배열을 사용해서 최적화된 루프로 생성한다.
*
*
* @param {Array} data 루프로 생성될 배열
* @param {Object} [context=null]
* @return {Function} 최적화된 루프 콜백 (data, index, groupIndex 3가지 파라미터를 받는다.)
*/
loopArray(data: any[], context?: any): ((data: any, index: number, groupIndex: number) => void );
/**
* @method makeIndex
*
* 배열의 키 기반 인덱스를 생성한다.
*
* 개별 값 별로 멀티 인덱스를 생성한다.
*
* @param {Array} data
* @param {String} keyField
* @return {Object} 생성된 인덱스
*/
makeIndex(data: any[], keyField: string): any;
/**
* @method startsWith
* Check that it matches the starting string search string.
*
* @param {String} string
* @param {String} searchString
* @param {Number} [position=0]
* @return {Number} position
*/
startsWith(str: string, searchString: string, position?: number): number;
/**
* @method endsWith
* Check that it matches the end of a string search string.
*
* @param {String} string
* @param {String} searchString
* @return {Number} position
*/
endsWith(str: string, searchString: string, position?: number): number;
inArray(target: any, list: any[]): number;
trim(text: string): string;
ready: ((...args: any[]) => void);
param(data: any): string;
ajax(data: any): void;
scrollWidth(): number;
}
interface JuiStatic {
/**
* @method ready
*
* ready 타임에 실행될 callback 정의
*
* @param {Function} callback
*/
ready(depends?: string[], callback?: (...args: any[]) => void): void;
/**
* @method defineUI
*
* 사용자가 실제로 사용할 수 있는 UI 클래스를 정의
*
* @param {String} name 모듈 로드와 상속에 사용될 이름을 정한다.
* @param {Array} depends 'define'이나 'defineUI'로 정의된 클래스나 객체를 인자로 받을 수 있다.
* @param {Function} callback UI 클래스를 해당 콜백 함수 내에서 클래스 형태로 구현하고 리턴해야 한다.
*/
defineUI(name: string, depends: string[], callback: () => void, parent?: string): void;
/**
* @method define
*
* UI 클래스에서 사용될 클래스를 정의하고, 자유롭게 상속할 수 있는 클래스를 정의
*
* @param {String} name 모듈 로드와 상속에 사용될 이름을 정한다.
* @param {Array} depends 'define'이나 'defineUI'로 정의된 클래스나 객체를 인자로 받을 수 있다.
* @param {Function} callback UI 클래스를 해당 콜백 함수 내에서 클래스 형태로 구현하고 리턴해야 한다.
* @param {String} parent 상속받을 클래스
*/
define(name: string, depends: string[], callback: () => void, parent?: string): void;
/**
* @method redefine
*
* UI 클래스에서 사용될 클래스를 정의하고, 자유롭게 상속할 수 있는 클래스를 정의
*
* @param {String} name 모듈 로드와 상속에 사용될 이름을 정한다.
* @param {Array} depends 'define'이나 'defineUI'로 정의된 클래스나 객체를 인자로 받을 수 있다.
* @param {Function} callback UI 클래스를 해당 콜백 함수 내에서 클래스 형태로 구현하고 리턴해야 한다.
* @param {String} parent 상속받을 클래스
*/
redefine(name: string, depends: string[], callback: () => void, parent?: string): void;
/**
* define과 defineUI로 정의된 클래스 또는 객체를 가져온다.
*
* @param name 가져온 클래스 또는 객체의 이름
* @return {*}
*/
include(name: string): any;
/**
* define과 defineUI로 정의된 모든 클래스와 객체를 가져온다.
*
* @return {Array}
*/
includeAll(): any[];
/**
* @method add
* Adds a component object created
*
* @param {Object} ui UI instance
*/
add(uiIns: any): void;
/**
* @method emit
* Generates a custom event to an applicable component
*
* @param {String} key Selector or UI type
* @param {String} type Event type
* @param {Array} args Event arguments
*/
emit(key: string, type: string, args: any[]): void;
/**
* @method get
* Gets a component currently created
*
* @param {Integer/String} key
* @returns {Object/Array} UI instance
*/
get(key: number|string): any;
/**
* @method getAll
* Gets all components currently created
*
* @return {Array} UI instances
*/
getAll(): any[];
/**
* @method create
* It is possible to create a component dynamically after the ready point
*
* @param {String} type UI type
* @param {String/DOMElement} selector
* @param {Object} options
* @return {Object}
*/
create(type: string, selector: any, options?: {}): any;
}
interface UICollection {
destroy(): void;
}
interface UICore {
tpl?: any;
event?: any;
root?: any;
/**
* @method emit
* Generates a custom event. The first parameter is the type of a custom event. A function defined as an option or on method is called
*
* @param {String} type Event type
* @param {Function} args Event Arguments
* @return {Mixed}
*/
emit(type: string, args: () => void): any;
/**
* @method on
* A callback function defined as an on method is run when an emit method is called
*
* @param {String} type Event type
* @param {Function} callback
*/
on(type: string, callback: () => void): void;
/**
* @method off
* Removes a custom event of an applicable type or callback handler
*
* @param {String} type Event type
*/
off(type: string): void;
/**
* @method addValid
* Check the parameter type of a UI method and generates an alarm when a wrong value is entered
*
* @param {String} name Method name
* @param {Array} params Parameters
*/
addValid(name: string, params: any[]): void;
/**
* @method callBefore
* Sets a callback function that is called before a UI method is run
*
* @param {String} name Method name
* @param {Function} callback
* @return {Mixed}
*/
callBefore(name: string, callback: () => void): void;
/**
* @method callAfter
* Sets a callback function that is called after a UI method is run
*
* @param {String} name Method name
* @param {Function} callback
* @return {Mixed}
*/
callAfter(name: string, callback: () => void): void;
/**
* @method callDelay
* Sets a callback function and the delay time before/after a UI method is run
*
* @param {String} name Method name
* @param {Function} callback
*/
callDelay(name: string, callObj: () => void): void;
/**
* @method setTpl
* Dynamically defines the template method of a UI
*
* @param {String} name Template name
* @param {String} html Template markup
*/
setTpl(name: string, html: string): void;
/**
* @method setOption
* Dynamically defines the options of a UI
*
* @param {String} key
* @param {Mixed} value
*/
setOption(key: string, value: any): void;
/**
* @method destroy
* Removes all events set in a UI obejct and the DOM element
*
*/
destroy(): void;
}
//noinspection TypeScriptUnresolvedVariable
export interface UIEvent extends UICore {
root?: any;
/**
* @method find
* Get the child element of the root element
*
* @param {String/HTMLElement} Selector
* @returns {*|jQuery}
*/
find(selector: any): JQuery;
}
export class ColorScale {
domain(color: string, color2: string): this;
ticks(max: number): this;
}
export interface UtilColor {
/**
* @method format
*
* convert color to format string
*
* // hex
* color.format({ r : 255, g : 255, b : 255 }, 'hex') // #FFFFFF
*
* // rgb
* color.format({ r : 255, g : 255, b : 255 }, 'rgb') // rgba(255, 255, 255, 0.5);
*
* // rgba
* color.format({ r : 255, g : 255, b : 255, a : 0.5 }, 'rgb') // rgba(255, 255, 255, 0.5);
*
* @param {Object} obj obj has r, g, b and a attributes
* @param {"hex"/"rgb"} type format string type
* @returns {*}
*/
format(obj: any, type: string): string;
/**
* @method scale
*
* get color scale
*
* var c = color.scale().domain('#FF0000', '#00FF00');
*
* // get middle color
* c(0.5) == #808000
*
* // get middle color list
* c.ticks(20); // return array , [startColor, ......, endColor ]
*
* @returns {func} scale function
*/
scale(): ColorScale;
/**
* @method map
*
* create color map
*
* var colorList = color.map(['#352a87', '#0f5cdd', '#00b5a6', '#ffc337', '#fdff00'], count)
*
* @param {Array} color_list
* @param {Number} count a divide number
* @returns {Array} converted color list
*/
map(color_list: string[], count: number): string[];
/**
* @method rgb
*
* parse string to rgb color
*
* color.rgb("#FF0000") === { r : 255, g : 0, b : 0 }
*
* color.rgb("rgb(255, 0, 0)") == { r : 255, g : 0, b : }
*
* @param {String} str color string
* @returns {Object} rgb object
*/
rgb(str: string): any;
/**
* @method HSVtoRGB
*
* convert hsv to rgb
*
* color.HSVtoRGB(0,0,1) === #FFFFF === { r : 255, g : 0, b : 0 }
*
* @param {Number} H hue color number (min : 0, max : 360)
* @param {Number} S Saturation number (min : 0, max : 1)
* @param {Number} V Value number (min : 0, max : 1 )
* @returns {Object}
*/
HSVtoRGB(H: number, S: number, V: number): any;
/**
* @method RGBtoHSV
*
* convert rgb to hsv
*
* color.RGBtoHSV(0, 0, 255) === { h : 240, s : 1, v : 1 } === '#FFFF00'
*
* @param {Number} R red color value
* @param {Number} G green color value
* @param {Number} B blue color value
* @return {Object} hsv color code
*/
RGBtoHSV(R: number, G: number, B: number): any;
/**
* @method lighten
*
* rgb 컬러 밝은 농도로 변환
*
* @param {String} color RGB color code
* @param {Number} rate 밝은 농도
* @return {String}
*/
lighten(color: string, rate: number): string;
/**
* @method darken
*
* rgb 컬러 어두운 농도로 변환
*
* @param {String} color RGB color code
* @param {Number} rate 어두운 농도
* @return {String}
*/
darken(color: string, rate: number): string;
}
interface UtilBase64 {
encode(input: string): string;
decode(input: string): string;
}
interface UtilKeyParser {
/**
* @method isIndexDepth
*
* @param {String} index
* @return {Boolean}
*/
isIndexDepth(index: string): boolean;
/**
* @method getIndexList
*
* @param {String} index
* @return {Array}
*/
getIndexList(index: string): boolean;
/**
* @method changeIndex
*
*
* @param {String} index
* @param {String} targetIndex
* @param {String} rootIndex
* @return {String}
*/
changeIndex(index: string, targetIndex: string, rootIndex: string): string;
/**
* @method getNextIndex
*
* @param {String} index
* @return {String}
*/
getNextIndex(index: string): string;
/**
* @method getParentIndex
*
*
* @param {String} index
* @returns {*}
*/
getParentIndex(index: string): string;
}
interface UtilMath {
/**
* @method rotate
*
* 2d rotate
*
* @param {Number} x
* @param {Number} y
* @param {Number} radian roate 할 radian
* @return {Object}
* @return {Number} return.x 변환된 x
* @return {Number} return.y 변환된 y
*
*/
rotate(x: number, y: number, radian: number): any;
resize(maxWidth: number, maxHeight: number, objectWidth: number, objectHeight: number): any;
/**
* @method radian
*
* convert degree to radian
*
* @param {Number} degree
* @return {Number} radian
*/
radian(degree: number): number;
/**
* @method degree
*
* convert radian to degree
*
* @param {Number} radian
* @return {Number} degree
*/
degree(radian: number): number;
angle(x1: number, y1: number, x2: number, y2: number): number;
/**
* @method interpolateNumber
*
* a, b 의 중간값 계산을 위한 callback 함수 만들기
*
* @param {Number} a first value
* @param {Number} b second value
* @return {Function}
*/
interpolateNumber(a: number, b: number): () => void;
// 중간값 round 해서 계산하기
interpolateRound(a: number, b: number): () => void;
round(num: number, fixed: number): number;
plus(a: number, b: number): number;
minus(a: number, b: number): number;
multi(a: number, b: number): number;
div(a: number, b: number): number;
remain(a: number, b: number): number;
/**
* 특정 구간의 값을 자동으로 계산
*
* @param {Object} min
* @param {Object} max
* @param {Object} ticks
* @param {Object} isNice
*/
nice(min: number, max: number, ticks: number, isNice: boolean): any;
matrix<T>(a: T[], b: T[]): T[];
matrix3d<T>(a: T[], b: T[]): T[];
inverseMatrix3d(a: any[]): any[];
}
export interface UtilScaleOrdinal extends Function {
(x: number): number;
domain(values: any[]): UtilScaleOrdinal;
range(values: any[]): UtilScaleOrdinal;
rangePoints(interval: number, padding?: number): () => void;
rangeBands(interval: number, padding?: number, outerPadding?: number): () => void;
invert(x: number): number;
}
export type UtilQuickSort = (array: number[], isClone: boolean) => this;
+15
View File
@@ -0,0 +1,15 @@
/// <reference types="jquery"/>
import {jui, UtilColor, UtilBase} from "./index";
jui.ready(["util.color"], function(color: UtilColor) {
console.log(color.rgb("#ff0000"));
});
let _ : UtilBase = jui.include("util.base");
let str: string = "10";
console.log(_.typeCheck("string", str));
let i: number = 10;
console.log(_.typeCheck("string", i));
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"jui-core-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+996
View File
@@ -0,0 +1,996 @@
// Type definitions for jui-grid 2.0
// Project: https://github.com/juijs/jui-grid
// Definitions by: Jin-Ho Park <https://github.com/easylogic>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import {UIEvent} from 'jui-core';
export interface GridColumn {
(index: number|string): this;
/** @property {HTMLElement} [element=null] TH element of a specified column */
element: any;
/** @property {String} [order="asc"] Column sort state */
order: "asc"|"desc";
/** @property {String} [name=null] Column name */
name?: string;
/** @property {Array} data Data from all rows belonging for a specified column */
data: any[];
/** @property {Array} list TD element of all rows belonging to a specified column */
list: any[];
/** @property {Integer} index Column index */
index: number;
/** @property {"show"/"hide"/"resize"} [type="show"] The current column state */
type: "show"|"hide"|"resize";
/** @property {Integer} [width=null] Column width */
width?: number;
hide(): void;
show(): void;
}
export interface GridRow {
/** @property {Array} data Data of a specifiedrow. */
data: any[];
/** @property {Integer} seq Data of a sequence. */
seq: number;
/** @property {Integer} [rownum=null] The unique number of a child row under the specified parent row if a parent row exists. */
rownum?: number;
/** @property {String/Integer} [index=null] Index of a specified row. In the case of a tree structure, a depth is given. */
index: number|string;
/** @property {HTMLElement} [element=null] TR element of a specified row. */
element: any;
/** @property {Array} list List of TD elements of a specified row. */
list: any[];
/** @property {Object} list List of hidden TD element. */
hidden: {};
/** @property {uix.table.row} parent Variable that refers to the parent row. */
parent?: GridRow;
/** @property {Array} children List of child rows. */
children: any[];
/** @property {Integer} [depth=0] The depth of the current row in the case of a tree structure. */
depth: number;
/** @property {"open"/"fold"} [type="fold"] State value that indicates whether a child row is shown or hidden. */
type: "open"|"fold";
/** @property {Function} [type="null"] State value that indicates whether a child row is shown or hidden. */
tpl?: () => void;
setIndex(rownum: number|string): void;
reload(columns: GridColumn[], seq: any, xssFilter: any): void;
destroy(): void;
isLeaf(): boolean;
fold(): void;
open(): void;
appendChild(row: GridRow): void;
insertChild(rownum: number, row: GridRow, isReload?: any): void;
removeChild(index: number|string): void;
lastChild(): GridRow;
lastChildLeaf(lastRow: GridRow): GridRow|any;
showCell(index: number): void;
hideCell(index: number): void;
}
export interface GridBase {
appendRow(index: number|string, data?: {}): GridRow;
insertRow(index: number|string, data: {}): GridRow;
updateRow(index: number|string, data: {}): GridRow;
moveRow(index: number|string, targetIndex: number|string): void;
removeRow(index: number|string): void;
openRow(index: number|string): void;
openRowAll(): void;
foldRow(index: number|string): void;
foldRowAll(): void;
removeRows(): void;
sortRows(name: string, isDesc: boolean): void;
appendColumn(tplType: string, dataList: any[]): void;
removeColumn(index: number|string): void;
hideColumn(index: number|string): void;
showColumn(index: number|string): void;
getColumnCount(): number;
getRowCount(): number;
getColumn(index?: number|string): GridColumn|GridColumn[];
getRow(index?: number|string): GridRow|GridRow[];
getRowAll(index: number|string): GridRow[];
getRowParent(index: number|string): GridRow;
setColumn(index: number|string, column: GridColumn): void;
setRow(index: number|string, row: GridRow): void;
}
export interface GridTable extends UIEvent {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {Array} [fields=null]
* Sets the name of columns in the order of being displayed on the table screen.
*/
fields?: any[],
/**
* @cfg {Array} [csv=null]
* Sets the column key shown when converted to a CSV string.
*/
csv?: any[],
/**
* @cfg {Array} [csvNames=null]
* Sets the name of a column shown when converting to a CSV string, which must be defined in the same order as the CSV option.
*/
csvNames?: any[],
/**
* @cfg {Array} [csvNumber=null]
* Sets the column key to be changed to a number form when converted to a CSV string.
*/
csvNumber?: any[],
/**
* @cfg {Array} data
* Sets the initial row list of a table.
*/
data?: any[],
/**
* @cfg {Boolean/Array} [colshow=false]
* Sets a column index shown when the Show/Hide Column menu is enabled.
*/
colshow?: boolean|any[],
/**
* @cfg {Boolean} [scroll=false]
* Determines whether to use a table scroll.
*/
scroll?: boolean,
/**
* @cfg {Integer} [scrollHeight=200]
* Sets the reference height of a body area when using a table scroll.
*/
scrollHeight?: number,
/**
* @cfg {Integer} [width=0]
* Sets the area of a table.
*/
width?: number,
/**
* @cfg {Boolean} [expand=false]
* Determines whether to use an extended row area.
*/
expand?: boolean,
/**
* @cfg {Boolean} [expandEvent=true]
* Sets the Show/Hide state of an extended row area when clicking on a row.
*/
expandEvent?: boolean,
/**
* @cfg {Boolean|Array} [editRow=false]
* Determines whether to use a modified row area.
*/
editRow?: boolean|any[],
/**
* @cfg {Boolean} [editEvent=true]
* Sets the Show/Hide state of an extended row area when doubleclicking on a row/cell.
*/
editEvent?: boolean,
/**
* @cfg {Boolean} [resize=false]
* Determines whether to use the column resizing function.
*/
resize?: boolean,
/**
* @cfg {Boolean/Array} [sort=false]
* Determines whether to use the table sort function.
*/
sort?: boolean|any[],
/**
* @cfg {Integer} [sortIndex=null]
* Determines whether to use the table sort function.
*/
sortIndex?: number,
/**
* @cfg {String} [sortOrder="asc"]
* Determines whether to use the table sort function.
*/
sortOrder?: "asc"|"desc",
/**
* @cfg {Boolean} [sortEvent=true]
* Determines whether to use the sort function when you click on a column.
*/
sortEvent?: boolean,
/**
* @cfg {Boolean} [moveRow=false]
* Determines whether to use the move function when you fire row draggable event.
*/
moveRow?: boolean,
}): this;
root?: any;
/**
* @method update
* Updates the list of rows or modifies the row at a specified index.
*
* @param {Array} rows
*/
update(indexOrRows?: any, rows?: any): void;
/**
* @method updateTree
* It is possible to configure a tree table using an object array with the index and data properties.
*
* @param {Array} rows
*/
updateTree(rows: any[]): void;
/**
* @method append
* Add a row or a child row to at a specified index.
*
* @param {RowObject} row
*/
append(rowOrIndex?: number|any, row?: any): void;
/**
* @method insert
* Adds a row at a specified index.
*
* @param {Integer} index
* @param {RowObject} row
*/
insert(index: number, dataList: {}): void;
/**
* @method select
* Adds a selected class to a row at a specified index and gets an instance of the applicable row.
*
* @param {Integer} index
* @return {RowObject} row
*/
select(index: number): GridRow;
/**
* @method unselect
* Removes a selected class from a selected row and gets an instance of the row in question.
*
* @return {RowObject} row
*/
unselect(): GridRow;
/**
* @method check
* Add a checked class to a row at a specified index.
*
* @param {Integer} index
*/
check(index: number): void;
/**
* @method uncheck
* Removes a checked class from a row at a specified index.
*
* @param {Integer} index
*/
uncheck(index: number): void;
/**
* @method uncheckAll
* Removes checked classes from all rows.
*/
uncheckAll(): void;
/**
* @method remove
* Remove a row at a specified index.
*
* @param {Integer} index
*/
remove(index: number): void;
/**
* @method reset
* Removes all rows.
*/
reset(): void;
/**
* @method move
* Moves a row iat a specified index to the target index.
*
* @param {Integer} index
* @param {Integer} targetIndex
*/
move(index: number, targetIndex: number): void;
/**
* @method sort
* Moves a row iat a specified index to the target index.
*
* @param {Integer} index
* @param {String} order "asc" or "desc"
*/
sort(index: number, order: string, e?: any): void;
/**
* @method scroll
* Sets the scroll based on the height of a table.
*
* @param {Integer} height
*/
scroll(height: number): void;
/**
* @method open
* Shows a child row of a specified index.
*
* @param {Integer} index
*/
open(index: number): void;
/**
* @method fold
* Hides a child row of a specified index.
*
* @param {Integer} index
*/
fold(index: number): void;
/**
* @method openAll
* Shows all child rows of a specified index.
*/
openAll(): void;
/**
* @method foldAll
* Hides all child rows of a specified index.
*/
foldAll(): void;
/**
* @method resize
* Resets the inner scroll and columns of a table.
*/
resize(): void;
/**
* @method resizeColumns
* Resets the sizes of all columns of a table.
*/
resizeColumns(): void;
/**
* @method size
* Gets the size of all the rows of a table.
*
* @return {Integer} size
*/
size(): number;
/**
* @method count
* Gets the number of trows of a table.
*
* @return {Integer} count
*/
count(): number;
/**
* @method list
* Gets all the rows of a table.
*
* @return {Array} rows
*/
list(): GridRow[];
/**
* @method listData
* Gets the data of all the rows of a table.
*
* @return {Array} datas
*/
listData(): any[];
/**
* @method listAll
* Gets all the rows of a table including child rows.
*
* @return {Array} rows
*/
listAll(): GridRow[];
/**
* @method listChecked
* Gets all rows in a check state.
*
* @return {Array} rows
*/
listChecked(): GridRow[];
/**
* @method listColumn
* Gets all columns.
*
* @return {Array} columns
*/
listColumn(): GridColumn;
/**
* @method get
* Gets the row at the specified index.
*
* @param {Integer} index
* @return {RowObject} row
*/
get(index: number): GridRow;
/**
* @method getAll
* Gets all rows of at the specified index including child rows.
*
* @param {Integer} index
* @return {Array} rows
*/
getAll(index: number): GridRow[];
/**
* @method getColumn
* Gets the column at the specified index.
*
* @param {"Integer"/"String"} key index or column key
* @return {ColumnObject} column
*/
getColumn(index: number|string): GridColumn;
/**
* @method showColumn
* Shows the column index (or column name).
*
* @param {"Integer"/"String"} key index or column name
*/
showColumn(index: number|string, e?: any): void;
/**
* @method hideColumn
* Hides the column index (or column name).
*
* @param {"Integer"/"String"} key index or column name
*/
hideColumn(index: number|string, e?: any): void;
/**
* @method initColumns
* It is possible to determine the index or name of the column to be shown in an array.
*
* @param {"Integer"/"String"} key index or column name
*/
initColumns(keys: any): void;
/**
* @method showColumnMenu
* Shows the Show/Hide Column menu at specified coordinates.
*
* @param {Integer} x
* @param {Integer} y
*/
showColumnMenu(x: number, y: number): void;
/**
* @method hideColumnMenu
* Hides the Show/Hide Column menu.
*/
hideColumnMenu(): void;
/**
* @method toggleColumnMenu
* Shows or hides the Show/Hide Column menu.
*
* @param {Integer} x
* @param {Integer} y
*/
toggleColumnMenu(x: number, y: number): void;
/**
* @method showExpand
* Shows the extended row area of a specified index.
*
* @param {Integer} index
*/
showExpand(index: number, obj?: any, e?: any): void;
/**
* @method hideExpand
* Hides the extended row area of a specified index.
*/
hideExpand(e?: any): void;
/**
* @method getExpand
* Get a row in which the extended area is currently activated.
*
* @return {RowObject} row
*/
getExpand(): GridRow;
/**
* @method showEditRow
* Shows the modified row area of a specified index.
*
* @param {Integer} index
*/
showEditRow(index: number, e?: any): void;
/**
* @method hideEditRow
* Hides the modified row area of a specified index.
*/
hideEditRow(data?: any): void;
/**
* @method getEditRow
* Get a row in which the modified area is currently activated.
*
* @return {RowObject} row
*/
getEditRow(): GridRow;
/**
* @method setCsv
* Updates a table using a CVS string.
*/
setCsv(csvOrKey: any, key?: any): void;
/**
* @method setCsvFile
* Updates a table using a CVS file.
*/
setCsvFile(fileOrKey: any, key?: any): void;
/**
* @method getCsv
* Gets the data of a table as a CSV string.
*
* @param {Boolean} isTree
* @return {String} csv
*/
getCsv(isTree: boolean): string;
/**
* @method getCsvBase64
* Gets the data of a table as a CSV string encoded as base64.
*
* @param {Boolean} isTree
* @return {String} base64
*/
getCsvBase64(isTree: boolean): string;
/**
* @method downloadCsv
* Downloads the data of a table as a CSV file.
*
* @param {String} name
* @param {Boolean} isTree
*/
downloadCsv(name: string, isTree: boolean): void;
/**
* @method activeIndex
* Gets the index of a row that is activated in an extended/modified/selected state.
*
* @return {Integer} index
*/
activeIndex(): number;
}
export interface GridXTable extends UIEvent {
(selector: any, options?: {
}): this;
render(isTree?: boolean): void;
/**
* @method select
* Adds a selected class to a row at a specified index and gets an instance of the applicable row.
*
* @param {Integer} index
* @return {RowObject} row
*/
select(index: number): GridRow;
/**
* @method unselect
* Removes a selected class from a selected row and gets an instance of the row in question.
*
* @return {RowObject} row
*/
unselect(): GridRow;
/**
* @method update
* Updates the list of rows or modifies the row at a specified index.
*
* @param {Array} rows
*/
update(dataList: any[]): void;
/**
* @method updateTree
* It is possible to configure a tree table using an object array with the index and data properties.
*
* @param {Array} rows
*/
updateTree(tree: any[]): void;
/**
* @method append
* Add a row or a child row to at a specified index.
*
* @param {RowObject} row
* @param {RowObject} row
*/
append(index: number, data: {}): void;
/**
* @method open
* Shows a child row of a specified index.
*
* @param {Integer} index
*/
open(index: number|string): void;
/**
* @method fold
* Hides a child row of a specified index.
*
* @param {Integer} index
*/
fold(index: number|string): void;
/**
* @method openAll
* Shows all child rows of a specified index.
*/
openAll(index: number|string): void;
/**
* @method foldAll
* Hides all child rows of a specified index.
*/
foldAll(index: number|string): void;
/**
* @method next
* Changes to the next page.
*/
next(): void;
/**
* @method page
* Changes to the page of at a specified index.
*
* @param {Integer} index
*/
page(pNo: number): void;
/**
* @method sort
* Moves a row iat a specified index to the target index.
*
* @param {Integer} index
* @param {String} order "asc" or "desc"
*/
sort(index: number, order: "asc"|"desc", e?: any, isNotLoading?: any): void;
/**
* @method filter
* Filters columns at a specified to locate rows that contain keywords in the cell value.
*
* @param {Function} callback
*/
filter(callback: (data: any) => void): void;
/**
* @method rollback
* Returns filtered rows to the original state.
*/
rollback(): void;
/**
* @method clear
* Remove all row elements.
*/
clear(): void;
/**
* @method clear
* Remove all data
*/
reset(): void;
/**
* @method resize
* Resets the inner scroll and columns of a table.
*/
resize(): void;
/**
* @method scrollWidth
* Sets the scroll based on the width of a table.
*
* @param {Integer} width
*/
scrollWidth(scrollWidth: number, isInit?: boolean): void;
/**
* @method scrollHeight
* Sets the scroll based on the height of a table.
*
* @param {Integer} height
*/
scrollHeight(h: number): void;
/**
* @method scrollTop
* Sets the scroll based on the height of a table.
*
* @param {Integer|String} index
* @param {Integer} dist
*/
scrollTop(index: number|string, dist: number): void;
/**
* @deprecated
* @method height
* Sets the scroll based on the height of a table.
*
* @param {Integer} height
*/
height(h: number): void;
/**
* @method size
* Gets the size of all the rows of a table.
*
* @return {Integer} size
*/
size(): number;
/**
* @method count
* Gets the number of trows of a table.
*
* @return {Integer} count
*/
count(): number;
/**
* @method list
* Gets all the rows of a table.
*
* @return {Array} rows
*/
list(): GridRow[];
/**
* @method listColumn
* Gets all columns.
*
* @return {Array} columns
*/
listColumn(): GridColumn[];
/**
* @method listData
* Gets the data of all the rows of a table.
*
* @return {Array} datas
*/
listData(): any[];
/**
* @method get
* Gets the row at the specified index.
*
* @param {Integer|String} index
* @return {RowObject} row
*/
get(index: number): GridRow;
getAll(index: number, _result?: any): GridRow[];
/**
* @method getColumn
* Gets the column at the specified index.
*
* @param {"Integer"/"String"} key index or column key
* @return {ColumnObject} column
*/
getColumn(index: number|string): GridColumn;
/**
* @method getData
* Gets the data at the specified index.
*
* @param {"Integer"/"String"} key index
* @return {ColumnObject} data
*/
getData(index: number|string): any;
/**
* @method showColumn
* Shows the column index (or column name).
*
* @param {"Integer"/"String"} key index or column name
*/
showColumn(index: number|string): void;
/**
* @method hideColumn
* Hides the column index (or column name).
*
* @param {"Integer"/"String"} key index or column name
*/
hideColumn(index: number|string): void;
/**
* @method initColumns
* It is possible to determine the index or name of the column to be shown in an array.
*
* @param {"Integer"/"String"} key index or column name
*/
initColumns(keys: number|string): void;
/**
* @method showColumnMenu
* Shows the Show/Hide Column menu at specified coordinates.
*
* @param {Integer} x
* @param {Integer} y
*/
showColumnMenu(x: number, y: number): void;
/**
* @method hideColumnMenu
* Hides the Show/Hide Column menu.
*/
hideColumnMenu(): void;
/**
* @method toggleColumnMenu
* Shows or hides the Show/Hide Column menu.
*
* @param {Integer} x
* @param {Integer} y
*/
toggleColumnMenu(x: number, y: number): void;
/**
* @method showExpand
* Shows the extended row area of a specified index.
*
* @param {Integer} index
*/
showExpand(index: number, obj: any): void;
/**
* @method hideExpand
* Hides the extended row area of a specified index.
*/
hideExpand(index: number): void;
/**
* @method getExpand
* Get a row in which the extended area is currently activated.
*
* @return {RowObject} row
*/
getExpand(): GridRow;
/**
* @method showLoading
* Shows the loading screen for the specified delay time.
*
* @param {Integer} delay
*/
showLoading(delay: number): void;
/**
* @method hideLoading
* Hides the loading screen.
*/
hideLoading(): void;
/**
* @method setCsv
* Updates a table using a CVS string.
*/
setCsv(csv: string): void;
/**
* @method setCsvFile
* Updates a table using a CVS file.
*/
setCsvFile(file: any): void;
/**
* @method getCsv
* Gets the data of a table as a CSV string.
*
* @param {Boolean} isTree
* @return {String} csv
*/
getCsv(): string;
/**
* @method getCsvBase64
* Gets the data of a table as a CSV string encoded as base64.
*
* @param {Boolean} isTree
* @return {String} base64
*/
getCsvBase64(): string;
/**
* @method downloadCsv
* Downloads the data of a table as a CSV file.
*
* @param {String} name
* @param {Boolean} isTree
*/
downloadCsv(name: string): void;
/**
* @method rowFunc
* Ir is possible to use a function for all row data applicable to the column (or column name) of a specified column (or column name). Currently only SUM and AVG are supported.
*
* @param {"sum"/"svg"} funcType
* @param {Integer} columnIndex
* @param {Function} callback
*/
rowFunc(type: "sum"|"avg", index: number, callback: (data: any) => void): any;
/**
* @method getPage
* Gets the current page of a table.
*
* @return {Integer} page
*/
getPage(): number;
/**
* @method activeIndex
* Gets the index of a row that is activated in an extended/modified/selected state.
*
* @return {Integer} index
*/
activeIndex(): number;
}
+182
View File
@@ -0,0 +1,182 @@
/// <reference types="jquery" />
import {jui} from 'jui-core';
import {GridTable, GridXTable, GridRow} from "./index";
jui.ready([ "grid.table" ], function(table: GridTable) {
let table_1: GridTable = table("#table_1", {
data: [
{ name: "Hong", age: "20", location: "Ilsan" },
{ name: "Jung", age: "30", location: "Seoul" },
{ name: "Park", age: "15", location: "Yeosu" },
{ name: "Kang", age: "32", location: "Seoul" },
{ name: "Song", age: "12", location: "Gwangju" },
{ name: "Yoon", age: "22", location: "Damyang" },
{ name: "Kim", age: "33", location: "Busan" },
{ name: "Hwang", age: "21", location: "Seoul" }
]
});
table_1.scroll(100);
});
jui.ready([ "grid.table" ], function(table: GridTable) {
let table_3:GridTable = table("#table_3", {
event: {
expand: function(row: any, e: any): void {
$(row.list[0]).html("<i class='icon-right'></i>");
},
expandend: function(row: any, e: any): void {
$(row.list[0]).html("<i class='icon-left'></i>");
}
},
expand: true
});
table_3.update([
{ name: "Hong", age: "20", location: "Ilsan" },
{ name: "Jung", age: "30", location: "Seoul" },
{ name: "Park", age: "10", location: "Dangjin" }
]);
let table_3_submit: Function = function(index: number) {
var name = $(table_3.root).find(".name").val(),
age = $(table_3.root).find(".age").val(),
location = $(table_3.root).find(".location").val();
//noinspection TypeScriptValidateTypes
table_3.update(index, { name: name, age: age, location: location });
table_3.hideExpand();
}
});
jui.ready([ "grid.xtable" ], function(xtable: GridXTable) {
var page = 1;
let xtable_2: GridXTable = xtable("#xtable_2", {
fields: [ "name", "age", "location" ],
resize: true,
sort: true,
buffer: "page",
bufferCount: 20
});
let xtable_2_submit: Function = function() {
var result: any[] = [];
for(var i = 0; i < 1000000; i++) {
result.push({ name: "Alvin" + i, age: Math.floor(Math.random() * 100) + 1, location: "LA" });
}
page = 1;
xtable_2.update(result);
xtable_2.resize();
}
let xtable_2_page: Function = function(no: number) {
page += no;
page = (page < 1) ? 1 : page;
xtable_2.page(page);
}
});
jui.ready([ "grid.xtable" ], function(xtable: GridXTable) {
let xtable_4:GridXTable = xtable("#xtable_4", {
fields: [ "name", "age", "location" ],
data: [
{ name: "Hong", age: "20", location: "Ilsan" },
{ name: "Jung", age: "30", location: "Seoul" },
{ name: "Park", age: "10", location: "Dangjin" }
],
resize: true,
sort: true,
buffer: "s-page",
bufferCount: 20
});
let xtable_4_submit: Function = function(isMulti: boolean) {
if(isMulti) {
xtable_4.filter(function(data: any) {
if(data.age >= 30 || data.name.indexOf("ng") != -1) {
return true;
}
});
} else {
xtable_4.filter(function(data: any) {
if(data.location.indexOf("eo") != -1) {
return true;
}
});
}
}
});
jui.ready([ "grid.xtable" ], function(xtable: GridXTable) {
let xtable_6: GridXTable = xtable("#xtable_6", {
fields: [ "name", "age", "location" ],
resize: true,
sort: true,
width: 800,
scrollWidth: 600,
scrollHeight: 400,
rowHeight: 26,
buffer: "vscroll",
tpl: {
row: "<tr><td><!= name !></td><td><!= age !></td><td><!= location !></td></tr>",
none: "<tr><td colspan='3' class='none' align='center'>Data does not exist.</td></tr>"
}
});
let xtable_6_submit: Function = function() {
var result: any[] = [];
for(var i = 0; i < 1000000; i++) {
result.push({ name: "Alvin" + i, age: Math.floor(Math.random() * 100) + 1, location: "LA" });
}
xtable_6.update(result);
}
});
jui.ready([ "grid.xtable" ], function(xtable: GridXTable) {
let xtable_8: GridXTable = xtable("#xtable_8", {
fields: [ "url", "count" ],
resize: true,
buffer: "vscroll",
rowHeight: 27,
scrollHeight: 300,
tpl: {
row: $("#tpl_row").html(),
none: $("#tpl_none").html()
},
event: {
select: function(row: GridRow, e:any) {
if(row.type == "fold") {
xtable_8.open(row.index);
} else {
xtable_8.fold(row.index);
}
}
}
});
xtable_8.updateTree([
{ index: "0", type: "open", data: { url: "/", count: 105 } },
{ index: "0.0", type: "fold", data: { url: "/css", count: 35 } },
{ index: "0.0.0", type: "fold", data: { url: "/index.css", count: 15 } },
{ index: "0.0.1", type: "fold", data: { url: "/layout.css", count: 15 } },
{ index: "0.0.2", type: "fold", data: { url: "/login.css", count: 5 } },
{ index: "0.1", type: "fold", data: { url: "/js", count: 35 } },
{ index: "0.1.0", type: "fold", data: { url: "/index.js", count: 23 } },
{ index: "0.1.1", type: "fold", data: { url: "/jquery.js", count: 12 } },
{ index: "0.2", type: "fold", data: { url: "/img", count: 0 } },
{ index: "0.2.0", type: "fold", data: { url: "logo.ico", count: 0 } },
{ index: "0.3", type: "fold", data: { url: "/main.jsp", count: 10 } },
{ index: "0.4", type: "fold", data: { url: "/login.jsp", count: 10 } },
{ index: "0.5", type: "fold", data: { url: "/sitemap.xml", count: 10 } },
{ index: "0.6", type: "fold", data: { url: "/package.json", count: 5 } }
]);
});
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"jui-grid-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+1380
View File
File diff suppressed because it is too large Load Diff
+124
View File
@@ -0,0 +1,124 @@
/// <reference types="jui-core"/>
import {jui} from 'jui-core';
import {
UIAccordion, UIAutoComplete, UIColorPicker, UICombo, UIDatePicker, UIDropdown, UIModal, UINotify,
UIPaging, UIProgress, UIProperty, UISelect
} from 'jui';
jui.ready([
'ui.accordion',
'ui.autocomplete',
'ui.colorpicker',
'ui.combo',
'ui.datepicker',
'ui.dropdown',
'ui.modal',
'ui.notify',
'ui.paging',
'ui.progress',
'ui.property',
'ui.select'
], function (
accordion: UIAccordion,
autocomplete: UIAutoComplete,
colorpicker: UIColorPicker,
combo: UICombo,
datepicker: UIDatePicker,
dropdown: UIDropdown,
modal: UIModal,
notify: UINotify,
paging: UIPaging,
progress: UIProgress,
property: UIProperty,
select: UISelect
) {
let a: UIAccordion = accordion("#test", {
multipanel: false
});
console.log(a.activeIndex());
let autoComplete: UIAutoComplete = autocomplete("#test", {
words : []
});
autoComplete.update([]);
let colorPicker: UIColorPicker = colorpicker("#test", {
color: '#FFFF00'
});
console.log(colorPicker.getColor('hex'));
let comboInstance: UICombo = combo("#test", {
keydown: true
})
console.log(comboInstance.getValue());
let datePicker: UIDatePicker = datepicker("#test", {
type: "daily"
});
datePicker.select(Date.now());
datePicker.select(2016, 1, 2);
datePicker.select(new Date());
let dropdownInstance: UIDropdown = dropdown("#test", {
width: 100
})
dropdownInstance.update([]);
dropdownInstance.hide();
dropdownInstance.reload();
let m : UIModal = modal("#test", {autoHide: true});
m.show();
let n: UINotify = notify("#test");
n.add({ title: "Caution message Send!!!", message: "Feb 15, 2013-12-24 02:24:19", color: 'warning' }, 1000);
n.add({ title: "Caution message Send!!!", message: "Feb 15, 2013-12-24 02:24:19", color: 'success' }, 1000);
n.reset();
let p: UIPaging = paging("#test", { count :100, pageCount : 5 });
p.first();
p.last();
p.next();
p.prev();
p.page(10);
let prog: UIProgress = progress("#test", { striped: true });
console.log(prog.getValue());
prog.setValue(100);
let propertyView: UIProperty = property("#test", {
items : [
{ type : 'group', title : 'Sample Category'},
{ type : 'text', title : 'Category Name', key: 'sample-category-name', value : 'test'}
]
})
console.log(propertyView.getValue());
let selectInstance: UISelect = select("#test", {
items : [
{ type : 'item', value : '0', text : 'first', html : '<div>test</div>', selected : true },
{ type : 'divider' }
],
multi: true,
placeholder: 'Sample Select'
});
console.log(selectInstance.getValue());
});
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"jui-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+136 -108
View File
@@ -1,4 +1,4 @@
// Type definitions for Leaflet.markercluster v0.4.0
// Type definitions for Leaflet.markercluster 1.0
// Project: https://github.com/Leaflet/Leaflet.markercluster
// Definitions by: Robert Imig <https://github.com/rimig>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -6,137 +6,165 @@
/// <reference types="leaflet" />
declare namespace L {
export interface MarkerCluster extends L.Marker {
/*
* Recursively retrieve all child markers of this cluster.
*/
getAllChildMarkers(): Marker[];
/*
* Returns the count of how many child markers we have.
*/
getChildCount(): number;
/*
* Zoom to the minimum of showing all of the child markers, or the extents of this cluster.
*/
zoomToBounds(): void;
/*
* Returns the cluster bounds.
*/
getBounds(): LatLngBounds;
}
export interface MarkerClusterGroupOptions {
/*
* When you mouse over a cluster it shows the bounds of its markers.
*/
showCoverageOnHover?: boolean;
/*
* When you mouse over a cluster it shows the bounds of its markers.
*/
showCoverageOnHover?: boolean;
/*
* When you click a cluster we zoom to its bounds.
*/
zoomToBoundsOnClick?: boolean;
/*
* When you click a cluster we zoom to its bounds.
*/
zoomToBoundsOnClick?: boolean;
/*
* When you click a cluster at the bottom zoom level we spiderfy it
* so you can see all of its markers.
*/
spiderfyOnMaxZoom?: boolean;
/*
* When you click a cluster at the bottom zoom level we spiderfy it
* so you can see all of its markers.
*/
spiderfyOnMaxZoom?: boolean;
/*
* Clusters and markers too far from the viewport are removed from the map
* for performance.
*/
removeOutsideVisibleBounds?: boolean;
/*
* Clusters and markers too far from the viewport are removed from the map
* for performance.
*/
removeOutsideVisibleBounds?: boolean;
/*
* Smoothly split / merge cluster children when zooming and spiderfying.
* If L.DomUtil.TRANSITION is false, this option has no effect (no animation is possible).
*/
animate?: boolean;
/*
* Smoothly split / merge cluster children when zooming and spiderfying.
* If L.DomUtil.TRANSITION is false, this option has no effect (no animation is possible).
*/
animate?: boolean;
/*
* If set to true (and animate option is also true) then adding individual markers to the
* MarkerClusterGroup after it has been added to the map will add the marker and animate it
* into the cluster. Defaults to false as this gives better performance when bulk adding markers.
* addLayers does not support this, only addLayer with individual Markers.
*/
animateAddingMarkers?: boolean;
/*
* If set to true (and animate option is also true) then adding individual markers to the
* MarkerClusterGroup after it has been added to the map will add the marker and animate it
* into the cluster. Defaults to false as this gives better performance when bulk adding markers.
* addLayers does not support this, only addLayer with individual Markers.
*/
animateAddingMarkers?: boolean;
/*
* If set, at this zoom level and below markers will not be clustered. This defaults to disabled.
*/
disableClusteringAtZoom?: number;
/*
* If set, at this zoom level and below markers will not be clustered. This defaults to disabled.
*/
disableClusteringAtZoom?: number;
/*
* The maximum radius that a cluster will cover from the central marker (in pixels). Default 80.
* Decreasing will make more, smaller clusters. You can also use a function that accepts
* the current map zoom and returns the maximum cluster radius in pixels
*/
maxClusterRadius?: number | ((zoom: number) => number);
/*
* The maximum radius that a cluster will cover from the central marker (in pixels). Default 80.
* Decreasing will make more, smaller clusters. You can also use a function that accepts
* the current map zoom and returns the maximum cluster radius in pixels
*/
maxClusterRadius?: number | ((zoom: number) => number);
/*
* Options to pass when creating the L.Polygon(points, options) to show the bounds of a cluster.
* Defaults to empty
*/
polygonOptions?: PolylineOptions;
/*
* Options to pass when creating the L.Polygon(points, options) to show the bounds of a cluster.
* Defaults to empty
*/
polygonOptions?: PolylineOptions;
/*
* If set to true, overrides the icon for all added markers to make them appear as a 1 size cluster.
*/
singleMarkerMode?: boolean;
/*
* If set to true, overrides the icon for all added markers to make them appear as a 1 size cluster.
*/
singleMarkerMode?: boolean;
/*
* Allows you to specify PolylineOptions to style spider legs.
* By default, they are { weight: 1.5, color: '#222', opacity: 0.5 }.
*/
spiderLegPolylineOptions?: PolylineOptions;
/*
* Allows you to specify PolylineOptions to style spider legs.
* By default, they are { weight: 1.5, color: '#222', opacity: 0.5 }.
*/
spiderLegPolylineOptions?: PolylineOptions;
/*
* Increase from 1 to increase the distance away from the center that spiderfied markers are placed.
* Use if you are using big marker icons (Default: 1).
*/
spiderfyDistanceMultiplier?: number;
/*
* Increase from 1 to increase the distance away from the center that spiderfied markers are placed.
* Use if you are using big marker icons (Default: 1).
*/
spiderfyDistanceMultiplier?: number;
/*
* Function used to create the cluster icon
*/
iconCreateFunction?: any;
/*
* Function used to create the cluster icon
*/
iconCreateFunction?: ((cluster: L.MarkerCluster) => L.Icon);
/*
* Boolean to split the addLayers processing in to small intervals so that the page does not freeze.
*/
chunkedLoading?: boolean;
/*
* Boolean to split the addLayers processing in to small intervals so that the page does not freeze.
*/
chunkedLoading?: boolean;
/*
* Time delay (in ms) between consecutive periods of processing for addLayers. Default to 50ms.
*/
chunkDelay?: number;
/*
* Time delay (in ms) between consecutive periods of processing for addLayers. Default to 50ms.
*/
chunkDelay?: number;
}
export class MarkerClusterGroup extends FeatureGroup<ILayer> {
constructor();
constructor(options: MarkerClusterGroupOptions);
export interface MarkerClusterGroup extends FeatureGroup {
/*
* Bulk methods for adding and removing markers and should be favoured over the
* single versions when doing bulk addition/removal of markers.
*/
addLayers(layers:ILayer[]):MarkerClusterGroup;
removeLayers(layers:ILayer[]):MarkerClusterGroup;
/*
* Bulk methods for adding and removing markers and should be favoured over the
* single versions when doing bulk addition/removal of markers.
*/
addLayers(layers: Layer[]): this;
removeLayers(layers: Layer[]): this;
clearLayers():MarkerClusterGroup;
clearLayers(): this;
/*
* If you have a marker in your MarkerClusterGroup and you want to get the visible
* parent of it
*/
getVisibleParent(marker: Marker): Marker;
/*
* If you have a marker in your MarkerClusterGroup and you want to get the visible
* parent of it
*/
getVisibleParent(marker: Marker): Marker;
/*
* If you have customized the clusters icon to use some data from the contained markers,
* and later that data changes, use this method to force a refresh of the cluster icons.
*/
refreshClusters():MarkerClusterGroup;
refreshClusters(layerGroup:LayerGroup<ILayer>):MarkerClusterGroup;
refreshClusters(marker: Marker):MarkerClusterGroup;
refreshClusters(markers: Marker[]):MarkerClusterGroup;
/*
* If you have customized the clusters icon to use some data from the contained markers,
* and later that data changes, use this method to force a refresh of the cluster icons.
*/
refreshClusters(clusters?: Marker | Marker[] | LayerGroup | {[index: string]: Layer}): this;
/*
* Returns the total number of markers contained within that cluster.
*/
getChildCount(): number;
/*
* Returns the total number of markers contained within that cluster.
*/
getChildCount(): number;
/*
* Returns the array of total markers contained within that cluster.
*/
getAllChildMarkers(): Marker[];
/*
* Returns the array of total markers contained within that cluster.
*/
getAllChildMarkers(): Marker[];
/*
* Zooms to show the given marker (spiderfying if required),
* calls the callback when the marker is visible on the map.
*/
zoomToShowLayer(layer: any, callback: () => void): void;
/*
* Returns true if the given layer (marker) is in the cluster.
*/
hasLayer(layer: Layer): boolean;
/*
* Zooms to show the given marker (spiderfying if required),
* calls the callback when the marker is visible on the map.
*/
zoomToShowLayer(layer: Layer, callback?: () => void): void;
}
/*
* Create a marker cluster group, optionally given marker cluster group options.
*/
export function markerClusterGroup(options?: MarkerClusterGroupOptions): MarkerClusterGroup;
}
@@ -1,19 +1,78 @@
var map: L.Map;
var markerClusterGroup: L.MarkerClusterGroup;
const polylineOptions: L.PolylineOptions = {};
const icon: L.Icon = L.icon({ iconUrl: 'foo' });
// CircleMarker
var circleMarker: L.CircleMarker = new L.CircleMarker(new L.LatLng(0, 0));
let markerClusterGroupOptions: L.MarkerClusterGroupOptions = {};
markerClusterGroupOptions = {
showCoverageOnHover: true,
zoomToBoundsOnClick: false,
spiderfyOnMaxZoom: true,
removeOutsideVisibleBounds: false,
animate: true,
animateAddingMarkers: false,
disableClusteringAtZoom: 12,
maxClusterRadius: 40,
polygonOptions: polylineOptions,
singleMarkerMode: true,
spiderLegPolylineOptions: polylineOptions,
spiderfyDistanceMultiplier: 2,
iconCreateFunction: (cluster: L.MarkerCluster) => {
const childMarkers: L.Marker[] = cluster.getAllChildMarkers();
const childCount: number = cluster.getChildCount();
cluster.zoomToBounds();
const bounds: L.LatLngBounds = cluster.getBounds();
return icon;
},
chunkedLoading: false,
chunkDelay: 100
}
markerClusterGroup.addLayer(circleMarker);
map.addLayer(markerClusterGroup);
map.removeLayer(markerClusterGroup);
let markerClusterGroup: L.MarkerClusterGroup;
markerClusterGroup = L.markerClusterGroup();
markerClusterGroup = L.markerClusterGroup(markerClusterGroupOptions);
// Marker
var marker = new L.Marker(new L.LatLng(0, 0));
let map = L.map('foo');
markerClusterGroup.addLayers([circleMarker, marker]);
map.addLayer(markerClusterGroup);
markerClusterGroup.refreshClusters();
map.removeLayer(markerClusterGroup);
markerClusterGroup = markerClusterGroup.addTo(map);
map = map
.addLayer(markerClusterGroup)
.removeLayer(markerClusterGroup);
const latLng: L.LatLng = L.latLng(10, 10);
const layer: L.Layer = L.marker(latLng);
const layers: L.Layer[] = [layer];
let marker: L.Marker = L.marker(latLng);
let markers: L.Marker[] = [marker];
const layerGroup: L.LayerGroup = L.layerGroup(layers);
marker = markerClusterGroup.getVisibleParent(marker);
markerClusterGroup = markerClusterGroup
// Layers
.addLayer(layer)
.removeLayer(layer)
.addLayers(layers)
.removeLayers(layers)
.clearLayers()
// RefreshClusters
.refreshClusters()
.refreshClusters(layerGroup)
.refreshClusters(marker)
.refreshClusters(markers)
.refreshClusters(markerClusterGroup)
.refreshClusters({ id_any: layer });
const childCount: number = markerClusterGroup.getChildCount();
markers = markerClusterGroup.getAllChildMarkers();
markerClusterGroup.zoomToShowLayer(marker);
markerClusterGroup.zoomToShowLayer(marker, () => {});
let hasLayer: boolean;
hasLayer = markerClusterGroup.hasLayer(layer);
hasLayer = markerClusterGroup.hasLayer(marker);
+1 -1
View File
@@ -1,5 +1,5 @@
{
"dependencies": {
"@types/leaflet": "^0.7"
"@types/leaflet": "^1.0"
}
}
+4 -1
View File
@@ -4,8 +4,11 @@
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "../tslint.json"
}
+428
View File
@@ -0,0 +1,428 @@
// Type definitions for libpq 1.8
// Project: https://github.com/brianc/node-libpq#readme
// Definitions by: Vlad Rindevich <https://github.com/Lodin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import {EventEmitter} from 'events';
import {Buffer} from 'buffer';
declare namespace Libpq {
export interface NotifyMsg {
relname: string;
extra: string;
be_pid: number;
}
export interface ResultError {
severity: string;
sqlState: string;
messagePrimary: string;
messageDetail?: string;
messageHint?: string;
statementPosition?: string;
internalPosition?: string;
internalQuery?: string;
context?: string;
schemaName?: string;
tableName?: string;
dataTypeName?: string;
constraintName?: string;
sourceFile: string;
sourceLine: string;
sourceFunction: string;
}
}
declare class Libpq extends EventEmitter {
/**
* Current connection state.
*/
connected: boolean;
/**
* Issues a request to cancel the currently executing query on this instance of libpq.
*
* @returns {(boolean|string)} true if the cancel request was sent; a string error message if
* the cancel request failed for any reason. The string will
* contain the error message provided by libpq.
*/
cancel(): true|string;
/**
* Manually frees the memory associated with a PGresult pointer. Generally this is called
* for you, but if you absolutely want to free the pointer yourself, you can.
*/
clear(): void;
/**
* @returns {string} the status string associated with a result. Something akin to INSERT 3 0
* if you inserted 3 rows.
*/
cmdStatus(): string;
/**
* @returns {string} the number of tuples (rows) affected by the command. Even though this is a
* number, it is returned as a string to mirror libpq's behavior.
*/
cmdTuples(): string;
/**
* (async) Connects to a PostgreSQL backend server process.
*
* This function actually calls the PQconnectdb blocking connection method in a background
* thread within node's internal thread-pool. There is a way to do non-blocking network I/O
* for some of the connecting with libpq directly, but it still blocks when your local file
* system looking for config files, SSL certificates, .pgpass file, and doing possible dns
* resolution. Because of this, the best way to get fully non-blocking is to juse use
* libuv_queue_work and let node do it's magic and so that's what I do. This function does
* not block.
*
* @param {string} connectParams an optional string
* @param {Function} callback mandatory. It is called when the connection has successfully been
* established.
*/
connect(connectParams: string, callback: (err?: Error) => void): void;
connect(callback: (err?: Error) => void): void;
/**
* (sync) Attempts to connect to a PostgreSQL server. BLOCKS until it either succeedes, or
* fails. If it fails it will throw an exception.
*
* @param {string} connectionParams an optional string
*/
connectSync(connectionParams?: string): void;
/**
* Reads waiting data from the socket. If the socket is not readable and you call this it will
* block so be careful and only call it within the readable callback for the most part.
*
* @returns {boolean} true if data was read; false if there was an error. You can access
* error details with [[Libpq.errorMessage]].
*/
consumeInput(): boolean
/**
* Retrieves the last error message from the connection. This is intended to be used after most
* functions which return an error code to get more detailed error information about the
* connection. You can also check this before issuing queries to see if your connection has
* been lost.
*
* @returns {string}
*/
errorMessage(): string;
/**
* Exact copy of the PQescapeIdentifier function within libpq. Requires an established
* connection but does not perform any I/O.
*
* @param {string} input
*/
escapeIdentifier(input: string): string;
/**
* Exact copy of the PQescapeLiteral function within libpq. Requires an established connection
* but does not perform any I/O.
*
* @param {string} input
*/
escapeLiteral(input: string): string;
/**
* (sync) Sends a command to the backend and blocks until a result is received.
*
* @param {string} [commandText=""] a required string of the query.
*/
exec(commandText?: string): void;
/**
* (sync) Sends a command and parameters to the backend and blocks until a result is received.
*
* @param {string} [commandText=""] a required string of the query.
* @param {Array.<(string|number)>} [parameters=[]] a required array of string values
* corresponding to each parameter in the
* commandText.
*/
execParams(commandText?: string, parameters?: Array<string|number>): void;
/**
* (sync) Sends a command to the server to execute a previously prepared statement. Blocks
* until the results are returned.
*
* @param {string} [statementName=""] a required string of the name of the prepared statement.
* @param {Array.<(string|number)>} [parameters=[]] the parameters to pass to the prepared
* statement.
*/
execPrepared(statementName?: string, parameters?: Array<string|number>): void;
/**
* Disconnects from the backend and cleans up all memory used by the libpq connection.
*/
finish(): void;
/**
* Flushes buffered data to the socket.
*
* @returns {number} 1 if socket is not write-ready at which case you should call
* [[Libpq.writable]] with a callback and wait for the socket to be writable
* and then call [[Libpq.flush]] again; 0 if all data was flushed; -1 if
* there was an error.
*/
flush(): number;
/**
* Retrieve the name of the field (column) at the given offset. Offset starts at 0.
*
* @param {number} fieldNumber
* @returns {string}
*/
fname(fieldNumber: number): string;
/**
* Retrieve the Oid of the field (column) at the given offset. Offset starts at 0.
*
* @param {number} fieldNumber
* @returns {number}
*/
ftype(fieldNumber: number): number;
/**
* After issuing a successfuly command like COPY table TO stdout gets copy data from the
* connection.
*
* @param {boolean} [async=false] a boolean. Pass false to block waiting for data from the
* backend. Defaults to false.
*
* @returns {Buffer|number} a node buffer if there is data available; 0 if the copy is still in
* progress (only if you have called [[Libpq.setNonBlocking]](true));
* -1 if the copy is completed; -2 if there was an error.
*/
getCopyData(async?: boolean): Buffer|number;
/**
* @param {number} tupleNumber
* @param {number} fieldNumber
* @returns {boolean} true if the value at the given offsets is actually null. Otherwise
* returns false. This is because [[Libpq.getvalue]] returns an empty
* string for both an actual empty string and for a null value. Weird, huh?
*/
getisnull(tupleNumber: number, fieldNumber: number): boolean;
/**
* Parses received data from the server into a PGresult struct and sets a pointer internally to
* the connection object to this result.
*
* Warning: this function will block if libpq is waiting on async results to be returned from
* the server. Call [[Libpq.isBusy]] to determine if this command will block.
*
* @returns {boolean} true if libpq was able to read buffered data & parse a result object;
* false if there are no results waiting to be parsed. Generally doing async
* style queries you'll call this repeadedly until it returns false and then
* use the result accessor methods to pull results out of the current result
* set.
*/
getResult(): boolean;
/**
* Retrieve the text value at a given tuple (row) and field (column) offset. Both offsets start
* at 0. A null value is returned as the empty string ''.
*
* @param {number} tupleNumber
* @param {number} [fieldNumber]
* @returns {string}
*/
getvalue(tupleNumber: number, fieldNumber?: number): string;
/**
* @returns {boolean} true if calling [[Libpq.consumeInput]] would block waiting for more
* data; false if all data has been read from the socket. Once this returns false it is
* safe to call [[Libpq.getResult]].
*/
isBusy(): boolean;
/**
* @returns {boolean} true if non-blocking mode is enabled; false if disabled.
*/
isNonBlocking(): boolean;
/**
* Retrieve the number of fields (columns) from the result.
*
* @returns {number}
*/
nfields(): number;
/**
* Checks for NOTIFY messages that have come in. If any have been received they will be in the
* following format:
*
* @example ```ts
*
* var msg = {
* relname: 'name of channel',
* extra: 'message passed to notify command',
* be_pid: 130
* }
* ```
*
* @returns {Libpq.NotifyMsg}
*/
notifies(): Libpq.NotifyMsg;
/**
* Retrieve the number of tuples (rows) from the result.
*
* @returns {number}
*/
ntuples(): number;
/**
* After issuing a successful command like COPY table FROM stdin you can start putting buffers
* directly into the databse with this function.
*
* @param {Buffer} buffer a required node buffer of text data such as
* Buffer('column1\tcolumn2\n')
*
* @returns {number} 1 if sent succesfully; 0 if the command would block (only if you have
* called [[Libpq.setNonBlocking]](true)); -1 if there was an error sending
* the command.
*/
putCopyData(buffer: Buffer): number;
/**
* Signals the backed your copy procedure is complete. If you pass errorMessage it will be sent
* to the backend and effectively cancel the copy operation.
*
* @param {string} [errorMessage] an optional string you can pass to cancel the copy operation.
*
* @returns {number} 1 if sent succesfully; 0 if the command would block (only if you have
* called [[Libpq.setNonBlocking]](true)); -1 if there was an error sending
* the command.
*/
putCopyEnd(errorMessage?: string): number;
/**
* (sync) Sends a named statement to the server to be prepared for later execution. blocks
* until a result from the prepare operation is received.
*
* @param {string} [statementName=""] a required string of name of the statement to prepare.
* @param {string} [commandText=""] a required string of the query.
* @param {number} [nParams=0] a count of the number of parameters in the commandText.
*/
prepare(statementName?: string, commandText?: string, nParams?: number): void;
/**
* Retrieves detailed error information from the current result object. Very similar to
* PQresultErrorField() except instead of passing a fieldCode and retrieving a single field,
* retrieves all fields from the error at once on a single object. The object returned is a
* simple hash, not an instance of an error object.
*
* If you wanted to access PG_DIAG_MESSAGE_DETAIL you would do the following:
* @example ```ts
*
* console.log(pq.errorFields().messageDetail);
* ```
* @returns {Libpq.ResultError}
*/
resultErrorFields(): Libpq.ResultError;
/**
* Retrieves the error message from the result. This will return null if the result does not
* have an error.
*
* @returns {string}
*/
resultErrorMessage(): string;
/**
* @returns {string} either PGRES_COMMAND_OK or PGRES_FATAL_ERROR depending on the status of
* the last executed command.
*/
resultStatus(): string;
/**
* (async) Sends a query to the server to be processed.
*
* @param {string} [commandText=""] a required string containing the query text.
* @returns {boolean} true if the command was sent succesfully or false if it failed to send.
*/
sendQuery(commandText?: string): boolean;
/**
* (async) Sends a query and to the server to be processed.
*
* @param {string} [commandText=""] a required string containing the query text.
* @param {Array.<(string|number)>} [parameters=[]] an array of parameters as strings used in
* the parameterized query.
* @returns {boolean} true if the command was sent succesfully or false if it failed to send.
*/
sendQueryParams(commandText?: string, parameters?: Array<string|number>): boolean;
/**
* (async) Sends a request to the backend to prepare a named statement with the given name.
*
* @param {string} [statementName=""] a required string of name of the statement to prepare.
* @param {string} [commandText=""] a required string of the query.
* @param {number} [nParams=0] a count of the number of parameters in the commandText.
* @returns {boolean} true if the command was sent succesfully or false if it failed to send.
*/
sendPrepare(statementName?: string, commandText?: string, nParams?: number): boolean;
/**
* (async) Sends a request to execute a previously prepared statement.
*
* @param {string} [statementName=""] a required string of the name of the prepared statement.
* @param {string[]} [parameters=[]] the parameters to pass to the prepared statement.
* @returns {boolean} true if the command was sent succesfully or false if it failed to send.
*/
sendQueryPrepared(statementName?: string, parameters?: string[]): boolean;
/**
* @returns the version of the connected PostgreSQL backend server as a number.
*/
serverVersion(): number;
/**
* Toggle the socket blocking on write.
*
* @param {boolean} [nonBlocking] true to set the connection to use non-blocking writes, false to
* use blocking writes.
*
* @returns {boolean} true if the socket's state was succesfully toggled, false if there was
* an error.
*/
setNonBlocking(nonBlocking?: boolean): boolean;
/**
* @returns {number} an int representing the file descriptor for the socket used internally by
* the connection.
*/
socket(): number;
/**
* This uses libuv to start a read watcher on the socket open to the backend. As soon as this
* socket becomes readable the pq instance will emit a readable event. It is up to you to call
* [[Libpq.consumeInput]] one or more times to clear this read notification or it will
* continue to emit read events over and over and over. The exact flow is outlined [here] under
* the documentation for PQisBusy.
*/
startReader(): void;
/**
* Tells libuv to stop the read watcher on the connection socket.
*/
stopReader(): void;
/**
* Call this to make sure the socket has flushed all data to the operating system. Once the
* socket is writable, your callback will be called. Usefully when using PQsetNonBlocking
* and PQflush for async writing.
*
* @param {Function} callback
*/
writable(callback: () => void): void;
}
export = Libpq;
+828
View File
@@ -0,0 +1,828 @@
/// <reference types="node" />
/// <reference types="mocha" />
import {Buffer} from 'buffer';
import * as assert from 'assert';
import * as async from 'async';
import * as PQ from 'libpq';
import * as _ from 'lodash';
declare const ok: Function;
const createTable = (pq: PQ) => {
pq.exec('CREATE TEMP TABLE test_data(name text, age int)');
console.log(pq.resultErrorMessage());
pq.exec("INSERT INTO test_data(name, age) VALUES ('brian', 32), ('aaron', 30), ('', null);")
};
const blink = (n: number, cb: Function) => {
const connections: PQ[] = [];
for (let i = 0; i < 30; i++) {
connections.push(new PQ())
}
const connect = (con: PQ, cb: (err?: Error) => void) => {
con.connect(cb);
};
async.each(connections, connect, ok(() => {
connections.forEach((con) => {
con.finish();
});
cb();
}))
};
const queryText = "SELECT * FROM generate_series(1, 1000)";
const query = (pq: PQ, cb: Function) => {
const readError = (message?: string) => {
cleanup();
return cb(new Error(message || pq.errorMessage()));
};
const onReadable = () => {
if (!pq.consumeInput()) {
return readError();
}
if (pq.isBusy()) {
return;
}
pq.getResult();
if (pq.getResult()) {
return readError('Only one result at a time is accepted');
}
cleanup();
return cb(null, [])
};
const sent = pq.sendQuery(queryText);
if (!sent) return cb(new Error(pq.errorMessage()));
console.log('sent query');
const cleanup = () => {
pq.removeListener('readable', onReadable);
pq.stopReader();
};
pq.on('readable', onReadable);
pq.startReader();
};
describe('async connection', () => {
it('works', (done) => {
const pq = new PQ();
assert(!pq.connected, 'should have connected set to falsy');
pq.connect(err => {
assert.ifError(err);
pq.exec('SELECT NOW()');
assert.equal(pq.ntuples(), 1);
done();
});
});
it('works with hard-coded connection parameters', (done) => {
const pq = new PQ();
const conString = `host=${process.env.PGHOST || 'localhost'}`;
pq.connect(conString, done);
});
it('returns an error to the callback if connection fails', (done) => {
new PQ().connect('host=asldkfjasldkfjalskdfjasdf', err => {
assert(err, 'should have passed an error');
done();
});
});
it('respects the active domain', (done) => {
const pq = new PQ();
const domain = require('domain').create();
domain.run(() => {
const activeDomain = process.domain;
assert(activeDomain, 'Should have an active domain');
pq.connect(() => {
assert.strictEqual(process.domain, activeDomain, 'Active domain is lost');
done();
});
});
});
});
const consume = (pq: PQ, cb: Function) => {
if (!pq.isBusy()) return cb();
pq.startReader();
const onReadable = () => {
assert(pq.consumeInput(), pq.errorMessage());
if (pq.isBusy()) {
console.log('consuming a 2nd buffer of input later...');
return;
}
pq.removeListener('readable', onReadable);
pq.stopReader();
cb();
};
pq.on('readable', onReadable);
};
describe('async simple query', () => {
let pq: PQ;
it('dispatches simple query', (done: Function) => {
assert(pq.setNonBlocking(true));
pq.writable(() => {
const success = pq.sendQuery('SELECT 1');
assert.strictEqual(pq.flush(), 0, 'Should have flushed all data to socket');
assert(success, pq.errorMessage());
consume(pq, () => {
assert.ifError(pq.errorMessage());
assert(pq.getResult());
assert.strictEqual(pq.getResult(), false);
assert.strictEqual(pq.ntuples(), 1);
assert.strictEqual(pq.getvalue(0, 0), '1');
done();
});
});
});
it('dispatches parameterized query', (done: Function) => {
const success = pq.sendQueryParams('SELECT $1::text as name', ['Brian']);
assert(success, pq.errorMessage());
assert.strictEqual(pq.flush(), 0, 'Should have flushed query text & parameters');
consume(pq, () => {
assert.ifError(pq.errorMessage());
assert(pq.getResult());
assert.strictEqual(pq.getResult(), false);
assert.strictEqual(pq.ntuples(), 1);
assert.equal(pq.getvalue(0, 0), 'Brian');
done();
})
});
it('dispatches named query', (done: Function) => {
const statementName = 'async-get-name';
const success = pq.sendPrepare(statementName, 'SELECT $1::text as name', 1);
assert(success, pq.errorMessage());
assert.strictEqual(pq.flush(), 0, 'Should have flushed query text');
consume(pq, () => {
assert.ifError(pq.errorMessage());
//first time there should be a result
assert(pq.getResult());
//call 'getResult' until it returns false indicating
//there is no more input to consume
assert.strictEqual(pq.getResult(), false);
//since we only prepared a statement there should be
//0 tuples in the result
assert.equal(pq.ntuples(), 0);
//now execute the previously prepared statement
const success = pq.sendQueryPrepared(statementName, ['Brian']);
assert(success, pq.errorMessage());
assert.strictEqual(pq.flush(), 0, 'Should have flushed parameters');
consume(pq, () => {
assert.ifError(pq.errorMessage());
//consume the result of the query execution
assert(pq.getResult());
assert.equal(pq.ntuples(), 1);
assert.equal(pq.getvalue(0, 0), 'Brian');
//call 'getResult' again to ensure we're finished
assert.strictEqual(pq.getResult(), false);
done();
});
});
});
});
describe('cancel a request', () => {
it('works', (done) => {
const pq = new PQ();
pq.connectSync();
const sent = pq.sendQuery('pg_sleep(5000)');
assert(sent, 'should have sent');
const canceled = pq.cancel();
assert.strictEqual(canceled, true, 'should have canceled');
const hasResult = pq.getResult();
assert(hasResult, 'should have a result');
assert.equal(pq.resultStatus(), 'PGRES_FATAL_ERROR');
assert.equal(pq.getResult(), false);
pq.exec('SELECT NOW()');
done();
});
});
describe('Constructing multiple', () => {
it('works all at once', () => {
for (let i = 0; i < 1000; i++) {
const pq = new PQ();
}
});
it('connects and disconnects each client', (done) => {
const connect = (n: number, cb: (err?: Error) => void) => {
const pq = new PQ();
pq.connect(cb);
};
async.times(30, connect, done);
});
});
describe('COPY IN', () => {
let pq: PQ;
before(() => {
pq = new PQ();
pq.connectSync();
createTable(pq);
});
after(() => {
pq.finish();
});
it('check existing data assuptions', () => {
pq.exec('SELECT COUNT(*) FROM test_data');
assert.equal(pq.getvalue(0, 0), 3);
});
it('copies data in', () => {
const success = pq.exec('COPY test_data FROM stdin');
assert.equal(pq.resultStatus(), 'PGRES_COPY_IN');
const buffer = new Buffer("bob\t100\n", 'utf8');
const res1 = pq.putCopyData(buffer);
assert.strictEqual(res1, 1);
const res2 = pq.putCopyEnd();
assert.strictEqual(res2, 1);
while (pq.getResult()) {
}
pq.exec('SELECT COUNT(*) FROM test_data');
assert.equal(pq.getvalue(0, 0), 4);
});
it('can cancel copy data in', () => {
const success = pq.exec('COPY test_data FROM stdin');
assert.equal(pq.resultStatus(), 'PGRES_COPY_IN');
const buffer = new Buffer("bob\t100\n", 'utf8');
const res1 = pq.putCopyData(buffer);
assert.strictEqual(res1, 1);
const res2 = pq.putCopyEnd('cancel!');
assert.strictEqual(res2, 1);
while (pq.getResult()) {
}
assert(pq.errorMessage());
assert(
pq.errorMessage().includes('cancel!'),
`${pq.errorMessage()} should have contained "cancel!"`
);
pq.exec('SELECT COUNT(*) FROM test_data');
assert.equal(pq.getvalue(0, 0), 4);
});
});
describe('COPY OUT', () => {
let pq: PQ;
before(() => {
pq = new PQ();
pq.connectSync();
createTable(pq);
});
after(() => {
pq.finish();
});
const getRow = (pq: PQ, expected: string) => {
const result = <Buffer> pq.getCopyData(false);
assert(result instanceof Buffer, 'Result should be a buffer');
assert.equal(result.toString('utf8'), expected);
};
it('copies data out', () => {
pq.exec('COPY test_data TO stdin');
assert.equal(pq.resultStatus(), 'PGRES_COPY_OUT');
getRow(pq, 'brian\t32\n');
getRow(pq, 'aaron\t30\n');
getRow(pq, '\t\\N\n');
assert.strictEqual(<number> pq.getCopyData(), -1);
});
});
describe('without being connected', () => {
it('exec fails', () => {
const pq = new PQ();
pq.exec();
assert.equal(pq.resultStatus(), 'PGRES_FATAL_ERROR');
assert(pq.errorMessage());
});
it('fails on async query', () => {
const pq = new PQ();
const success = pq.sendQuery('blah');
assert.strictEqual(success, false);
assert.equal(pq.resultStatus(), 'PGRES_FATAL_ERROR');
assert(pq.errorMessage());
});
it('throws when reading while not connected', () => {
const pq = new PQ();
assert.throws(() => {
pq.startReader();
});
});
it('throws when writing while not connected', () => {
const pq = new PQ();
assert.throws(() => {
pq.writable(() => {
});
});
});
});
describe('error info', () => {
let pq: PQ;
before(() => {
pq = new PQ();
pq.connectSync();
createTable(pq);
});
after(() => {
pq.finish();
});
describe('when there is no error', () => {
it('everything is null', () => {
pq.exec('SELECT NOW()');
assert(!pq.errorMessage(), pq.errorMessage());
assert.equal(pq.ntuples(), 1);
assert(pq.resultErrorFields(), undefined);
});
});
describe('when there is an error', () => {
it('sets all error codes', () => {
pq.exec('INSERT INTO test_data VALUES(1, NOW())');
assert(pq.errorMessage());
const err = pq.resultErrorFields();
assert.notEqual(err, null);
assert.equal(err.severity, 'ERROR');
assert.equal(err.sqlState, 42804);
assert.equal(err.messagePrimary, 'column "age" is of type integer but expression is of type timestamp with time zone');
assert.equal(err.messageDetail, undefined);
assert.equal(err.messageHint, 'You will need to rewrite or cast the expression.');
assert.equal(err.statementPosition, 33);
assert.equal(err.internalPosition, undefined);
assert.equal(err.internalQuery, undefined);
assert.equal(err.context, undefined);
assert.equal(err.schemaName, undefined);
assert.equal(err.tableName, undefined);
assert.equal(err.dataTypeName, undefined);
assert.equal(err.constraintName, undefined);
assert.equal(err.sourceFile, "parse_target.c");
assert(parseInt(err.sourceLine));
assert.equal(err.sourceFunction, "transformAssignedExpr");
});
});
});
describe('escapeLiteral', () => {
it('fails to escape when the server is not connected', () => {
const pq = new PQ();
const result = pq.escapeLiteral('test');
assert.strictEqual(result, null);
assert(pq.errorMessage());
});
it('escapes a simple string', () => {
const pq = new PQ();
pq.connectSync();
const result = pq.escapeLiteral('bang');
assert.equal(result, "'bang'");
});
it('escapes a bad string', () => {
const pq = new PQ();
pq.connectSync();
const result = pq.escapeLiteral("'; TRUNCATE TABLE blah;");
assert.equal(result, "'''; TRUNCATE TABLE blah;'");
});
});
describe('escapeIdentifier', () => {
it('fails when the server is not connected', () => {
const pq = new PQ();
const result = pq.escapeIdentifier('test');
assert.strictEqual(result, null);
assert(pq.errorMessage());
});
it('escapes a simple string', () => {
const pq = new PQ();
pq.connectSync();
const result = pq.escapeIdentifier('bang');
assert.equal(result, '"bang"');
});
});
describe('connecting', () => {
it('works', () => {
const client = new PQ();
client.connectSync();
});
});
describe('many connections', () => {
it('works', (done) => {
async.timesSeries(10, blink, done)
})
});
describe('connectSync', () => {
it('works 50 times in a row', () => {
const pqs = _.times(50, () => new PQ());
pqs.forEach((pq) => {
pq.connectSync();
});
pqs.forEach((pq) => {
pq.finish();
});
});
});
describe('connect async', () => {
const total = 50;
it(`works ${total} times in a row`, (done) => {
const pqs = _.times(total, () => new PQ());
let count = 0;
const connect = (cb: Function) => {
pqs.forEach((pq) => {
pq.connect((err) => {
assert.ifError(err);
count++;
pq.startReader();
if (count == total) {
cb();
}
});
});
};
connect(() => {
pqs.forEach((pq) => {
pq.stopReader();
pq.finish();
});
done();
});
});
});
describe('multiple queries', () => {
const pq = new PQ();
before((done) => {
pq.connect(done)
});
it('first query works', (done) => {
query(pq, done);
});
it('second query works', (done) => {
query(pq, done);
});
it('third query works', (done) => {
query(pq, done);
});
});
describe('set & get non blocking', () => {
let pq: PQ;
before(() => {
pq = new PQ();
pq.connectSync();
createTable(pq);
});
after(() => {
pq.finish();
});
it('is initially set to false', () => {
assert.strictEqual(pq.isNonBlocking(), false);
});
it('can switch back and forth', () => {
assert.strictEqual(pq.setNonBlocking(true), true);
assert.strictEqual(pq.isNonBlocking(), true);
assert.strictEqual(pq.setNonBlocking(), true);
assert.strictEqual(pq.isNonBlocking(), false);
});
});
describe('LISTEN/NOTIFY', () => {
let listener: PQ;
let notifier: PQ;
before(() => {
listener = new PQ();
notifier = new PQ();
listener.connectSync();
notifier.connectSync();
});
it('works', () => {
notifier.exec("NOTIFY testing, 'My Payload'");
let notice = listener.notifies();
assert.equal(notice, null);
listener.exec('LISTEN testing');
notifier.exec("NOTIFY testing, 'My Second Payload'");
listener.exec('SELECT NOW()');
notice = listener.notifies();
assert(notice, 'listener should have had a notification come in');
assert.equal(notice.relname, 'testing', 'missing relname == testing');
assert.equal(notice.extra, 'My Second Payload');
assert(notice.be_pid);
});
after(() => {
listener.finish();
notifier.finish();
});
});
describe('result accessors', () => {
let pq: PQ;
before(() => {
pq = new PQ();
pq.connectSync();
createTable(pq);
});
after(() => {
pq.finish();
});
before(() => {
pq.exec("INSERT INTO test_data(name, age) VALUES ('bob', 80) RETURNING *");
assert(!pq.errorMessage());
});
it('has ntuples', () => {
assert.strictEqual(pq.ntuples(), 1);
});
it('has cmdStatus', () => {
assert.equal(pq.cmdStatus(), 'INSERT 0 1');
});
it('has command tuples', () => {
assert.strictEqual(pq.cmdTuples(), '1');
});
});
describe('Retrieve server version from connection', () => {
it('return version number when connected', () => {
const pq = new PQ();
pq.connectSync();
const version = pq.serverVersion();
assert.equal(typeof version, 'number');
assert(version > 60000);
});
it('return zero when not connected', () => {
const pq = new PQ();
const version = pq.serverVersion();
assert.equal(typeof version, 'number');
assert.equal(version, 0);
});
});
describe('getting socket', () => {
let pq: PQ;
before(() => {
pq = new PQ();
pq.connectSync();
createTable(pq);
});
after(() => {
pq.finish();
});
it('returns -1 when not connected', () => {
const pq = new PQ();
assert.equal(pq.socket(), -1);
});
it('returns value when connected', () => {
assert(pq.socket() > 0);
});
});
describe('connecting with bad credentials', () => {
it('throws an error', () => {
try {
new PQ().connectSync('asldkfjlasdf');
} catch (e) {
assert.equal(e.toString().indexOf('connection pointer is NULL'), -1);
return;
}
assert.fail(null, null, 'Should have thrown an exception', '');
});
});
describe('connecting with no credentials', () => {
let pq: PQ;
before(() => {
pq = new PQ();
pq.connectSync();
});
it('is connected', () => {
assert(pq.connected, 'should have connected == true');
});
after(() => {
pq.finish();
assert(!pq.connected);
});
});
describe('result checking', () => {
let pq: PQ;
before(() => {
pq = new PQ();
pq.connectSync();
});
after(() => {
pq.finish();
});
it('executes query', () => {
pq.exec('SELECT NOW() as my_col');
assert.equal(pq.resultStatus(), 'PGRES_TUPLES_OK');
});
it('has 1 tuple', () => {
assert.equal(pq.ntuples(), 1);
});
it('has 1 field', () => {
assert.strictEqual(pq.nfields(), 1);
});
it('has column name', () => {
assert.equal(pq.fname(0), 'my_col');
});
it('has oid type of timestamptz', () => {
assert.strictEqual(pq.ftype(0), 1184);
});
it('has value as a date', () => {
const now = new Date();
const val = pq.getvalue(0);
const date = new Date(Date.parse(val));
assert.equal(date.getFullYear(), now.getFullYear());
assert.equal(date.getMonth(), now.getMonth());
});
it('can manually clear result multiple times', () => {
pq.clear();
pq.clear();
pq.clear();
});
});
describe('low-level query integration tests', () => {
let pq: PQ;
before(() => {
pq = new PQ();
pq.connectSync();
createTable(pq);
});
after(() => {
pq.finish();
});
describe('exec', () => {
before(() => {
pq.exec('SELECT * FROM test_data');
});
it('has correct tuples', () => {
assert.strictEqual(pq.ntuples(), 3);
});
it('has correct field count', () => {
assert.strictEqual(pq.nfields(), 2);
});
it('has correct rows', () => {
assert.strictEqual(pq.getvalue(0, 0), 'brian');
assert.strictEqual(pq.getvalue(1, 1), '30');
assert.strictEqual(pq.getvalue(2, 0), '');
assert.strictEqual(pq.getisnull(2, 0), false);
assert.strictEqual(pq.getvalue(2, 1), '');
assert.strictEqual(pq.getisnull(2, 1), true);
});
});
});
describe('sync query with parameters', () => {
let pq: PQ;
before(() => {
pq = new PQ();
pq.connectSync();
createTable(pq);
});
after(() => {
pq.finish();
});
it('works with single string parameter', () => {
const queryText = 'SELECT $1::text as name';
pq.execParams(queryText, ['Brian']);
assert.strictEqual(pq.ntuples(), 1);
assert.strictEqual(pq.getvalue(0, 0), 'Brian');
});
it('works with a number parameter', () => {
const queryText = 'SELECT $1::int as age';
pq.execParams(queryText, [32]);
assert.strictEqual(pq.ntuples(), 1);
assert.strictEqual(pq.getvalue(0, 0), '32');
});
it('works with multiple parameters', () => {
const queryText = 'INSERT INTO test_data(name, age) VALUES($1, $2)';
pq.execParams(queryText, ['Barkley', 4]);
assert.equal(pq.resultErrorMessage(), '');
});
});
describe('prepare and execPrepared', () => {
let pq: PQ;
before(() => {
pq = new PQ();
pq.connectSync();
createTable(pq);
});
after(() => {
pq.finish();
});
const statementName = 'get-name';
describe('preparing a statement', () => {
it('works properly', () => {
pq.prepare(statementName, 'SELECT $1::text as name', 1);
assert.ifError(pq.resultErrorMessage());
assert.equal(pq.resultStatus(), 'PGRES_COMMAND_OK');
});
});
describe('executing a prepared statement', () => {
it('works properly', () => {
pq.execPrepared(statementName, ['Brian']);
assert.ifError(pq.resultErrorMessage());
assert.strictEqual(pq.ntuples(), 1);
assert.strictEqual(pq.nfields(), 1);
assert.strictEqual(pq.getvalue(0, 0), 'Brian');
});
});
});
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"libpq-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+174 -15
View File
@@ -1,28 +1,187 @@
// Type definitions for lolex 1.5.1
// Type definitions for lolex 1.5
// Project: https://github.com/sinonjs/lolex
// Definitions by: Wim Looman <https://github.com/Nemo157>
// Definitions by: Wim Looman <https://github.com/Nemo157>, Josh Goldberg <https://github.com/joshuakgoldberg>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Timer object used in node.
*/
export interface NodeTimer {
/**
* Stub method call. Does nothing.
*/
ref(): void;
export interface Clock {
/**
* Stub method call. Does nothing.
*/
unref(): void;
}
/**
* Timer identifier for clock scheduling.
*/
export type TimerId = number | NodeTimer;
/**
* Lolex clock for a browser environment.
*/
type BrowserClock = LolexClock<number>;
/**
* Lolex clock for a Node environment.
*/
type NodeClock = LolexClock<NodeTimer> & {
/**
* Mimicks process.hrtime().
*
* @param prevTime Previous system time to calculate time elapsed.
* @returns High resolution real time as [seconds, nanoseconds].
*/
hrtime(prevTime?: [number, number]): [number, number];
};
/**
* Clock object created by lolex.
*/
type Clock = BrowserClock | NodeClock;
/**
* Names of clock methods that may be faked by install.
*/
type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date";
/**
* Controls the flow of time.
*/
export interface LolexClock<TTimerId extends TimerId> {
/**
* Current clock time.
*/
now: number;
setTimeout(callback: () => any, timeout: number): number;
setInterval(callback: () => any, timeout: number): number;
setImmediate(callback: () => any): number;
/**
* Implements the Date object but using this clock to provide the correct time.
*/
Date: typeof Date;
clearTimeout(id: number): void;
clearInterval(id: number): void;
clearImmediate(id: number): void;
/**
* Schedules a callback to be fired once timeout milliseconds have ticked by.
*
* @param callback Callback to be fired.
* @param timeout How many ticks to wait to run the callback.
* @returns Time identifier for cancellation.
*/
setTimeout(callback: () => any, timeout: number): TTimerId;
setSystemTime(now: number): void;
setSystemTime(date: Date): void;
/**
* Clears a timer, as long as it was created using setTimeout.
*
* @param id Timer ID or object.
*/
clearTimeout(id: TTimerId): void;
tick(ms: number): void;
/**
* Schedules a callback to be fired every time timeout milliseconds have ticked by.
*
* @param callback Callback to be fired.
* @param timeout How many ticks to wait between callbacks.
* @returns Time identifier for cancellation.
*/
setInterval(callback: () => any, timeout: number): TTimerId;
/**
* Clears a timer, as long as it was created using setInterval.
*
* @param id Timer ID or object.
*/
clearInterval(id: TTimerId): void;
/**
* Schedules the callback to be fired once 0 milliseconds have ticked by.
*
* @param callback Callback to be fired.
* @remarks You'll still have to call clock.tick() for the callback to fire.
* @remarks If called during a tick the callback won't fire until 1 millisecond has ticked by.
*/
setImmediate(callback: () => any): TTimerId;
/**
* Clears a timer, as long as it was created using setImmediate.
*
* @param id Timer ID or object.
*/
clearImmediate(id: TTimerId): void;
/**
* Advances the clock to the the moment of the first scheduled timer, firing it.
*/
next(): void;
/**
* Advance the clock, firing callbacks if necessary.
*
* @param time How many ticks to advance by.
*/
tick(time: number | string): void;
/**
* Runs all pending timers until there are none remaining.
*
* @remarks If new timers are added while it is executing they will be run as well.
*/
runAll(): void;
/**
* Takes note of the last scheduled timer when it is run, and advances the clock to
* that time firing callbacks as necessary.
*/
runToLast(): void;
/**
* Simulates a user changing the system clock.
*
* @param now New system time.
* @remarks This affects the current time but it does not in itself cause timers to fire.
*/
setSystemTime(now?: number | Date): void;
/**
* Restores the original methods on the context that was passed to lolex.install,
* or the native timers if no context was given.
*/
uninstall(): void;
}
export declare function createClock(now?: number): Clock;
/**
* Creates a clock.
*
* @param now Current time for the clock.
* @param loopLimit Maximum number of timers that will be run when calling runAll()
* before assuming that we have an infinite loop and throwing an error
* (by default, 1000).
* @type TClock Type of clock to create.
* @remarks The default epoch is 0.
*/
export declare function createClock<TClock extends Clock>(now?: number | Date, loopLimit?: number): TClock;
export declare function install(now?: number, toFake?: string[]): Clock;
export declare function install(context?: any, now?: number, toFake?: string[]): Clock;
/**
* Creates a clock and installs it globally.
*
* @param now Current time for the clock, as with lolex.createClock().
* @param toFake Names of methods that should be faked.
* @type TClock Type of clock to create.
* @usage lolex.install(["setTimeout", "clearTimeout"]);
*/
export declare function install<TClock extends Clock>(now?: number | Date, toFake?: FakeMethod[]): TClock;
/**
* Creates a clock and installs it onto the context object.
*
* @param context Context to install the clock onto.
* @param now Current time for the clock, as with lolex.createClock().
* @param toFake Names of methods that should be faked.
* @type TClock Type of clock to create.
* @usage lolex.install(context, ["setTimeout", "clearTimeout"]);
*/
export declare function install<TClock extends Clock>(context?: any, now?: number | Date, toFake?: FakeMethod[]): TClock;
+62 -104
View File
@@ -1,126 +1,84 @@
import lolex = require("lolex");
function a() {
var clock = lolex.createClock();
let browserClock: lolex.BrowserClock = lolex.createClock() as lolex.BrowserClock;
let nodeClock: lolex.NodeClock = lolex.createClock() as lolex.NodeClock;
clock.setTimeout(function () {
console.log("The poblano is a mild chili pepper originating in the state of Puebla, Mexico.");
}, 15);
browserClock = lolex.createClock<lolex.BrowserClock>();
nodeClock = lolex.createClock<lolex.NodeClock>();
// ...
lolex.createClock<lolex.BrowserClock>(7);
lolex.createClock<lolex.BrowserClock>(new Date());
lolex.createClock<lolex.BrowserClock>(7, 9001);
lolex.createClock<lolex.BrowserClock>(new Date(), 9001);
clock.tick(15);
}
lolex.createClock<lolex.NodeClock>(7);
lolex.createClock<lolex.NodeClock>(new Date());
lolex.createClock<lolex.NodeClock>(7, 9001);
lolex.createClock<lolex.NodeClock>(new Date(), 9001);
function b() {
var clock = lolex.install(window);
lolex.install<lolex.BrowserClock>(7);
lolex.install<lolex.BrowserClock>(new Date());
lolex.install<lolex.BrowserClock>(7, ["setTimeout"]);
lolex.install<lolex.BrowserClock>(new Date(), ["setTimeout"]);
window.setTimeout(() => {}, 15); // Schedules with clock.setTimeout
lolex.install<lolex.NodeClock>(7);
lolex.install<lolex.NodeClock>(new Date());
lolex.install<lolex.NodeClock>(7, ["setTimeout"]);
lolex.install<lolex.NodeClock>(new Date(), ["setTimeout"]);
clock.uninstall();
lolex.install<lolex.BrowserClock>({}, 7);
lolex.install<lolex.BrowserClock>({}, new Date());
lolex.install<lolex.BrowserClock>({}, 7, ["setTimeout"]);
lolex.install<lolex.BrowserClock>({}, new Date(), ["setTimeout"]);
// window.setTimeout is restored to the native implementation
}
lolex.install<lolex.NodeClock>({}, 7);
lolex.install<lolex.NodeClock>({}, new Date());
lolex.install<lolex.NodeClock>({}, 7, ["setTimeout"]);
lolex.install<lolex.NodeClock>({}, new Date(), ["setTimeout"]);
function c() {
var clock = lolex.install();
const browserNow: number = browserClock.now;
const browserDate: Date = new browserClock.Date();
// Equivalent to
// var clock = lolex.install(typeof global !== "undefined" ? global : window);
}
const nodeNow: number = nodeClock.now;
const nodeDate: Date = new nodeClock.Date();
var clock: lolex.Clock;
const browserTimeout: number = browserClock.setTimeout(() => {}, 7);
const browserInterval: number = browserClock.setInterval(() => {}, 7);
const browserImmediate: number = browserClock.setImmediate(() => {});
const nodeTimeout: lolex.NodeTimer = nodeClock.setTimeout(() => {}, 7);
const nodeInterval: lolex.NodeTimer = nodeClock.setInterval(() => {}, 7);
const nodeImmediate: lolex.NodeTimer = nodeClock.setImmediate(() => {});
/**
* var clock = lolex.createClock([now])
*/
browserClock.clearTimeout(browserTimeout);
browserClock.clearInterval(browserInterval);
browserClock.clearImmediate(browserImmediate);
clock = lolex.createClock();
clock = lolex.createClock(Date.now());
nodeClock.clearTimeout(nodeTimeout);
nodeClock.clearInterval(nodeInterval);
nodeClock.clearImmediate(nodeImmediate);
browserClock.tick(7);
browserClock.tick("08");
/**
* var clock = lolex.install([context[, now[, toFake]]])
*/
nodeClock.tick(7);
nodeClock.tick("08");
clock = lolex.install();
clock = lolex.install(window);
clock = lolex.install(window, Date.now());
clock = lolex.install(window, Date.now(), ['setTimeout', 'clearTimeout']);
browserClock.next();
nodeClock.next();
browserClock.runAll();
nodeClock.runAll();
/**
* var clock = lolex.install([now[, toFake]])
*/
browserClock.runToLast();
nodeClock.runToLast();
clock = lolex.install(Date.now());
clock = lolex.install(Date.now(), ['setTimeout', 'clearTimeout']);
browserClock.setSystemTime();
browserClock.setSystemTime(7);
browserClock.setSystemTime(new Date());
/**
* clock.now
*/
var n: number = clock.now;
var id: number;
/**
* var id = clock.setTimeout(callback, timeout)
*/
id = clock.setTimeout(() => {}, 1000);
/**
* clock.clearTimeout(id)
*/
clock.clearTimeout(id);
/**
* var id = clock.setInterval(callback, timeout)
*/
id = clock.setInterval(() => {}, 1000);
/**
* clock.clearInterval(id)
*/
clock.clearInterval(id);
/**
* var id = clock.setImmediate(callback)
*/
id = clock.setImmediate(() => {});
/**
* clock.clearImmediate(id)
*/
clock.clearImmediate(id);
/**
* clock.setSystemTime
*/
clock.setSystemTime(0);
clock.setSystemTime(new Date());
/**
* clock.tick(time)
*/
clock.tick(1000);
/**
* clock.uninstall()
*/
clock.uninstall();
nodeClock.setSystemTime();
nodeClock.setSystemTime(7);
nodeClock.setSystemTime(new Date());
browserClock.uninstall();
nodeClock.uninstall();
+193 -13
View File
@@ -1,4 +1,4 @@
// Type definitions for Maker.js
// Type definitions for Maker.js 0.9.31
// Project: https://github.com/Microsoft/maker.js
// Definitions by: Dan Marshall <https://github.com/danmarshall>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -17,6 +17,23 @@
*
*/
declare namespace MakerJs {
/**
* Version info
*/
var version: string;
/**
* Enumeration of environment types.
*/
var environmentTypes: {
BrowserUI: string;
NodeJs: string;
WebWorker: string;
Unknown: string;
};
/**
* Current execution environment type, should be one of environmentTypes.
*/
var environment: string;
/**
* String-based enumeration of unit types: imperial, metric or otherwise.
* A model may specify the unit system it is using, if any. When importing a model, it may have different units.
@@ -543,6 +560,10 @@ declare namespace MakerJs {
* The endpoints of the path, in absolute coords.
*/
endPoints: IPoint[];
/**
* Length of the path.
*/
pathLength: number;
}
/**
* A chain of paths which connect end to end.
@@ -556,7 +577,17 @@ declare namespace MakerJs {
* Flag if this chain forms a loop end to end.
*/
endless?: boolean;
/**
* Total length of all paths in the chain.
*/
pathLength: number;
}
/**
* Test to see if an object implements the required properties of a chain.
*
* @param item The item to test.
*/
function isChain(item: any): boolean;
/**
* Callback to model.findChains() with resulting array of chains and unchained paths.
*/
@@ -839,7 +870,7 @@ declare namespace MakerJs.point {
* @param rotationOrigin The center point of rotation.
* @returns A new point.
*/
function rotate(pointToRotate: IPoint, angleInDegrees: number, rotationOrigin: IPoint): IPoint;
function rotate(pointToRotate: IPoint, angleInDegrees: number, rotationOrigin?: IPoint): IPoint;
/**
* Scale a point's coordinates.
*
@@ -923,7 +954,7 @@ declare namespace MakerJs.path {
* @param rotationOrigin The center point of rotation.
* @returns The original path (for chaining).
*/
function rotate(pathToRotate: IPath, angleInDegrees: number, rotationOrigin: IPoint): IPath;
function rotate(pathToRotate: IPath, angleInDegrees: number, rotationOrigin?: IPoint): IPath;
/**
* Scale a path.
*
@@ -950,6 +981,34 @@ declare namespace MakerJs.path {
* @param useOriginB Optional flag to converge the origin point of lineB instead of the end point.
*/
function converge(lineA: IPathLine, lineB: IPathLine, useOriginA?: boolean, useOriginB?: boolean): IPoint;
/**
* Get points along a path.
*
* @param pathContext Path to get points from.
* @param numberOfPoints Number of points to divide the path.
* @returns Array of points which are on the path spread at a uniform interval.
*/
function toPoints(pathContext: IPath, numberOfPoints: number): IPoint[];
/**
* Get key points (a minimal a number of points) along a path.
*
* @param pathContext Path to get points from.
* @param maxArcFacet Optional maximum length between points on an arc or circle.
* @returns Array of points which are on the path.
*/
function toKeyPoints(pathContext: IPath, maxArcFacet?: number): IPoint[];
/**
* Center a path at [0, 0].
*
* @param pathToCenter The path to center.
*/
function center(pathToCenter: IPath): IPath;
/**
* Move a path so its bounding box begins at [0, 0].
*
* @param pathToZero The path to zero.
*/
function zero(pathToZero: IPath): IPath;
}
declare namespace MakerJs.path {
/**
@@ -1140,6 +1199,12 @@ declare namespace MakerJs.model {
* @param origin Optional offset reference point.
*/
function originate(modelToOriginate: IModel, origin?: IPoint): IModel;
/**
* Center a model at [0, 0].
*
* @param modelToCenter The model to center.
*/
function center(modelToCenter: IModel): IModel;
/**
* Create a clone of a model, mirrored on either or both x and y axes.
*
@@ -1181,7 +1246,7 @@ declare namespace MakerJs.model {
* @param rotationOrigin The center point of rotation.
* @returns The original model (for chaining).
*/
function rotate(modelToRotate: IModel, angleInDegrees: number, rotationOrigin: IPoint): IModel;
function rotate(modelToRotate: IModel, angleInDegrees: number, rotationOrigin?: IPoint): IModel;
/**
* Scale a model.
*
@@ -1215,6 +1280,12 @@ declare namespace MakerJs.model {
* @param modelCallbackAfterWalk Callback for each model after recursion.
*/
function walk(modelContext: IModel, options: IWalkOptions): void;
/**
* Move a model so its bounding box begins at [0, 0].
*
* @param modelToZero The model to zero.
*/
function zero(modelToZero: IModel): IModel;
}
declare namespace MakerJs.model {
/**
@@ -1321,10 +1392,11 @@ declare namespace MakerJs.path {
*
* @param arc Arc to straighten.
* @param bevel Optional flag to bevel the angle to prevent it from being too sharp.
* @param prefix Optional prefix to apply to path ids.
* @param prefix Optional string prefix to apply to path ids.
* @param close Optional flag to make a closed geometry by connecting the endpoints.
* @returns Model of straight lines with same endpoints as the arc.
*/
function straighten(arc: IPathArc, bevel?: boolean, prefix?: string): IModel;
function straighten(arc: IPathArc, bevel?: boolean, prefix?: string, close?: boolean): IModel;
}
declare namespace MakerJs.model {
/**
@@ -1423,7 +1495,7 @@ declare namespace MakerJs.measure {
* @param arcA The arc to test.
* @param arcB The arc to check for overlap.
* @param excludeTangents Boolean to exclude exact endpoints and only look for deep overlaps.
* @returns Boolean true if arc1 is overlapped with arcB.
* @returns Boolean true if arcA is overlapped with arcB.
*/
function isArcOverlapping(arcA: IPathArc, arcB: IPathArc, excludeTangents: boolean): boolean;
/**
@@ -1467,7 +1539,7 @@ declare namespace MakerJs.measure {
* @param lineA The line to test.
* @param lineB The line to check for overlap.
* @param excludeTangents Boolean to exclude exact endpoints and only look for deep overlaps.
* @returns Boolean true if line1 is overlapped with lineB.
* @returns Boolean true if lineA is overlapped with lineB.
*/
function isLineOverlapping(lineA: IPathLine, lineB: IPathLine, excludeTangents: boolean): boolean;
/**
@@ -1475,7 +1547,7 @@ declare namespace MakerJs.measure {
*
* @param measureA The measurement to test.
* @param measureB The measurement to check for overlap.
* @returns Boolean true if measure1 is overlapped with measureB.
* @returns Boolean true if measureA is overlapped with measureB.
*/
function isMeasurementOverlapping(measureA: IMeasure, measureB: IMeasure): boolean;
/**
@@ -1665,10 +1737,22 @@ declare namespace MakerJs.path {
*
* @param pathA First path to fillet, which will be modified to fit the fillet.
* @param pathB Second path to fillet, which will be modified to fit the fillet.
* @param filletRadius Radius of the fillet.
* @param options Optional IPointMatchOptions object to specify pointMatchingDistance.
* @returns Arc path object of the new fillet.
*/
function fillet(pathA: IPath, pathB: IPath, filletRadius: number, options?: IPointMatchOptions): IPathArc;
}
declare namespace MakerJs.chain {
/**
* Adds a fillet between each link in a chain. Each path will be cropped to fit a fillet, and all fillets will be returned as paths in a returned model object.
*
* @param chainToFillet The chain to add fillets to.
* @param filletRadius Radius of the fillet.
* @returns Model object containing paths which fillet the joints in the chain.
*/
function fillet(chainToFillet: IChain, filletRadius: number): IModel;
}
declare namespace MakerJs.kit {
/**
* Helper function to use the JavaScript "apply" function in conjunction with the "new" keyword.
@@ -1687,6 +1771,13 @@ declare namespace MakerJs.kit {
function getParameterValues(ctor: IKit): any[];
}
declare namespace MakerJs.model {
/**
* Find a single chain within a model, across all layers. Shorthand of findChains; useful when you know there is only one chain to find in your model.
*
* @param modelContext The model to search for a chain.
* @returns A chain object or null if chains were not found.
*/
function findSingleChain(modelContext: IModel): IChain;
/**
* Find paths that have common endpoints and form chains.
*
@@ -1695,6 +1786,25 @@ declare namespace MakerJs.model {
*/
function findChains(modelContext: IModel, callback: IChainCallback, options?: IFindChainsOptions): void;
}
declare namespace MakerJs.chain {
/**
* Get points along a chain of paths.
*
* @param chainContext Chain of paths to get points from.
* @param distance Distance along the chain between points.
* @param maxPoints Maximum number of points to retrieve.
* @returns Array of points which are on the chain spread at a uniform interval.
*/
function toPoints(chainContext: IChain, distance: number, maxPoints?: number): IPoint[];
/**
* Get key points (a minimal a number of points) along a chain of paths.
*
* @param chainContext Chain of paths to get points from.
* @param maxArcFacet The maximum length between points on an arc or circle.
* @returns Array of points which are on the chain.
*/
function toKeyPoints(chainContext: IChain, maxArcFacet?: number): IPoint[];
}
declare namespace MakerJs.model {
/**
* Find paths that have common endpoints and form loops.
@@ -1836,14 +1946,29 @@ declare namespace MakerJs.exporter {
}
}
declare namespace MakerJs.exporter {
/**
* Map of SVG Path Data by layer name.
*/
interface IPathDataByLayerMap {
[layer: string]: string;
}
/**
* Convert a chain to SVG path data.
*/
function chainToSVGPathData(chain: IChain, offset: IPoint, scale: number): string;
function chainToSVGPathData(chain: IChain, offset: IPoint): string;
/**
* Convert a path to SVG path data.
*/
function pathToSVGPathData(pathToExport: IPath, offset: IPoint, offset2: IPoint, scale: number): string;
function pathToSVGPathData(pathToExport: IPath, offset: IPoint, offset2: IPoint): string;
/**
* Convert a model to SVG path data.
*
* @param modelToExport Model to export.
* @param byLayers Boolean flag (default true) to return a map of path data by layer.
* @param origin Optional reference origin.
* @returns String of SVG path data (if byLayers is false) or an object map of path data by layer .
*/
function toSVGPathData(modelToExport: IModel, byLayers?: boolean, origin?: IPoint): IPathDataByLayerMap | string;
function toSVG(modelToExport: IModel, options?: ISVGRenderOptions): string;
function toSVG(pathsToExport: IPath[], options?: ISVGRenderOptions): string;
function toSVG(pathToExport: IPath, options?: ISVGRenderOptions): string;
@@ -1925,6 +2050,7 @@ declare namespace MakerJs.models {
constructor(origin: IPoint, control1: IPoint, control2: IPoint, end: IPoint, accuracy?: number);
static typeName: string;
static getBezierSeeds(curve: BezierCurve, options?: IFindChainsOptions): IPathBezierSeed[];
static computeLength(seed: IPathBezierSeed): number;
static computePoint(seed: IPathBezierSeed, t: number): IPoint;
}
}
@@ -2030,6 +2156,28 @@ declare namespace MakerJs.models {
static getPoints(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number, circumscribed?: boolean): IPoint[];
}
}
declare namespace MakerJs.models {
class Holes implements IModel {
paths: IPathMap;
/**
* Create an array of circles of the same radius from an array of center points.
*
* Example:
* ```
* //Create some holes from an array of points
* var makerjs = require('makerjs');
* var model = new makerjs.models.Holes(10, [[0, 0],[50, 0],[25, 40]]);
* var svg = makerjs.exporter.toSVG(model);
* document.write(svg);
* ```
*
* @param holeRadius Hole radius.
* @param points Array of points for origin of each hole.
* @param ids Optional array of corresponding path ids for the holes.
*/
constructor(holeRadius: number, points: IPoint[], ids?: string[]);
}
}
declare namespace MakerJs.models {
class BoltCircle implements IModel {
paths: IPathMap;
@@ -2042,6 +2190,26 @@ declare namespace MakerJs.models {
constructor(width: number, height: number, holeRadius: number);
}
}
declare namespace MakerJs.models {
class Dogbone implements IModel {
paths: IPathMap;
/**
* Create a dogbone from width, height, corner radius, style, and bottomless flag.
*
* Example:
* ```
* var d = new makerjs.models.Dogbone(50, 100, 5);
* ```
*
* @param width Width of the rectangle.
* @param height Height of the rectangle.
* @param radius Corner radius.
* @param style Optional corner style: 0 (default) for dogbone, 1 for vertical, -1 for horizontal.
* @param bottomless Optional flag to omit the bottom line and bottom corners (default false).
*/
constructor(width: number, height: number, radius: number, style?: number, bottomless?: boolean);
}
}
declare namespace MakerJs.models {
class Dome implements IModel {
paths: IPathMap;
@@ -2102,7 +2270,11 @@ declare namespace MakerJs.models {
*
* Example:
* ```
* var r = new makerjs.models.Rectangle(100, 50);
* //Create a rectangle from width and height
* var makerjs = require('makerjs');
* var model = new makerjs.models.Rectangle(50, 100);
* var svg = makerjs.exporter.toSVG(model);
* document.write(svg);
* ```
*
* @param width Width of the rectangle.
@@ -2114,8 +2286,12 @@ declare namespace MakerJs.models {
*
* Example:
* ```
* //Create a rectangle which will surround a model
* var makerjs = require('makerjs');
* var e = new makerjs.models.Ellipse(17, 10); // draw an ellipse so we have something to surround.
* var r = new makerjs.models.Rectangle(e, 3); // draws a rectangle surrounding the ellipse by 3 units.
* var svg = makerjs.exporter.toSVG({ models: { e: e, r: r }});
* document.write(svg);
* ```
*
* @param modelToSurround IModel object.
@@ -2127,9 +2303,13 @@ declare namespace MakerJs.models {
*
* Example:
* ```
* //Create a rectangle from a measurement.
* var makerjs = require('makerjs');
* var e = new makerjs.models.Ellipse(17, 10); // draw an ellipse so we have something to measure.
* var m = makerjs.measure.modelExtents(e); // measure the ellipse.
* var r = new makerjs.models.Rectangle(m); // draws a rectangle surrounding the ellipse.
* var svg = makerjs.exporter.toSVG({ models: { e: e, r: r }});
* document.write(svg);
* ```
*
* @param measurement IMeasure object. See http://microsoft.github.io/maker.js/docs/api/modules/makerjs.measure.html#pathextents and http://microsoft.github.io/maker.js/docs/api/modules/makerjs.measure.html#modelextents to get measurements of paths and models.
@@ -2173,6 +2353,6 @@ declare namespace MakerJs.models {
declare namespace MakerJs.models {
class Text implements IModel {
models: IModelMap;
constructor(font: opentype.Font, text: string, fontSize: number, combine?: boolean);
constructor(font: opentype.Font, text: string, fontSize: number, combine?: boolean, centerCharacterOrigin?: boolean, bezierAccuracy?: number);
}
}
+44 -1
View File
@@ -9,11 +9,36 @@ function test() {
var paths = testPaths();
var models = testModels();
var model: MakerJs.IModel = models[0];
var seed: MakerJs.IPathBezierSeed = { type: makerjs.pathType.BezierSeed, origin: [0,0], end: [1,1], controls: []};
var chain: MakerJs.IChain = {
endless: false,
links: [
{
endPoints: [],
reversed: false,
pathLength: 0,
walkedPath: {
layer: '',
modelContext: model,
offset: p1,
pathContext: paths.line,
pathId: 'x',
route: [],
routeKey: ''
}
}
],
pathLength: 0
};
function testRoot() {
makerjs.version;
makerjs.environment;
makerjs.environmentTypes.BrowserUI;
makerjs.cloneObject({});
makerjs.createRouteKey([]);
makerjs.extendObject({abc:123}, {xyz:789});
makerjs.isChain({});
makerjs.isFunction(function(){});
makerjs.isNumber(0);
makerjs.isObject({});
@@ -62,6 +87,7 @@ function test() {
useSvgPathOnly: false,
viewBox: false
});
makerjs.exporter.toSVGPathData(model);
makerjs.exporter.tryGetModelUnits(model);
}
@@ -88,7 +114,7 @@ function test() {
makerjs.measure.isBetween(7, 8, 9, false);
makerjs.measure.isBetweenArcAngles(7, paths.arc, false);
makerjs.measure.isBetweenPoints([1,1], paths.line, true);
makerjs.measure.isBezierSeedLinear({type: '', origin:[], end:[], controls:[]});
makerjs.measure.isBezierSeedLinear(seed);
makerjs.measure.isLineOverlapping(paths.line, paths.line, false);
makerjs.measure.isMeasurementOverlapping(mm, mp);
var mm = makerjs.measure.modelExtents(model);
@@ -105,6 +131,7 @@ function test() {
function testModel(){
makerjs.model.breakPathsAtIntersections(model, { paths:{ } });
makerjs.model.center(model);
var opts: MakerJs.ICombineOptions = { trimDeadEnds: true, pointMatchingDistance: 2 };
makerjs.model.combine(model, model, true, false, true, false, opts);
makerjs.model.combineIntersection(model, model);
@@ -116,6 +143,7 @@ function test() {
makerjs.model.expandPaths(model, 7);
makerjs.model.findChains(model, function (chains: MakerJs.IChain[], loose: MakerJs.IWalkPath[], layer: string) {})
makerjs.model.findLoops(model);
makerjs.model.findSingleChain(model);
makerjs.model.getSimilarModelId(model, 'foo');
makerjs.model.getSimilarPathId(model, 'foo');
makerjs.model.isPathInsideModel(paths.line, model);
@@ -131,18 +159,24 @@ function test() {
makerjs.model.simplify(model);
makerjs.model.walk(model, {});
makerjs.model.walkPaths(model, (modelContext: MakerJs.IModel, pathId: string, pathContext: MakerJs.IPath) => {});
makerjs.model.zero(model);
model.exporterOptions = { foo: 'bar' };
}
function testModels(): MakerJs.IModel[] {
makerjs.models.BezierCurve.computeLength(seed);
makerjs.models.BezierCurve.computePoint(seed, 0);
makerjs.models.BezierCurve.getBezierSeeds(new makerjs.models.BezierCurve([]));
return [
new makerjs.models.BezierCurve([]),
new makerjs.models.BoltCircle(7, 7, 7, 7),
new makerjs.models.BoltRectangle(2, 2, 2),
new makerjs.models.ConnectTheDots(true, [ [0,0], [1,1] ]),
new makerjs.models.Dogbone(1,1,1),
new makerjs.models.Dome(5, 7),
new makerjs.models.Ellipse(2,2),
new makerjs.models.EllipticArc(2,2,3,4),
new makerjs.models.Holes(1,[]),
new makerjs.models.Oval(7, 7),
new makerjs.models.OvalArc(6, 4, 2, 12, true),
new makerjs.models.Polygon(7, 5),
@@ -159,6 +193,7 @@ function test() {
function testPath() {
makerjs.path.breakAtPoint(paths.arc, [0,0]).type;
makerjs.path.center(paths.line);
makerjs.path.clone(paths.line);
makerjs.path.converge(paths.line, paths.line);
makerjs.path.distort(paths.arc, 5, 6);
@@ -173,6 +208,8 @@ function test() {
makerjs.path.rotate(paths.line, 5, [0,0]);
makerjs.path.scale(paths.arc, 8);
makerjs.path.straighten(paths.arc);
makerjs.path.toKeyPoints(paths.arc, 1);
makerjs.path.toPoints(paths.circle, 1);
}
function testPaths() {
@@ -217,6 +254,12 @@ function test() {
makerjs.point.zero();
}
function testChain() {
makerjs.chain.fillet(chain, 1);
makerjs.chain.toKeyPoints(chain);
makerjs.chain.toPoints(chain, 1);
}
function testSolvers() {
makerjs.solvers.solveTriangleASA(4, 4, 4);
makerjs.solvers.solveTriangleSSS(9, 9, 9);
+1 -1
View File
@@ -1765,7 +1765,7 @@ declare namespace __MaterialUI {
multiLine?: boolean;
name?: string;
onBlur?: React.FocusEventHandler<{}>;
onChange?: React.FormEventHandler<{}>;
onChange?: (e: React.FormEvent<{}>, newValue: string) => void;
onEnterKeyDown?: React.KeyboardEventHandler<{}>;
onFocus?: React.FocusEventHandler<{}>;
onKeyDown?: React.KeyboardEventHandler<{}>;
+2
View File
@@ -69,6 +69,8 @@ declare class Mocha {
ui?: string;
reporter?: string;
timeout?: number;
reporterOptions?: any;
slow?: number;
bail?: boolean;
});
+3
View File
@@ -3,6 +3,9 @@
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Theodore Brown <https://github.com/theodorejb/>, Leon Yu <https://github.com/leonyu/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = Modernizr; // support AMD require
export as namespace Modernizr; // keep a global namespace
declare namespace __Modernizr {
interface AudioBoolean {
ogg: boolean;
+1
View File
@@ -122,6 +122,7 @@ declare namespace NodeCache {
stdTTL?: number;
checkperiod?: number;
useClones?: boolean;
errorOnMissing?: boolean;
}
interface Stats {
+18
View File
@@ -62,17 +62,35 @@ export namespace exchange {
function code(options: Options, issue: (client: any, code: string, redirectURI: string, issued: IssuedFunction) => void): MiddlewareFunction;
function code(issue: (client: any, code: string, redirectURI: string, issued: IssuedFunction) => void): MiddlewareFunction;
// arity == 5; issue(client, scope, req.body, req.authInfo, issued);
function clientCredentials(options: Options, issue: (client: any, scope: string[], body: any, authInfo: any, issued: IssuedFunction) => void): MiddlewareFunction;
// arity == 4; issue(client, scope, req.body, issued);
function clientCredentials(options: Options, issue: (client: any, scope: string[], body: any, issued: IssuedFunction) => void): MiddlewareFunction;
// arity == 3; issue(client, scope, issued);
function clientCredentials(options: Options, issue: (client: any, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction;
// arity == 2; issue(client, issued);
function clientCredentials(options: Options, issue: (client: any, issued: IssuedFunction) => void): MiddlewareFunction;
function clientCredentials(issue: (client: any, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction;
function clientCredentials(issue: (client: any, issued: IssuedFunction) => void): MiddlewareFunction;
// arity == 7; issue(client, username, passwd, scope, req.body, req.authInfo, issued);
function password(options: Options, issue: (client: any, username: string, password: string, scope: string[], body: any, authInfo: any, issued: IssuedFunction) => void): MiddlewareFunction;
// arity == 6; issue(client, username, passwd, scope, req.body, issued);
function password(options: Options, issue: (client: any, username: string, password: string, scope: string[], body: any, issued: IssuedFunction) => void): MiddlewareFunction;
// arity == 5; issue(client, username, passwd, scope, issued);
function password(options: Options, issue: (client: any, username: string, password: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction;
// arity == 4; issue(client, username, passwd, issued);
function password(options: Options, issue: (client: any, username: string, password: string, issued: IssuedFunction) => void): MiddlewareFunction;
function password(issue: (client: any, username: string, password: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction;
function password(issue: (client: any, username: string, password: string, issued: IssuedFunction) => void): MiddlewareFunction;
// arity == 6; issue(client, refreshToken, scope, req.body, req.authInfo, issued);
function refreshToken(options: Options, issue: (client: any, refreshToken: string, scope: string[], body: any, authInfo: any, issued: IssuedFunction) => void): MiddlewareFunction;
// arity == 5; issue(client, refreshToken, scope, req.body, issued);
function refreshToken(options: Options, issue: (client: any, refreshToken: string, scope: string[], body: any, issued: IssuedFunction) => void): MiddlewareFunction;
// arity == 4; issue(client, refreshToken, scope, issued);
function refreshToken(options: Options, issue: (client: any, refreshToken: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction;
// arity == 3; issue(client, refreshToken, issued);
function refreshToken(options: Options, issue: (client: any, refreshToken: string, issued: IssuedFunction) => void): MiddlewareFunction;
function refreshToken(issue: (client: any, refreshToken: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction;
function refreshToken(issue: (client: any, refreshToken: string, issued: IssuedFunction) => void): MiddlewareFunction;
+4 -3
View File
@@ -464,6 +464,7 @@ interface ModalView {
interface navigatorOptions {
animation?: string;
onTransitionEnd?: any;
[key: string]: any; //for options
}
/**
@@ -806,7 +807,7 @@ interface onsStatic {
* @return {Promise} Promise object that resolves to the alert dialog component object
* @description Create a alert dialog instance from a template
*/
createAlertDialog(page: string): any;
createAlertDialog(page: string, options?: any): any;
/**
* @param {String} page Page name. Can be either an HTML file or an <ons-template> containing a <ons-dialog> component
* @param {Object} [options] Parameter object
@@ -814,7 +815,7 @@ interface onsStatic {
* @return {Promise} Promise object that resolves to the dialog component object
* @description Create a dialog instance from a template
*/
createDialog(page: string): any;
createDialog(page: string, options?: any): any;
/**
* @param {String} page Page name. Can be either an HTML file or an <ons-template> containing a <ons-dialog> component
* @param {Object} [options] Parameter object
@@ -822,7 +823,7 @@ interface onsStatic {
* @return {Promise} Promise object that resolves to the popover component object
* @description Create a popover instance from a template
*/
createPopover(page: string): any;
createPopover(page: string, options?: any): any;
/**
* @description Utility methods to create different kinds of alert dialogs. There are three methods available: alert, confirm and prompt
+71 -71
View File
@@ -63,19 +63,19 @@ declare namespace fin {
/**
* Retrieves an array of wrapped fin.desktop.Windows for each of the application’s child windows.
*/
getChildWindows(callback?: (children: OpenFinWindow[]) => any, errorCallback?: (reason: string) => void): void;
getChildWindows(callback?: (children: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of active window groups for all of the application's windows. Each group is represented as an array of wrapped fin.desktop.Windows.
*/
getGroups(callback?: (groups: OpenFinWindow[][]) => any, errorCallback?: (reason: string) => void): void;
getGroups(callback?: (groups: OpenFinWindow[][]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves the JSON manifest that was used to create the application. Invokes the error callback if the application was not created from a manifest.
*/
getManifest(callback?: (manifest: any) => any, errorCallback?: (reason: string) => void): void;
getManifest(callback?: (manifest: any) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves UUID of the application that launches this application. Invokes the error callback if the application was created from a manifest.
*/
getParentUuid(callback?: (uuid: string) => any, errorCallback?: (reason: string) => void): void;
getParentUuid(callback?: (uuid: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves current configuration of application's shortcuts.
*/
@@ -103,7 +103,7 @@ declare namespace fin {
/**
* Runs the application. When the application is created, run must be called.
*/
run(callback?: (successObj: SuccessObj) => any, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => any): void;
run(callback?: (successObj: SuccessObj) => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): void;
/**
* Tells the rvm to relaunch the main application once upon a complete shutdown
*/
@@ -115,7 +115,7 @@ declare namespace fin {
/**
* Adds a customizable icon in the system tray and notifies the application when clicked.
*/
setTrayIcon(iconUrl: string, listener: (clickInfo: TrayIconClickedEvent) => any, callback?: () => void, errorCallback?: (reason: string) => void): void;
setTrayIcon(iconUrl: string, listener: (clickInfo: TrayIconClickedEvent) => void, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Closes the application by terminating its process.
*/
@@ -130,15 +130,15 @@ declare namespace fin {
/**
* application has a shortcut on the desktop
*/
desktop: boolean;
desktop?: boolean;
/**
* application has no shortcut in the start menu
*/
startMenu: boolean;
startMenu?: boolean;
/**
* application will be launched on system startup
*/
systemStartup: boolean;
systemStartup?: boolean;
}
interface SuccessObj {
@@ -155,10 +155,10 @@ declare namespace fin {
}
interface ApplicationOptions {
url: string;
uuid: string;
name: string;
mainWindowOptions: WindowOptions;
url?: string;
uuid?: string;
name?: string;
mainWindowOptions?: WindowOptions;
}
interface WindowOptions {
@@ -185,8 +185,8 @@ declare namespace fin {
* This defines and applies rounded corners for a frameless window. Default for both width and height: 0.
*/
cornerRounding?: {
width: number;
height: number;
width?: number;
height?: number;
};
/**
* A field that the user can attach serializable data to to be ferried around with the window options. Default: ''.
@@ -267,14 +267,14 @@ declare namespace fin {
/**
* The size in pixels (Default: 2),
*/
size: number;
size?: number;
/**
* The size in pixels of an additional
* square resizable region located at the
* bottom right corner of a
* frameless window. (Default: 4)
*/
bottomRightCorner: number;
bottomRightCorner?: number;
};
/**
* A flag to show the Window's icon in the taskbar. Default: true.
@@ -310,35 +310,35 @@ declare namespace fin {
/**
* Reads available formats for the clipboard type
*/
availableFormats(type: string | null, callback?: (formats: string[]) => any, errorCallback?: (reason: string, error: ErrorInfo) => any): void;
availableFormats(type: string | null, callback?: (formats: string[]) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Reads available formats for the clipboard type
*/
readHtml(type: string | null, callback?: (html: string) => any, errorCallback?: (reason: string, error: ErrorInfo) => any): void;
readHtml(type: string | null, callback?: (html: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Read the content of the clipboard as Rtf
*/
readRtf(type: string | null, callback?: (rtf: string) => any, errorCallback?: (reason: string, error: ErrorInfo) => any): void;
readRtf(type: string | null, callback?: (rtf: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Read the content of the clipboard as plain text
*/
readText(type: string | null, callback?: (text: string) => any, errorCallback?: (reason: string, error: ErrorInfo) => any): void;
readText(type: string | null, callback?: (text: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Writes data into the clipboard
*/
write(data: any, type: string | null, callback?: () => any, errorCallback?: (reason: string, error: ErrorInfo) => any): void;
write(data: any, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Writes data into the clipboard as Html
*/
writeHtml(data: string, type: string | null, callback?: () => any, errorCallback?: (reason: string, error: ErrorInfo) => any): void;
writeHtml(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Writes data into the clipboard as Rtf
*/
writeRtf(data: string, type: string | null, callback?: () => any, errorCallback?: (reason: string, error: ErrorInfo) => any): void;
writeRtf(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Writes data into the clipboard as plain text
*/
writeText(data: string, type: string | null, callback?: () => any, errorCallback?: (reason: string, error: ErrorInfo) => any): void;
writeText(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
}
/**
@@ -353,11 +353,11 @@ declare namespace fin {
/**
* Registers an event listener on the specified event.
*/
addEventListener(type: OpenFinExternalApplicationEventType, listener: () => any, callback?: () => any, errorCallback?: (reason: string, error: ErrorInfo) => any): void;
addEventListener(type: OpenFinExternalApplicationEventType, listener: () => void, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Removes a previously registered event listener from the specified event.
*/
removeEventListener(type: OpenFinExternalApplicationEventType, listener: () => any, callback?: () => any, errorCallback?: (reason: string, error: ErrorInfo) => any): void;
removeEventListener(type: OpenFinExternalApplicationEventType, listener: () => void, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
}
/**
@@ -437,7 +437,7 @@ declare namespace fin {
/**
* A message of any primitive or composite-primitive type to be passed to the notification upon creation.
*/
message: any;
message?: any;
/**
* The timeout for displaying a notification.Can be in milliseconds or "never".
*/
@@ -445,7 +445,7 @@ declare namespace fin {
/**
* The url of the notification
*/
url: string;
url?: string;
/**
* A function that is called when a notification is clicked.
*/
@@ -619,70 +619,70 @@ declare namespace fin {
}
interface AppAssetInfo {
'src': string;
'alias': string;
'version': string;
'target': string;
'args': string;
src?: string;
alias?: string;
version?: string;
target?: string;
args?: string;
}
interface ApplicationInfo {
/**
* true when the application is running.
*/
isRunning: boolean;
isRunning?: boolean;
/**
* uuid of the application.
*/
uuid: string;
uuid?: string;
/**
* uuid of the application that launches this application.
*/
parentUuid: string;
parentUuid?: string;
}
interface WindowDetails {
uuid: string;
mainWindow: WindowInfo;
childWindows: WindowInfo[];
uuid?: string;
mainWindow?: WindowInfo;
childWindows?: WindowInfo[];
}
interface WindowInfo {
/**
* name of the child window
*/
name: string;
name?: string;
/**
* top-most coordinate of the child window
*/
top: number;
top?: number;
/**
* right-most coordinate of the child window
*/
right: number;
right?: number;
/**
* bottom-most coordinate of the child window
*/
bottom: number;
bottom?: number;
/**
* left-most coordinate of the child window
*/
left: number;
left?: number;
}
interface LogInfo {
/**
* the filename of the log
*/
name: string;
name?: string;
/**
* the size of the log in bytes
*/
size: number;
size?: number;
/**
* the unix time at which the log was created "Thu Jan 08 2015 14:40:30 GMT-0500 (Eastern Standard Time)"
*/
date: string;
date?: string;
}
interface ProcessInfo {
@@ -744,20 +744,20 @@ declare namespace fin {
/**
* the configured Proxy Address
*/
proxyAddress: string;
proxyAddress?: string;
/**
* the configured Proxy port
*/
proxyPort: number;
proxyPort?: number;
/**
* Proxy Type
*/
type: string;
type?: string;
}
interface RvmInfo {
version: string;
"start-time": string;
version?: string;
"start-time"?: string;
}
interface ExternalProcessLaunchInfo {
@@ -780,15 +780,15 @@ declare namespace fin {
/**
* "Exited" Or "released" on a call to releaseExternalProcess
*/
topic: string;
topic?: string;
/**
* The mapped UUID which identifies the launched process
*/
uuid: string;
uuid?: string;
/*
* Process exit code
*/
exitCode: number;
exitCode?: number;
}) => void;
certificate?: CertificationInfo;
}
@@ -801,7 +801,7 @@ declare namespace fin {
/**
* An internally tokenized and comma delimited string allowing partial or full checks of the subject fields
*/
subject: string;
subject?: string;
/**
* A hex string with or without spaces
*/
@@ -809,28 +809,28 @@ declare namespace fin {
/**
* A hex string with or without spaces
*/
thumbprint: string;
thumbprint?: string;
/**
* A boolean indicating that the certificate is trusted and not revoked
*/
trusted: boolean;
trusted?: boolean;
}
interface ExternalProcessInfo {
pid: number;
pid?: number;
listener?: (result: {
/**
* "Exited" Or "released" on a call to releaseExternalProcess
*/
topic: string;
topic?: string;
/**
* The mapped UUID which identifies the launched process
*/
uuid: string;
uuid?: string;
/*
* Process exit code
*/
exitCode: number;
exitCode?: number;
}) => void;
}
@@ -1321,11 +1321,11 @@ declare namespace fin {
/**
* This value is clamped from 0.0 to 1.0
*/
opacity: number;
opacity?: number;
/**
* The total time in milliseconds this transition should take.
*/
duration: number;
duration?: number;
/**
* Treat 'opacity' as absolute or as a delta. Defaults to false.
*/
@@ -1343,7 +1343,7 @@ declare namespace fin {
/**
* The total time in milliseconds this transition should take.
*/
duration: number;
duration?: number;
/**
* Treat 'left' and 'top' as absolute or as deltas. Defaults to false.
*/
@@ -1361,7 +1361,7 @@ declare namespace fin {
/**
* The total time in milliseconds this transition should take.
*/
duration: number;
duration?: number;
/**
* Treat 'width' and 'height' as absolute or as deltas. Defaults to false.
*/
@@ -1384,19 +1384,19 @@ declare namespace fin {
/**
* the height of the window.
*/
height: number;
height?: number;
/**
* left-most coordinate of the window.
*/
left: number;
left?: number;
/**
* top-most coordinate of the window.
*/
top: number;
top?: number;
/**
* the width of the window.
*/
width: number;
width?: number;
}
interface SessionChangedEvent {
+10
View File
@@ -0,0 +1,10 @@
// Type definitions for passport-anonymous 1.0
// Project: https://github.com/jaredhanson/passport-anonymous
// Definitions by: Pavel Puchkov <https://github.com/0x6368656174>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import * as passport from "passport";
export class Strategy implements passport.Strategy {
authenticate: () => void;
}
@@ -0,0 +1,4 @@
import * as passport from "passport";
import { Strategy } from "passport-anonymous";
passport.use(new Strategy());
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"passport-anonymous-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "../tslint.json"
}
+4 -2
View File
@@ -679,9 +679,10 @@ declare namespace R {
indexOf<T>(target: T): (list: T[]) => number;
/**
* Returns all but the last element of a list.
* Returns all but the last element of a list or string.
*/
init<T>(list: T[]): T[];
init(list: string): string;
/**
* Inserts the supplied element into the list, at index index. Note that
@@ -1467,9 +1468,10 @@ declare namespace R {
T(): boolean;
/**
* Returns all but the first element of a list.
* Returns all but the first element of a list or string.
*/
tail<T>(list: T[]): T[];
tail(list: string): string;
/**
* Returns a new list containing the first `n` elements of the given list. If
+8
View File
@@ -575,6 +575,8 @@ interface Obj { a: number; b: number };
R.head(['fi', 'fo', 'fum']); //=> 'fi'
R.head([10, 'ten']); // => 10
R.head(['10', 10]); // => '10'
R.head('abc'); //=> 'a'
R.head(''); //=> ''
}
(() => {
@@ -591,6 +593,8 @@ interface Obj { a: number; b: number };
() => {
R.init(['fi', 'fo', 'fum']); //=> ['fi', 'fo']
R.init('abc'); //=> 'ab'
R.init(''); //=> ''
}
() => {
@@ -623,6 +627,8 @@ interface Obj { a: number; b: number };
() => {
R.last(['fi', 'fo', 'fum']); //=> 'fum'
R.last('abc'); //=> 'c'
R.last(''); //=> ''
}
() => {
@@ -862,6 +868,8 @@ type Pair = KeyValuePair<string, number>
() => {
R.tail(['fi', 'fo', 'fum']); //=> ['fo', 'fum']
R.tail([1, 2, 3]); //=> [2, 3]
R.tail('abc'); //=> 'bc'
R.tail(''); //=> ''
}
() => {
+11
View File
@@ -5,6 +5,7 @@
import * as React from 'react';
export = ReactBootstrap;
export as namespace ReactBootstrap;
declare namespace ReactBootstrap {
@@ -602,7 +603,17 @@ declare namespace ReactBootstrap {
// <Tab />
interface TabProps extends React.HTMLProps<Tab> {
animation?: boolean;
'aria-labelledby'?:string;
bsClass?:string;
eventKey?: any; // TODO: Add more specific type
onEnter?: Function;
onEntered?: Function;
onEntering?: Function;
onExit?: Function;
onExited?: Function;
onExiting?: Function;
unmountOnExit?: boolean;
tabClassName?:string;
}
interface TabClass extends React.ClassicComponentClass<TabProps> {
Container: TabContainer;
+15
View File
@@ -598,6 +598,21 @@ export class ReactBootstrapTest extends Component<any, any> {
</Tabs>
</div>
<div style={style}>
<Tabs defaultActiveKey={1} animation={true}>
<Tab animation={true}
onEntered={() => {}}
onEntering={() => {}}
onExit={() => {}}
onExited={() => {}}
onExiting={()=>{}}
unmountOnExit={true}
bsClass="some style" tabClassName="classname" eventKey={1} title='Tab 1'>Tab 1 content</Tab>
<Tab eventKey={2} title='Tab 2'>Tab 2 content</Tab>
<Tab eventKey={3} title='Tab 3' disabled>Tab 3 content</Tab>
</Tabs>
</div>
<div style={style}>
<Tab.Container id="left-tabs-example" defaultActiveKey="first">
<Row className="clearfix">
+5 -6
View File
@@ -16,7 +16,7 @@ declare module "react-datepicker" {
disabled?: boolean;
endDate?: {};
excludeDates?: any[];
filterDate?():any;
filterDate?(): any;
fixedHeight?: boolean;
id?: string;
includeDates?: any[];
@@ -25,10 +25,9 @@ declare module "react-datepicker" {
maxDate?: {};
minDate?: {};
name?: string;
onBlur?():any;
onChange():any;
onChange(date?:any):any;
onFocus?():any;
onBlur?(handler: (e: any) => void): any;
onChange(handler: (date?: any, e?: any) => void): any;
onFocus?(handler: (e: any) => void): any;
peekNextMonth?: boolean;
placeholderText?: string;
popoverAttachment?: string;
@@ -40,7 +39,7 @@ declare module "react-datepicker" {
scrollableYearDropdown?: boolean;
selected?: {};
selectsEnd?: boolean;
selectsStart?: boolean;
selectsStart?: boolean;
showMonthDropdown?: boolean;
showYearDropdown?: boolean;
showWeekNumbers?: boolean;
+4 -3
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/gpbl/react-day-picker
// Definitions by: Giampaolo Bellavite <https://github.com/gpbl>, Jason Killian <https://github.com/jkillian>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.0
/// <reference types="react" />
@@ -22,9 +23,9 @@ declare namespace ReactDayPicker {
}
interface DayModifiers {
selected?: boolean;
disabled?: boolean;
[name: string]: boolean;
selected?: boolean;
disabled?: boolean;
[name: string]: boolean | undefined;
}
interface Modifiers {
@@ -24,6 +24,11 @@ interface MyCaptionProps extends ReactDayPicker.CaptionElementProps { }
class Caption extends React.Component<MyCaptionProps, {}> {
render() {
const { date, locale, localeUtils, onClick } = this.props;
if (!date || !localeUtils || typeof locale === 'undefined') {
return null
}
return (
<div className="DayPicker-Caption" onClick={ onClick }>
{ localeUtils.formatMonthTitle(date, locale) }

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