This commit is contained in:
Nicolas Penin
2019-02-04 12:10:22 +01:00
96 changed files with 5791 additions and 657 deletions
+2
View File
@@ -812,6 +812,8 @@ export interface AuthorizeOptions {
login_hint?: string;
prompt?: string;
mode?: "login" | "signUp";
acccessType?: string;
approvalPrompt?: string;
}
export interface CheckSessionOptions extends AuthorizeOptions {
+110
View File
@@ -1056,3 +1056,113 @@ const firehoseEventHandler: AWSLambda.FirehoseTransformationHandler = (
]
});
};
declare let lexEvent: AWSLambda.LexEvent;
lexEvent = {
currentIntent: {
name: 'intent-name',
slots: {
slot1: null,
slot2: 'value2',
},
slotDetails: {
slot1: {
resolutions: [
{ value: 'value1' },
],
originalValue: 'originalValue',
}
},
confirmationStatus: 'None',
},
bot: {
name: 'bot name',
alias: 'bot alias',
version: 'bot version',
},
userId: 'User ID specified in the POST request to Amazon Lex.',
inputTranscript: 'Text used to process the request',
invocationSource: 'FulfillmentCodeHook',
outputDialogMode: 'Text',
messageVersion: '1.0',
sessionAttributes: {
key1: 'value1',
key2: 'value2',
},
requestAttributes: {
key1: 'value1',
key2: 'value2',
}
};
declare let lexResult: AWSLambda.LexResult;
declare let lexDialogAction: AWSLambda.LexDialogAction;
declare let lexDialogActionBase: AWSLambda.LexDialogActionBase;
declare let lexDialogActionClose: AWSLambda.LexDialogActionClose;
declare let lexDialogActionConfirmIntent: AWSLambda.LexDialogActionConfirmIntent;
declare let lexDialogActionDelegate: AWSLambda.LexDialogActionDelegate;
declare let lexDialogActionElicitIntent: AWSLambda.LexDialogActionElicitIntent;
declare let lexDialogActionElicitSlot: AWSLambda.LexDialogActionElicitSlot;
declare let lexGenericAttachment: AWSLambda.LexGenericAttachment;
lexResult = {
sessionAttributes: {
attrib1: 'Value One',
},
dialogAction: {
type: 'Close',
fulfillmentState: 'Failed',
},
};
str = lexGenericAttachment.title;
str = lexGenericAttachment.subTitle;
str = lexGenericAttachment.imageUrl;
str = lexGenericAttachment.attachmentLinkUrl;
str = lexGenericAttachment.buttons[0].text;
str = lexGenericAttachment.buttons[0].value;
lexDialogAction.type === 'Close';
lexDialogAction.type === 'ConfirmIntent';
lexDialogAction.type === 'Delegate';
lexDialogAction.type === 'ElicitIntent';
lexDialogAction.type === 'ElicitSlot';
lexDialogActionBase.message!.contentType === 'CustomPayload';
lexDialogActionBase.message!.contentType === 'PlainText';
lexDialogActionBase.message!.contentType === 'SSML';
str = lexDialogActionBase.message!.content;
num = lexDialogActionBase.responseCard!.version;
lexDialogActionBase.responseCard!.contentType === 'application/vnd.amazonaws.card.generic';
// $ExpectType LexGenericAttachment
lexDialogActionBase.responseCard!.genericAttachments[0];
lexDialogActionClose.type === 'Close';
lexDialogActionClose.fulfillmentState === 'Failed';
lexDialogActionClose.fulfillmentState === 'Fulfilled';
lexDialogActionConfirmIntent.type === 'ConfirmIntent';
str = lexDialogActionConfirmIntent.intentName;
strOrNull = lexDialogActionConfirmIntent.slots['example'];
lexDialogActionDelegate.type === 'Delegate';
strOrNull = lexDialogActionDelegate.slots['example'];
lexDialogActionElicitIntent.type === 'ElicitIntent';
lexDialogActionElicitSlot.type === 'ElicitSlot';
strOrNull = lexDialogActionElicitSlot.slots['example'];
str = lexDialogActionElicitSlot.slotToElicit;
str = lexDialogActionElicitSlot.intentName;
const lexEventHandler: AWSLambda.LexHandler = async (
event: AWSLambda.LexEvent,
context: AWSLambda.Context,
) => {
// $ExpectType LexEvent
event;
// $ExpectType Context
context;
str = context.functionName;
return lexResult;
};
+97
View File
@@ -876,6 +876,100 @@ export interface SQSMessageAttributes {
[name: string]: SQSMessageAttribute;
}
// Lex
// https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html#supported-event-source-lex
export interface LexEvent {
currentIntent: {
name: string;
slots: { [name: string]: string | null };
slotDetails: LexSlotDetails;
confirmationStatus: 'None' | 'Confirmed' | 'Denied';
};
bot: {
name: string;
alias: string;
version: string;
};
userId: string;
inputTranscript: string;
invocationSource: 'DialogCodeHook' | 'FulfillmentCodeHook';
outputDialogMode: 'Text' | 'Voice';
messageVersion: '1.0';
sessionAttributes: { [key: string]: string };
requestAttributes: { [key: string]: string } | null;
}
export interface LexSlotResolution {
value: string;
}
export interface LexSlotDetails {
[name: string]: {
// The following line only works in TypeScript Version: 3.0, The array should have at least 1 and no more than 5 items
// resolutions: [LexSlotResolution, LexSlotResolution?, LexSlotResolution?, LexSlotResolution?, LexSlotResolution?];
resolutions: LexSlotResolution[]
originalValue: string;
};
}
export interface LexGenericAttachment {
title: string;
subTitle: string;
imageUrl: string;
attachmentLinkUrl: string;
buttons: Array<{
text: string;
value: string;
}>;
}
export interface LexDialogActionBase {
type: 'Close' | 'ElicitIntent' | 'ElicitSlot' | 'ConfirmIntent';
message?: {
contentType: 'PlainText' | 'SSML' | 'CustomPayload';
content: string;
};
responseCard?: {
version: number;
contentType: 'application/vnd.amazonaws.card.generic';
genericAttachments: LexGenericAttachment[];
};
}
export interface LexDialogActionClose extends LexDialogActionBase {
type: 'Close';
fulfillmentState: 'Fulfilled' | 'Failed';
}
export interface LexDialogActionElicitIntent extends LexDialogActionBase {
type: 'ElicitIntent';
}
export interface LexDialogActionElicitSlot extends LexDialogActionBase {
type: 'ElicitSlot';
intentName: string;
slots: { [name: string]: string | null };
slotToElicit: string;
}
export interface LexDialogActionConfirmIntent extends LexDialogActionBase {
type: 'ConfirmIntent';
intentName: string;
slots: { [name: string]: string | null };
}
export interface LexDialogActionDelegate {
type: 'Delegate';
slots: { [name: string]: string | null };
}
export type LexDialogAction = LexDialogActionClose | LexDialogActionElicitIntent | LexDialogActionElicitSlot | LexDialogActionConfirmIntent | LexDialogActionDelegate;
export interface LexResult {
sessionAttributes?: { [key: string]: string };
dialogAction: LexDialogAction;
}
/**
* AWS Lambda handler function.
* http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
@@ -938,6 +1032,9 @@ export type ScheduledHandler = Handler<ScheduledEvent, void>;
// TODO: Alexa
export type LexHandler = Handler<LexEvent, LexResult>;
export type LexCallback = Callback<LexResult>;
export type APIGatewayProxyHandler = Handler<APIGatewayProxyEvent, APIGatewayProxyResult>;
export type APIGatewayProxyCallback = Callback<APIGatewayProxyResult>;
export type ProxyHandler = APIGatewayProxyHandler; // Old name
@@ -150,3 +150,8 @@ const VisitorStateTest: Visitor<SomeVisitorState> = {
}
}
};
const VisitorAliasTest: Visitor = {
Function() {},
Expression() {},
};
+2
View File
@@ -145,6 +145,8 @@ export class Binding {
export type Visitor<S = {}> = VisitNodeObject<S, Node> & {
[Type in Node["type"]]?: VisitNode<S, Extract<Node, { type: Type; }>>;
} & {
[K in keyof t.Aliases]?: VisitNode<S, t.Aliases[K]>
};
export type VisitNode<S, P> = VisitNodeFunction<S, P> | VisitNodeObject<S, P>;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"private": true,
"dependencies": {
"@babel/types": "^7.0.0"
"@babel/types": "^7.3.0"
}
}
@@ -69,3 +69,12 @@ trans.default('name');
trans.deferred('name');
trans.immediate('name');
trans.exclusive('name');
const transTyped = db.transaction((param: number) => stmt.all(param));
transTyped(1);
trans.default(1);
trans.deferred(1);
trans.immediate(1);
trans.exclusive(1);
// $ExpectError
transTyped('name');
+15 -8
View File
@@ -4,10 +4,17 @@
// Mathew Rumsey <https://github.com/matrumz>
// Santiago Aguilar <https://github.com/sant123>
// Alessandro Vergani <https://github.com/loghorn>
// Andrew Kaiser <https://github.com/andykais>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.0
import Integer = require("integer");
type VariableArgFunction = (...params: any[]) => any;
type ArgumentTypes<F extends VariableArgFunction> = F extends (...args: infer A) => any
? A
: never;
declare namespace BetterSqlite3 {
interface Statement {
database: Database;
@@ -34,12 +41,12 @@ declare namespace BetterSqlite3 {
type: string | null;
}
interface Transaction {
(...params: any[]): any;
default(...params: any[]): any;
deferred(...params: any[]): any;
immediate(...params: any[]): any;
exclusive(...params: any[]): any;
interface Transaction<F extends VariableArgFunction> {
(...params: ArgumentTypes<F>): any;
default(...params: ArgumentTypes<F>): any;
deferred(...params: ArgumentTypes<F>): any;
immediate(...params: ArgumentTypes<F>): any;
exclusive(...params: ArgumentTypes<F>): any;
}
interface Database {
@@ -50,7 +57,7 @@ declare namespace BetterSqlite3 {
inTransaction: boolean;
prepare(source: string): Statement;
transaction(fn: (...params: any[]) => any): Transaction;
transaction<F extends VariableArgFunction>(fn: F): Transaction<F>;
exec(source: string): this;
pragma(source: string, options?: Database.PragmaOptions): any;
checkpoint(databaseName?: string): this;
@@ -113,7 +120,7 @@ declare namespace Database {
type SqliteError = typeof SqliteError;
type Statement = BetterSqlite3.Statement;
type ColumnDefinition = BetterSqlite3.ColumnDefinition;
type Transaction = BetterSqlite3.Transaction;
type Transaction = BetterSqlite3.Transaction<VariableArgFunction>;
type Database = BetterSqlite3.Database;
}
+5
View File
@@ -585,6 +585,11 @@ declare namespace Bull {
*/
getJobCounts(): Promise<JobCounts>;
/**
* Returns a promise that resolves with the job counts for the given queue of the given types.
*/
getJobCountByTypes(types: string[] | string): Promise<JobCounts>;
/**
* Returns a promise that resolves with the quantity of completed jobs.
*/
+6 -1
View File
@@ -127,7 +127,7 @@ declare class ByteBuffer
* Calculates the number of UTF8 characters of a string.JavaScript itself uses UTF- 16, so that a string's length property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
*/
static calculateUTF8Chars( str: string ): number;
/**
* Calculates the number of UTF8 bytes of a string. This is an alias of ByteBuffer#calculateUTF8Bytes.
*/
@@ -574,6 +574,11 @@ declare class ByteBuffer
*/
writeInt8( value: number, offset?: number ): ByteBuffer;
/**
* Write a 64bit signed integer. This is an alias of ByteBuffer#writeInt64.
*/
writeLong( value: number | Long, offset?: number ): ByteBuffer;
/**
* Writes a 16bit signed integer. This is an alias of ByteBuffer#writeInt16.
*/
+71 -72
View File
@@ -1,47 +1,55 @@
import jsdiff = require('diff');
import * as diff from 'diff';
const one = 'beep boop';
const other = 'beep boob blah';
let diff = jsdiff.diffChars(one, other);
printDiff(diff);
let changes = diff.diffChars(one, other);
examineChanges(changes);
const diffArraysResult = jsdiff.diffArrays<string>(['a', 'b', 'c'], ['a', 'c', 'd']);
// $ExpectType void
diff.diffChars(one, other, {
callback: (err, value) => {
err; // $ExpectType undefined
value; // $ExpectType Change[] | undefined
},
});
// $ExpectType void
diff.diffChars(one, other, (err, value) => {
err; // $ExpectType undefined
value; // $ExpectType Change[] | undefined
});
const diffArraysResult = diff.diffArrays(['a', 'b', 'c'], ['a', 'c', 'd']);
diffArraysResult.forEach(result => {
if (result.added) {
console.log(`added ${result.value.length} line(s):`, ...result.value);
} else if (result.removed) {
console.log(`removed ${result.value.length} line(s):`, ...result.value);
} else {
console.log(`no changes`);
}
result.added; // $ExpectType boolean | undefined
result.removed; // $ExpectType boolean | undefined
result.value; // $ExpectType string[]
result.count; // $ExpectType number | undefined
});
interface DiffObj {
value: number;
}
const a: DiffObj = {value: 0};
const b: DiffObj = {value: 1};
const c: DiffObj = {value: 2};
const d: DiffObj = {value: 3};
const arrayOptions: jsdiff.IArrayOptions = {
comparator: (left: DiffObj, right: DiffObj) => {
return left.value === right.value;
}
const a: DiffObj = { value: 0 };
const b: DiffObj = { value: 1 };
const c: DiffObj = { value: 2 };
const d: DiffObj = { value: 3 };
const arrayOptions: diff.ArrayOptions<DiffObj, DiffObj> = {
comparator: (left, right) => {
return left.value === right.value;
},
};
const diffResult = jsdiff.diffArrays([a, b, c], [a, b, d], arrayOptions);
diffResult.forEach(result => {
if (result.added) {
console.log(`added ${result.value.length} line(s):`, ...result.value);
} else if (result.removed) {
console.log(`removed ${result.value.length} line(s):`, ...result.value);
} else {
console.log(`no changes`);
}
const arrayChanges = diff.diffArrays([a, b, c], [a, b, d], arrayOptions);
arrayChanges.forEach(result => {
result.added; // $ExpectType boolean | undefined
result.removed; // $ExpectType boolean | undefined
result.value; // $ExpectType DiffObj[]
result.count; // $ExpectType number | undefined
});
// --------------------------
class LineDiffWithoutWhitespace extends jsdiff.Diff {
class LineDiffWithoutWhitespace extends diff.Diff {
tokenize(value: string): any {
return value.split(/^/m);
}
@@ -52,71 +60,62 @@ class LineDiffWithoutWhitespace extends jsdiff.Diff {
}
const obj = new LineDiffWithoutWhitespace();
diff = obj.diff(one, other);
printDiff(diff);
changes = obj.diff(one, other);
examineChanges(changes);
function printDiff(diff: jsdiff.IDiffResult[]) {
function addLineHeader(decorator: string, str: string | string[]) {
return (typeof str === 'string' ? str.split("\n") : str).map((line, index, array) => {
if (index === array.length - 1 && line === "") {
return line;
} else {
return decorator + line;
}
}).join("\n");
}
diff.forEach((part) => {
if (part.added) {
console.log(addLineHeader("+", part.value));
} else if (part.removed) {
console.log(addLineHeader("-", part.value));
} else {
console.log(addLineHeader(" ", part.value));
}
function examineChanges(diff: diff.Change[]) {
diff.forEach(part => {
part.added; // $ExpectType boolean | undefined
part.removed; // $ExpectType boolean | undefined
part.value; // $ExpectType string
part.count; // $ExpectType number | undefined
});
}
function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) {
const verifyPatch = jsdiff.parsePatch(
jsdiff.createTwoFilesPatch("oldFile.ts", "newFile.ts", oldStr, newStr,
"old", "new", { context: 1 }));
function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: diff.ParsedDiff) {
const verifyPatch = diff.parsePatch(
diff.createTwoFilesPatch('oldFile.ts', 'newFile.ts', oldStr, newStr, 'old', 'new', {
context: 1,
})
);
if (JSON.stringify(verifyPatch[0], Object.keys(verifyPatch[0]).sort()) !== JSON.stringify(uniDiff, Object.keys(uniDiff).sort())) {
console.error("Patch did not match uniDiff");
if (
JSON.stringify(verifyPatch[0], Object.keys(verifyPatch[0]).sort()) !==
JSON.stringify(uniDiff, Object.keys(uniDiff).sort())
) {
throw new Error('Patch did not match uniDiff');
}
}
function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) {
const verifyApply = [
jsdiff.applyPatch(oldStr, uniDiff),
jsdiff.applyPatch(oldStr, [uniDiff])
];
jsdiff.applyPatches([uniDiff], {
loadFile: (index: number, callback: (err: Error, data: string) => void) => {
function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: diff.ParsedDiff) {
const verifyApply = [diff.applyPatch(oldStr, uniDiff), diff.applyPatch(oldStr, [uniDiff])];
diff.applyPatches([uniDiff], {
loadFile: (index, callback) => {
index; // $ExpectType ParsedDiff
callback(undefined, one);
},
patched: (index: number, content: string) => {
patched: (index, content) => {
index; // $ExpectType ParsedDiff
verifyApply.push(content);
},
complete: (err?: Error) => {
if (err) {
console.error(err);
throw err;
}
verifyApply.forEach(result => {
if (result !== newStr) {
console.error("Result did not match newStr");
throw new Error('Result did not match newStr');
}
});
}
},
});
}
const uniDiffPatch = jsdiff.structuredPatch("oldFile.ts", "newFile.ts", one, other,
"old", "new", { context: 1 });
const uniDiffPatch = diff.structuredPatch('oldFile.ts', 'newFile.ts', one, other, 'old', 'new', {
context: 1,
});
verifyPatchMethods(one, other, uniDiffPatch);
const uniDiffStr = jsdiff.createPatch("file.ts", one, other, "old", "new",
{ context: 1 });
const uniDiffApply = jsdiff.parsePatch(uniDiffStr)[0];
const uniDiffStr = diff.createPatch('file.ts', one, other, 'old', 'new', { context: 1 });
const uniDiffApply = diff.parsePatch(uniDiffStr)[0];
verifyApplyMethods(one, other, uniDiffApply);
+392 -111
View File
@@ -1,121 +1,402 @@
// Type definitions for diff 3.5
// Type definitions for diff 4.0
// Project: https://github.com/kpdecker/jsdiff
// Definitions by: vvakame <https://github.com/vvakame>
// szdc <https://github.com/szdc>
// moc-yuto <https://github.com/moc-yuto>
// BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export = JsDiff;
export as namespace JsDiff;
export as namespace Diff;
declare namespace JsDiff {
interface IOptions {
ignoreCase: boolean;
}
export type Callback = (err: undefined, value?: Change[]) => void;
interface ILinesOptions extends IOptions {
ignoreWhitespace?: boolean;
newlineIsToken?: boolean;
}
interface IArrayOptions {
comparator?: (left: any, right: any) => boolean;
}
interface IDiffResult {
value: string;
count?: number;
added?: boolean;
removed?: boolean;
}
interface IDiffArraysResult<T> {
value: T[];
count?: number;
added?: boolean;
removed?: boolean;
}
interface IBestPath {
newPos: number;
componenets: IDiffResult[];
}
interface IHunk {
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
lines: string[];
}
interface IUniDiff {
oldFileName: string;
newFileName: string;
oldHeader: string;
newHeader: string;
index: string;
hunks: IHunk[];
}
class Diff {
diff(oldString: string, newString: string, options?: IOptions): IDiffResult[];
pushComponent(components: IDiffResult[], added: boolean, removed: boolean): void;
extractCommon(basePath: IBestPath, newString: string, oldString: string, diagonalPath: number): number;
equals(left: string, right: string): boolean;
removeEmpty(array: any[]): any[];
castInput(value: any): any;
join(chars: string[]): string;
tokenize(value: string): any; // return types are string or string[]
}
function diffChars(oldStr: string, newStr: string, options?: IOptions): IDiffResult[];
function diffWords(oldStr: string, newStr: string, options?: IOptions): IDiffResult[];
function diffWordsWithSpace(oldStr: string, newStr: string, options?: IOptions): IDiffResult[];
function diffJson(oldObj: object, newObj: object, options?: IOptions): IDiffResult[];
function diffLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[];
function diffCss(oldStr: string, newStr: string, options?: IOptions): IDiffResult[];
function diffTrimmedLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[];
function diffSentences(oldStr: string, newStr: string, options?: IOptions): IDiffResult[];
function diffArrays<T>(oldArr: T[], newArr: T[], options?: IArrayOptions): Array<IDiffArraysResult<T>>;
function createPatch(fileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string;
function createTwoFilesPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string;
function structuredPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): IUniDiff;
function applyPatch(oldStr: string, uniDiff: string | IUniDiff | IUniDiff[]): string;
function applyPatches(uniDiff: IUniDiff[], options: {
loadFile(index: number, callback: (err: Error, data: string) => void): void,
patched(index: number, content: string): void,
complete(err?: Error): void
}): void;
function parsePatch(diffStr: string, options?: {strict: boolean}): IUniDiff[];
function convertChangesToXML(changes: IDiffResult[]): string;
function convertChangesToDMP(changes: IDiffResult[]): Array<{0: number; 1: string; }>;
function merge(mine: string, theirs: string, base: string): IUniDiff;
function canonicalize(obj: any, stack: any[], replacementStack: any[]): any;
export interface CallbackOptions {
/**
* Callback to call with the result instead of returning the result directly.
*/
callback: Callback;
}
export interface BaseOptions {
/**
* `true` to ignore casing difference.
* @default false
*/
ignoreCase?: boolean;
}
export interface WordsOptions extends BaseOptions {
/**
* `true` to ignore leading and trailing whitespace. This is the same as `diffWords()`.
*/
ignoreWhitespace?: boolean;
}
export interface LinesOptions extends BaseOptions {
/**
* `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines()`.
*/
ignoreWhitespace?: boolean;
/**
* `true` to treat newline characters as separate tokens. This allows for changes to the newline structure
* to occur independently of the line content and to be treated as such. In general this is the more
* human friendly form of `diffLines()` and `diffLines()` is better suited for patches and other computer
* friendly output.
*/
newlineIsToken?: boolean;
}
export interface JsonOptions extends LinesOptions {
/**
* Replacer used to stringify the properties of the passed objects.
*/
stringifyReplacer?: (key: string, value: any) => any;
/**
* The value to use when `undefined` values in the passed objects are encountered during stringification.
* Will only be used if `stringifyReplacer` option wasn't specified.
* @default undefined
*/
undefinedReplacement?: any;
}
export interface ArrayOptions<TLeft, TRight> extends BaseOptions {
/**
* Comparator for custom equality checks.
*/
comparator?: (left: TLeft, right: TRight) => boolean;
}
export interface PatchOptions extends LinesOptions {
/**
* Describes how many lines of context should be included.
* @default 4
*/
context?: number;
}
export interface ApplyPatchOptions {
/**
* Number of lines that are allowed to differ before rejecting a patch.
* @default 0
*/
fuzzFactor?: number;
/**
* Callback used to compare to given lines to determine if they should be considered equal when patching.
* Should return `false` if the lines should be rejected.
*
* @default strict equality
*/
compareLine?: (
lineNumber: number,
line: string,
operation: '-' | ' ',
patchContent: string
) => boolean;
}
export interface ApplyPatchesOptions {
loadFile(index: ParsedDiff, callback: (err: any, data: string) => void): void;
patched(index: ParsedDiff, content: string, callback: (err: any) => void): void;
complete(err: any): void;
}
export interface Change {
count?: number;
/**
* Text content.
*/
value: string;
/**
* `true` if the value was inserted into the new string.
*/
added?: boolean;
/**
* `true` if the value was removed from the old string.
*/
removed?: boolean;
}
export interface ArrayChange<T> {
value: T[];
count?: number;
added?: boolean;
removed?: boolean;
}
export interface ParsedDiff {
index?: string;
oldFileName?: string;
newFileName?: string;
oldHeader?: string;
newHeader?: string;
hunks: Hunk[];
}
export interface Hunk {
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
lines: string[];
}
export interface BestPath {
newPos: number;
componenets: Change[];
}
export class Diff {
diff(
oldString: string,
newString: string,
options?: Callback | (ArrayOptions<any, any> & Partial<CallbackOptions>)
): Change[];
pushComponent(components: Change[], added: boolean, removed: boolean): void;
extractCommon(
basePath: BestPath,
newString: string,
oldString: string,
diagonalPath: number
): number;
equals(left: any, right: any): boolean;
removeEmpty(array: any[]): any[];
castInput(value: any): any;
join(chars: string[]): string;
tokenize(value: string): any; // return types are string or string[]
}
/**
* Diffs two blocks of text, comparing character by character.
*
* @returns A list of change objects.
*/
export function diffChars(oldStr: string, newStr: string, options?: BaseOptions): Change[];
export function diffChars(
oldStr: string,
newStr: string,
options: Callback | (BaseOptions & CallbackOptions)
): void;
/**
* Diffs two blocks of text, comparing word by word, ignoring whitespace.
*
* @returns A list of change objects.
*/
export function diffWords(oldStr: string, newStr: string, options?: WordsOptions): Change[];
export function diffWords(
oldStr: string,
newStr: string,
options: Callback | (WordsOptions & CallbackOptions)
): void;
/**
* Diffs two blocks of text, comparing word by word, treating whitespace as significant.
*
* @returns A list of change objects.
*/
export function diffWordsWithSpace(
oldStr: string,
newStr: string,
options?: WordsOptions
): Change[];
export function diffWordsWithSpace(
oldStr: string,
newStr: string,
options: Callback | (WordsOptions & CallbackOptions)
): void;
/**
* Diffs two blocks of text, comparing line by line.
*
* @returns A list of change objects.
*/
export function diffLines(oldStr: string, newStr: string, options?: LinesOptions): Change[];
export function diffLines(
oldStr: string,
newStr: string,
options: Callback | (LinesOptions & CallbackOptions)
): void;
/**
* Diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace.
*
* @returns A list of change objects.
*/
export function diffTrimmedLines(oldStr: string, newStr: string, options?: LinesOptions): Change[];
export function diffTrimmedLines(
oldStr: string,
newStr: string,
options: Callback | (LinesOptions & CallbackOptions)
): void;
/**
* Diffs two blocks of text, comparing sentence by sentence.
*
* @returns A list of change objects.
*/
export function diffSentences(oldStr: string, newStr: string, options?: BaseOptions): Change[];
export function diffSentences(
oldStr: string,
newStr: string,
options: Callback | (BaseOptions & CallbackOptions)
): void;
/**
* Diffs two blocks of text, comparing CSS tokens.
*
* @returns A list of change objects.
*/
export function diffCss(oldStr: string, newStr: string, options?: BaseOptions): Change[];
export function diffCss(
oldStr: string,
newStr: string,
options: Callback | (BaseOptions & CallbackOptions)
): void;
/**
* Diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter
* in this comparison.
*
* @returns A list of change objects.
*/
export function diffJson(
oldObj: string | object,
newObj: string | object,
options?: JsonOptions
): Change[];
export function diffJson(
oldObj: string | object,
newObj: string | object,
options: Callback | (JsonOptions & CallbackOptions)
): void;
/**
* Diffs two arrays, comparing each item for strict equality (`===`).
*
* @returns A list of change objects.
*/
export function diffArrays<TOld, TNew>(
oldArr: TOld[],
newArr: TNew[],
options?: ArrayOptions<TOld, TNew>
): Array<ArrayChange<TOld | TNew>>;
/**
* Creates a unified diff patch.
*
* @param oldFileName String to be output in the filename section of the patch for the removals.
* @param newFileName String to be output in the filename section of the patch for the additions.
* @param oldStr Original string value.
* @param newStr New string value.
* @param oldHeader Additional information to include in the old file header.
* @param newHeader Additional information to include in the new file header.
*/
export function createTwoFilesPatch(
oldFileName: string,
newFileName: string,
oldStr: string,
newStr: string,
oldHeader?: string,
newHeader?: string,
options?: PatchOptions
): string;
/**
* Creates a unified diff patch.
* Just like `createTwoFilesPatch()`, but with `oldFileName` being equal to `newFileName`.
*
* @param fileName String to be output in the filename section.
* @param oldStr Original string value.
* @param newStr New string value.
* @param oldHeader Additional information to include in the old file header.
* @param newHeader Additional information to include in the new file header.
*/
export function createPatch(
fileName: string,
oldStr: string,
newStr: string,
oldHeader?: string,
newHeader?: string,
options?: PatchOptions
): string;
/**
* This method is similar to `createTwoFilesPatch()`, but returns a data structure suitable for further processing.
* Parameters are the same as `createTwoFilesPatch()`.
*
* @param oldFileName String to be output in the `oldFileName` hunk property.
* @param newFileName String to be output in the `newFileName` hunk property.
* @param oldStr Original string value.
* @param newStr New string value.
* @param oldHeader Additional information to include in the `oldHeader` hunk property.
* @param newHeader Additional information to include in the `newHeader` hunk property.
* @returns An object with an array of hunk objects.
*/
export function structuredPatch(
oldFileName: string,
newFileName: string,
oldStr: string,
newStr: string,
oldHeader?: string,
newHeader?: string,
options?: PatchOptions
): ParsedDiff;
/**
* Applies a unified diff patch.
*
* @param patch May be a string diff or the output from the `parsePatch()` or `structuredPatch()` methods.
* @returns A string containing new version of provided data.
*/
export function applyPatch(
source: string,
patch: string | ParsedDiff | [ParsedDiff],
options?: ApplyPatchOptions
): string;
/**
* Applies one or more patches.
* This method will iterate over the contents of the patch and apply to data provided through callbacks.
*
* The general flow for each patch index is:
*
* 1. `options.loadFile(index, callback)` is called. The caller should then load the contents of the file
* and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution.
* 2. `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be
* the return value from `applyPatch()`. When it's ready, the caller should call `callback(err)` callback.
* Passing an `err` will terminate further patch execution.
* 3. Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made.
*/
export function applyPatches(patch: string | ParsedDiff[], options: ApplyPatchesOptions): void;
/**
* Parses a patch into structured data.
*
* @returns A JSON object representation of the a patch, suitable for use with the `applyPatch()` method.
*/
export function parsePatch(diffStr: string, options?: { strict?: boolean }): ParsedDiff[];
/**
* Converts a list of changes to a serialized XML format.
*/
export function convertChangesToXML(changes: Change[]): string;
/**
* Converts a list of changes to [DMP](http://code.google.com/p/google-diff-match-patch/wiki/API) format.
*/
export function convertChangesToDMP(changes: Change[]): Array<[1 | 0 | -1, string]>;
export function merge(mine: string, theirs: string, base: string): ParsedDiff;
export function canonicalize(obj: any, stack: any[], replacementStack: any[]): any;
+3 -4
View File
@@ -2,12 +2,11 @@
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
@@ -21,4 +20,4 @@
"index.d.ts",
"diff-tests.ts"
]
}
}
+1 -7
View File
@@ -1,7 +1 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": false,
"export-just-namespace": false
}
}
{ "extends": "dtslint/dt.json" }
+122
View File
@@ -0,0 +1,122 @@
import jsdiff = require('diff');
const one = 'beep boop';
const other = 'beep boob blah';
let diff = jsdiff.diffChars(one, other);
printDiff(diff);
const diffArraysResult = jsdiff.diffArrays<string>(['a', 'b', 'c'], ['a', 'c', 'd']);
diffArraysResult.forEach(result => {
if (result.added) {
console.log(`added ${result.value.length} line(s):`, ...result.value);
} else if (result.removed) {
console.log(`removed ${result.value.length} line(s):`, ...result.value);
} else {
console.log(`no changes`);
}
});
interface DiffObj {
value: number;
}
const a: DiffObj = {value: 0};
const b: DiffObj = {value: 1};
const c: DiffObj = {value: 2};
const d: DiffObj = {value: 3};
const arrayOptions: jsdiff.IArrayOptions = {
comparator: (left: DiffObj, right: DiffObj) => {
return left.value === right.value;
}
};
const diffResult = jsdiff.diffArrays([a, b, c], [a, b, d], arrayOptions);
diffResult.forEach(result => {
if (result.added) {
console.log(`added ${result.value.length} line(s):`, ...result.value);
} else if (result.removed) {
console.log(`removed ${result.value.length} line(s):`, ...result.value);
} else {
console.log(`no changes`);
}
});
// --------------------------
class LineDiffWithoutWhitespace extends jsdiff.Diff {
tokenize(value: string): any {
return value.split(/^/m);
}
equals(left: string, right: string): boolean {
return left.trim() === right.trim();
}
}
const obj = new LineDiffWithoutWhitespace();
diff = obj.diff(one, other);
printDiff(diff);
function printDiff(diff: jsdiff.IDiffResult[]) {
function addLineHeader(decorator: string, str: string | string[]) {
return (typeof str === 'string' ? str.split("\n") : str).map((line, index, array) => {
if (index === array.length - 1 && line === "") {
return line;
} else {
return decorator + line;
}
}).join("\n");
}
diff.forEach((part) => {
if (part.added) {
console.log(addLineHeader("+", part.value));
} else if (part.removed) {
console.log(addLineHeader("-", part.value));
} else {
console.log(addLineHeader(" ", part.value));
}
});
}
function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) {
const verifyPatch = jsdiff.parsePatch(
jsdiff.createTwoFilesPatch("oldFile.ts", "newFile.ts", oldStr, newStr,
"old", "new", { context: 1 }));
if (JSON.stringify(verifyPatch[0], Object.keys(verifyPatch[0]).sort()) !== JSON.stringify(uniDiff, Object.keys(uniDiff).sort())) {
console.error("Patch did not match uniDiff");
}
}
function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) {
const verifyApply = [
jsdiff.applyPatch(oldStr, uniDiff),
jsdiff.applyPatch(oldStr, [uniDiff])
];
jsdiff.applyPatches([uniDiff], {
loadFile: (index: number, callback: (err: Error, data: string) => void) => {
callback(undefined, one);
},
patched: (index: number, content: string) => {
verifyApply.push(content);
},
complete: (err?: Error) => {
if (err) {
console.error(err);
}
verifyApply.forEach(result => {
if (result !== newStr) {
console.error("Result did not match newStr");
}
});
}
});
}
const uniDiffPatch = jsdiff.structuredPatch("oldFile.ts", "newFile.ts", one, other,
"old", "new", { context: 1 });
verifyPatchMethods(one, other, uniDiffPatch);
const uniDiffStr = jsdiff.createPatch("file.ts", one, other, "old", "new",
{ context: 1 });
const uniDiffApply = jsdiff.parsePatch(uniDiffStr)[0];
verifyApplyMethods(one, other, uniDiffApply);
+121
View File
@@ -0,0 +1,121 @@
// Type definitions for diff 3.5
// Project: https://github.com/kpdecker/jsdiff
// Definitions by: vvakame <https://github.com/vvakame>
// szdc <https://github.com/szdc>
// moc-yuto <https://github.com/moc-yuto>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export = JsDiff;
export as namespace JsDiff;
declare namespace JsDiff {
interface IOptions {
ignoreCase: boolean;
}
interface ILinesOptions extends IOptions {
ignoreWhitespace?: boolean;
newlineIsToken?: boolean;
}
interface IArrayOptions {
comparator?: (left: any, right: any) => boolean;
}
interface IDiffResult {
value: string;
count?: number;
added?: boolean;
removed?: boolean;
}
interface IDiffArraysResult<T> {
value: T[];
count?: number;
added?: boolean;
removed?: boolean;
}
interface IBestPath {
newPos: number;
componenets: IDiffResult[];
}
interface IHunk {
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
lines: string[];
}
interface IUniDiff {
oldFileName: string;
newFileName: string;
oldHeader: string;
newHeader: string;
index: string;
hunks: IHunk[];
}
class Diff {
diff(oldString: string, newString: string, options?: IOptions): IDiffResult[];
pushComponent(components: IDiffResult[], added: boolean, removed: boolean): void;
extractCommon(basePath: IBestPath, newString: string, oldString: string, diagonalPath: number): number;
equals(left: string, right: string): boolean;
removeEmpty(array: any[]): any[];
castInput(value: any): any;
join(chars: string[]): string;
tokenize(value: string): any; // return types are string or string[]
}
function diffChars(oldStr: string, newStr: string, options?: IOptions): IDiffResult[];
function diffWords(oldStr: string, newStr: string, options?: IOptions): IDiffResult[];
function diffWordsWithSpace(oldStr: string, newStr: string, options?: IOptions): IDiffResult[];
function diffJson(oldObj: object, newObj: object, options?: IOptions): IDiffResult[];
function diffLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[];
function diffCss(oldStr: string, newStr: string, options?: IOptions): IDiffResult[];
function diffTrimmedLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[];
function diffSentences(oldStr: string, newStr: string, options?: IOptions): IDiffResult[];
function diffArrays<T>(oldArr: T[], newArr: T[], options?: IArrayOptions): Array<IDiffArraysResult<T>>;
function createPatch(fileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string;
function createTwoFilesPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string;
function structuredPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): IUniDiff;
function applyPatch(oldStr: string, uniDiff: string | IUniDiff | IUniDiff[]): string;
function applyPatches(uniDiff: IUniDiff[], options: {
loadFile(index: number, callback: (err: Error, data: string) => void): void,
patched(index: number, content: string): void,
complete(err?: Error): void
}): void;
function parsePatch(diffStr: string, options?: {strict: boolean}): IUniDiff[];
function convertChangesToXML(changes: IDiffResult[]): string;
function convertChangesToDMP(changes: IDiffResult[]): Array<{0: number; 1: string; }>;
function merge(mine: string, theirs: string, base: string): IUniDiff;
function canonicalize(obj: any, stack: any[], replacementStack: any[]): any;
}
+29
View File
@@ -0,0 +1,29 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"paths": {
"diff": [
"diff/v3"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"diff-tests.ts"
]
}
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": false,
"export-just-namespace": false
}
}
+4
View File
@@ -174,6 +174,10 @@ declare namespace Dockerode {
update(options: {}, callback: Callback<any>): void;
update(options: {}): Promise<any>;
logs(options: ContainerLogsOptions, callback: Callback<NodeJS.ReadableStream>): void;
logs(callback: Callback<NodeJS.ReadableStream>): void;
logs(options?: ContainerLogsOptions): Promise<NodeJS.ReadableStream>;
}
class Task {
+14
View File
@@ -35,6 +35,10 @@ interface MyComponentState {
stateProperty: string;
}
function toComponentType<T>(Component: ComponentClass<T> | StatelessComponent<T>): ComponentClass<T> | StatelessComponent<T> {
return Component;
}
class MyComponent extends Component<MyComponentProps, MyComponentState> {
handleEcho(value: string) {
return value;
@@ -59,6 +63,8 @@ const MyStatelessComponent = (props: StatelessProps) => <span />;
const AnotherStatelessComponent = (props: AnotherStatelessProps) => <span />;
const ComponentType = toComponentType(MyComponent);
// Enzyme.configure
function configureTest() {
const configureAdapter: { adapter: EnzymeAdapter } = { adapter: {} };
@@ -859,6 +865,14 @@ function ReactWrapperTest() {
reactWrapper = new ReactWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, undefined, { attachTo: document.createElement('div') });
reactWrapper = new ReactWrapper<MyComponentProps, MyComponentState>(<MyComponent stringProp="1" numberProp={1} />, reactWrapper, { attachTo: document.createElement('div') });
}
function test_component_type() {
const wrapper1 = shallow(<div><ComponentType stringProp={"S"} numberProp={1} /></div>);
wrapper1.find<MyComponentProps>(ComponentType).props().stringProp; // $ExpectType string
const wrapper2 = mount(<div><ComponentType stringProp={"S"} numberProp={1} /></div>);
wrapper2.find<MyComponentProps>(ComponentType).props().stringProp; // $ExpectType string
}
}
// CheerioWrapper
+13 -11
View File
@@ -27,7 +27,9 @@ export interface ComponentClass<Props> {
new(props: Props, context?: any): Component<Props>;
}
export type StatelessComponent<Props> = (props: Props, context?: any) => JSX.Element;
export type StatelessComponent<Props> = (props: Props, context?: any) => JSX.Element | null;
export type ComponentType<Props> = ComponentClass<Props> | StatelessComponent<Props>;
/**
* Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the
@@ -372,8 +374,8 @@ export class ShallowWrapper<P = {}, S = {}, C = Component> {
* Find every node in the render tree that matches the provided selector.
* @param selector The selector to match.
*/
find<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
find<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>;
find<P2>(component: ComponentType<P2>): ShallowWrapper<P2, any>;
find(props: EnzymePropSelector): ShallowWrapper<any, any>;
find(selector: string): ShallowWrapper<HTMLAttributes, any>;
@@ -381,8 +383,8 @@ export class ShallowWrapper<P = {}, S = {}, C = Component> {
* Removes nodes in the current wrapper that do not match the provided selector.
* @param selector The selector to match.
*/
filter<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
filter<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>;
filter<P2>(component: ComponentType<P2>): ShallowWrapper<P2, any>;
filter(props: EnzymePropSelector | string): ShallowWrapper<P, S>;
/**
@@ -394,8 +396,8 @@ export class ShallowWrapper<P = {}, S = {}, C = Component> {
* Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector
* can be provided and it will filter the children by this selector.
*/
children<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>;
children<P2>(component: ComponentType<P2>): ShallowWrapper<P2, any>;
children(selector: string): ShallowWrapper<HTMLAttributes, any>;
children(props?: EnzymePropSelector): ShallowWrapper<any, any>;
@@ -425,8 +427,8 @@ export class ShallowWrapper<P = {}, S = {}, C = Component> {
*
* Note: can only be called on a wrapper of a single node.
*/
parents<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>;
parents<P2>(component: ComponentType<P2>): ShallowWrapper<P2, any>;
parents(selector: string): ShallowWrapper<HTMLAttributes, any>;
parents(props?: EnzymePropSelector): ShallowWrapper<any, any>;
@@ -436,8 +438,8 @@ export class ShallowWrapper<P = {}, S = {}, C = Component> {
*
* Note: can only be called on a wrapper of a single node.
*/
closest<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
closest<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, never>;
closest<P2>(component: ComponentType<P2>): ShallowWrapper<P2, any>;
closest(props: EnzymePropSelector): ShallowWrapper<any, any>;
closest(selector: string): ShallowWrapper<HTMLAttributes, any>;
@@ -487,8 +489,8 @@ export class ReactWrapper<P = {}, S = {}, C = Component> {
* Find every node in the render tree that matches the provided selector.
* @param selector The selector to match.
*/
find<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
find<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>;
find<P2>(component: ComponentType<P2>): ReactWrapper<P2, any>;
find(props: EnzymePropSelector): ReactWrapper<any, any>;
find(selector: string): ReactWrapper<HTMLAttributes, any>;
@@ -501,16 +503,16 @@ export class ReactWrapper<P = {}, S = {}, C = Component> {
* Removes nodes in the current wrapper that do not match the provided selector.
* @param selector The selector to match.
*/
filter<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
filter<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>;
filter<P2>(component: ComponentType<P2>): ReactWrapper<P2, any>;
filter(props: EnzymePropSelector | string): ReactWrapper<P, S>;
/**
* Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector
* can be provided and it will filter the children by this selector.
*/
children<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>;
children<P2>(component: ComponentType<P2>): ReactWrapper<P2, any>;
children(selector: string): ReactWrapper<HTMLAttributes, any>;
children(props?: EnzymePropSelector): ReactWrapper<any, any>;
@@ -526,8 +528,8 @@ export class ReactWrapper<P = {}, S = {}, C = Component> {
*
* Note: can only be called on a wrapper of a single node.
*/
parents<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>;
parents<P2>(component: ComponentType<P2>): ReactWrapper<P2, any>;
parents(selector: string): ReactWrapper<HTMLAttributes, any>;
parents(props?: EnzymePropSelector): ReactWrapper<any, any>;
@@ -537,8 +539,8 @@ export class ReactWrapper<P = {}, S = {}, C = Component> {
*
* Note: can only be called on a wrapper of a single node.
*/
closest<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
closest<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, never>;
closest<P2>(component: ComponentType<P2>): ReactWrapper<P2, any>;
closest(props: EnzymePropSelector): ReactWrapper<any, any>;
closest(selector: string): ReactWrapper<HTMLAttributes, any>;
+8
View File
@@ -539,4 +539,12 @@ ruleTester.run('my-rule', rule, {
]
});
ruleTester.run('simple-valid-test', rule, {
valid: [
'foo',
'bar',
{ code: 'foo', options: [{ allowFoo: true }] },
]
});
//#endregion
+1 -1
View File
@@ -540,7 +540,7 @@ export class RuleTester {
name: string,
rule: Rule.RuleModule,
tests: {
valid?: RuleTester.ValidTestCase[];
valid?: Array<string | RuleTester.ValidTestCase>;
invalid?: RuleTester.InvalidTestCase[];
},
): void;
@@ -0,0 +1,22 @@
import fastifyRateLimit = require("fastify-rate-limit");
import * as IORedis from 'ioredis';
import { FastifyRequest, DefaultQuery } from "fastify";
import { IncomingMessage } from "http";
fastifyRateLimit();
const fastifyRateLimitOptions: fastifyRateLimit.FastifyRateLimitOptions<FastifyRequest<IncomingMessage, DefaultQuery, {test: string}>> = {
max: 3,
timeWindow: 5000,
cache: 10000,
whitelist: ['127.0.0.1'],
redis: new IORedis({ host: '127.0.0.1' }),
skipOnError: true, // default false
keyGenerator: (req) => {
return req.headers['x-real-ip']
|| req.headers['x-client-ip']
|| req.headers['x-forwarded-for']
|| req.params.test
|| req.ip;
},
};
+74
View File
@@ -0,0 +1,74 @@
// Type definitions for fastify-rate-limit 2.0
// Project: https://github.com/fastify/fastify-rate-limit#readme
// Definitions by: Christian D <https://github.com/pc-jedi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import { Redis } from "ioredis";
import { FastifyRequest } from "fastify";
import { IncomingMessage } from "http";
declare function fastifyRateLimit(): void;
declare namespace fastifyRateLimit {
interface FastifyRateLimitOptions<T = FastifyRequest<IncomingMessage>> {
/**
* Is the maximum number of requests a single client can perform inside a
* timeWindow.
*
* default: 1000
*/
max?: number;
/**
* The duration of the time window, can be expressed in milliseconds (as a
* number) or as a string, see ms too see the supported formats
*
* default: 1000 * 60
*/
timeWindow?: number;
/**
* This plugin internally uses a lru cache to handle the clients, you can
* change the size of the cache with this option.
*
* default: 5000
*/
cache?: number;
/**
* Array of string of ips to exclude from rate limiting.
*
* default: []
*/
whitelist?: string[];
/**
* By default this plugins uses an in-memory store, which is fast but if
* you application works on more than one server it is useless, since the
* data is store locally. You can pass a Redis client here and magically
* the issue is solved. To achieve the maximum speed, this plugins requires
* the use of ioredis.
*
* default: null
*/
redis?: Redis;
/**
* If `true` it will skip errors generated by the storage (eg, redis not
* reachable).
*
* default: false
*/
skipOnError?: boolean;
/**
* Function to generate a unique identifier for each incoming request.
*
* default: (req) => req.ip
*/
keyGenerator?: (req: T) => string;
}
}
export = fastifyRateLimit;
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"fastify": "^1.11.2"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": ["index.d.ts", "fastify-rate-limit-tests.ts"],
"exclude": ["node-modules"]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -0,0 +1,18 @@
import Tasks, { Queue } from "@google-cloud/tasks";
const client = new Tasks({});
const formattedParent = client.locationPath("[PROJECT]", "[LOCATION]");
const queue: Partial<Queue> = {};
const request = {
parent: formattedParent,
queue
};
client
.createQueue(request)
.then(([queue]) => {
const q = queue;
})
.catch(err => {
console.error(err);
});
File diff suppressed because it is too large Load Diff
+14
View File
@@ -0,0 +1,14 @@
{
"private": true,
"dependencies": {
"google-gax": "^0.22.1"
},
"types": "index",
"typesVersions": {
">=3.1.0-0": {
"*": [
"ts3.1/*"
]
}
}
}
@@ -0,0 +1,21 @@
import Tasks, { Queue } from "@google-cloud/tasks";
const client = new Tasks({});
// $ExpectError
const failedClient = new Tasks({ unrecognized: "" });
const formattedParent = client.locationPath("[PROJECT]", "[LOCATION]");
const queue: Partial<Queue> = {};
const request = {
parent: formattedParent,
queue
};
client
.createQueue(request)
.then(([queue]) => {
const q = queue;
})
.catch(err => {
console.error(err);
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"paths": {
"@google-cloud/tasks": ["google-cloud__tasks"]
},
"baseUrl": "../../",
"typeRoots": ["../../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": ["index.d.ts", "google-cloud__tasks-tests.ts"]
}
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"paths": {
"@google-cloud/tasks": ["google-cloud__tasks"]
},
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": ["index.d.ts", "google-cloud__tasks-tests.ts"]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+6
View File
@@ -288,6 +288,12 @@ export declare class RequestError implements Error {
public name: string;
public message: string;
public code: string;
public number?: number;
public state?: number;
public class?: number;
public lineNumber?: number;
public serverName?: string;
public procName?: string;
}
export declare class Transaction extends events.EventEmitter {
+9 -2
View File
@@ -19,6 +19,13 @@ export declare class Form extends events.EventEmitter {
* @param callback
*/
parse(request: http.IncomingMessage, callback?: (error: Error, fields: any, files: any) => any): void;
on(event: "part", listener: (part: Part) => void): this;
on(event: "close", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "progress", listener: (bytesReceived: number, bytesExpected: number) => void): this;
on(event: "field", listener: (name: string, value: string) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
}
export interface File {
@@ -29,7 +36,7 @@ export interface File {
/**
* the filename that the user reports for the file
*/
originalFileName: string;
originalFilename: string;
/**
* the absolute path of the uploaded file on disk
*/
@@ -44,7 +51,7 @@ export interface File {
size: number;
}
interface Part extends stream.Readable {
export interface Part extends stream.Readable {
/**
* the headers for this part. For example, you may be interested in content-type
*/
+1
View File
@@ -247,6 +247,7 @@ declare namespace needle {
export type NeedleCallback = core.NeedleCallback;
export type NeedleHttpVerbs = core.NeedleHttpVerbs;
export type NeedleOptions = core.NeedleOptions;
export type NeedleResponse = core.NeedleResponse;
export type ReadableStream = core.ReadableStream;
/**
+6 -2
View File
@@ -73,14 +73,18 @@ function API_head() {
function API_get() {
// using promises
let resp: needle.NeedleResponse;
needle('get', 'google.com/search?q=syd+barrett')
.then((resp) => {
.then((_resp) => {
// if no http:// is found, Needle will automagically prepend it.
resp = _resp;
});
// using callback
needle.get('google.com/search?q=syd+barrett', (err, resp) => {
needle.get('google.com/search?q=syd+barrett', (err, _resp) => {
// if no http:// is found, Needle will automagically prepend it.
resp = _resp; // assign response
});
}
+84
View File
@@ -0,0 +1,84 @@
// Type definitions for next-seo 1.10
// Project: https://github.com/garmeeh/next-seo#readme
// Definitions by: Thomas Kosiewski <https://github.com/ThomasK33>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import { Component } from "react";
export interface NextSeoProps {
config: Config;
}
export interface Config {
title?: string;
titleTemplate?: string;
description?: string;
canonical?: string;
dangerouslySetAllPagesToNoIndex?: boolean;
noindex?: boolean;
twitter?: Twitter;
facebook?: Facebook;
openGraph?: OpenGraph;
}
export interface Twitter {
cardType?: string;
site?: string;
handle?: string;
}
export interface Facebook {
appId?: number;
}
export interface OpenGraph {
url?: string;
type?: string;
title?: string;
description?: string;
images?: ReadonlyArray<OpenGraphImages>;
defaultImageHeight?: number;
defaultImageWidth?: number;
locale?: string;
site_name?: string;
profile?: OpenGraphProfile;
book?: OpenGraphBook;
article?: OpenGraphArticle;
}
export interface OpenGraphImages {
url?: string;
width?: number;
height?: number;
alt?: string;
}
export interface OpenGraphProfile {
firstName?: string;
lastName?: string;
username?: string;
gender?: string;
}
export interface OpenGraphBook {
authors?: ReadonlyArray<string>;
isbn?: string;
releaseDate?: string;
tags?: ReadonlyArray<string>;
}
export interface OpenGraphArticle {
publishedTime?: string;
modifiedTime?: string;
expirationTime?: string;
authors?: ReadonlyArray<string>;
section?: string;
tags?: ReadonlyArray<string>;
}
export default class NextSeo extends Component<NextSeoProps> { }
+48
View File
@@ -0,0 +1,48 @@
import NextSeo from 'next-seo';
new NextSeo({
config: {
canonical: "",
dangerouslySetAllPagesToNoIndex: false,
description: "",
facebook: {
appId: 0,
},
noindex: false,
openGraph: {
book: {
authors: [""],
isbn: "",
releaseDate: "",
tags: [""],
},
defaultImageHeight: 0,
defaultImageWidth: 0,
description: "",
images: [{
alt: "",
height: 0,
url: "",
width: 0,
}],
locale: "",
profile: {
firstName: "",
gender: "",
lastName: "",
username: "",
},
site_name: "",
title: "",
type: "",
url: "",
},
title: "",
titleTemplate: "",
twitter: {
cardType: "",
handle: "",
site: "",
},
},
});
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"target": "es6",
"jsx": "react",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"next-seo-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1 -1
View File
@@ -53,6 +53,6 @@ export type AppComponentType<P = {}, IP = P, C = NextAppContext> = NextComponent
>;
export class Container extends React.Component {}
export default class App<P = {}> extends React.Component<P & DefaultAppIProps & AppProps> {
export default class App<P = {}, S = {}> extends React.Component<P & DefaultAppIProps & AppProps, S> {
static getInitialProps(context: NextAppContext): Promise<DefaultAppIProps>;
}
+18
View File
@@ -6,6 +6,10 @@ interface TestAppProps {
pageProps: any;
}
interface TestAppState {
color: string;
}
interface TypedQuery extends DefaultQuery {
id?: string;
}
@@ -33,6 +37,20 @@ class TestAppWithProps extends App<TestAppProps & WithExampleProps> {
}
}
class ErrorTestAppWithState extends App<TestAppProps & WithExampleProps, TestAppState> {
static async getInitialProps({ Component, router, ctx }: NextAppContext) {
const pageProps = Component.getInitialProps && (await Component.getInitialProps(ctx));
return { pageProps };
}
render() {
const { Component, router, pageProps, example } = this.props;
return <Component {...pageProps} example={example} />;
}
state: {}; // $ExpectError
}
class TestAppWithTypedQuery extends App {
static async getInitialProps({ ctx }: NextAppContext<TypedQuery>) {
const { id } = ctx.query;
+97
View File
@@ -0,0 +1,97 @@
// Type definitions for node-sql-parser 1.0
// Project: https://github.com/taozhi8833998/node-sql-parser#readme
// Definitions by: taozhi8833998 <https://github.com/taozhi8833998>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
export interface With {
name: string;
stmt: any[];
columns?: any[];
}
export type WhilteListCheckMode = 'table' | 'column';
export interface TableColumnAst {
tableList: string[];
columnsList: string[];
ast: AST[] | AST;
}
export interface From {
db: string | null;
table: string;
as: string | null;
}
export interface Dual {
type: 'dual';
}
export interface Limit {
type: string;
value: number;
}
export interface OrderBy {
type: 'ASC' | 'DESC';
expr: any;
}
export interface ColumnRef {
type: 'column_ref';
table: string | null;
column: string;
}
export interface SetList {
column: string;
value: any;
table: string | null;
}
export interface InsertReplaceValue {
type: 'expr_list';
value: any[];
}
export interface Select {
with: With | null;
type: 'select';
options: any[] | null;
distinct: 'DISTINCT' | null;
columns: any[] | '*';
from: Array<From | Dual> | null;
where: any;
groupby: ColumnRef[] | null;
having: any[] | null;
orderby: OrderBy[] | null;
limit: Limit[] | null;
}
export interface Insert_Replace {
type: 'replace' | 'insert';
db: string | null;
table: string;
columns: string[] | null;
values: InsertReplaceValue[];
}
export interface Update {
type: 'udpate';
db: string | null;
table: string;
set: SetList[];
where: any;
}
export interface Delete {
type: 'delete';
tables: any;
from: Array<From | Dual>;
where: any;
}
export type AST = Select | Insert_Replace | Update | Delete;
export class Parser {
constructor();
parse(sql: string): TableColumnAst;
astify(sql: string): AST[] | AST;
sqlify(ast: AST[] | AST): string;
whiteListCheck(sql: string, whiteList: string[], type?: WhilteListCheckMode): Error | undefined;
tableList(sql: string): string[];
columnList(sql: string): string[];
}
@@ -0,0 +1,19 @@
import { Parser } from 'node-sql-parser';
const parser = new Parser();
const sql = 'select id from tableA';
// $ExpectType Select | Insert_Replace | Update | Delete | AST[]
const selectAst = parser.astify(sql);
// $ExpectType string
parser.sqlify(selectAst);
// $ExpectType string[]
parser.tableList(sql);
// $ExpectType string[]
parser.columnList(sql);
// $ExpectType Error | undefined
parser.whiteListCheck(sql, ['select::null::tableA'], 'table');
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"node-sql-parser-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+2
View File
@@ -32,6 +32,7 @@
// Zane Hannan AU <https://github.com/ZaneHannanAU>
// Jeremie Rodriguez <https://github.com/jeremiergz>
// Samuel Ainsworth <https://github.com/samuela>
// Kyle Uehlein <https://github.com/kuehlein>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/** inspector module types */
@@ -2886,6 +2887,7 @@ declare module "child_process" {
gid?: number;
windowsHide?: boolean;
windowsVerbatimArguments?: boolean;
shell?: boolean | string;
}
interface ExecFileOptionsWithStringEncoding extends ExecFileOptions {
encoding: BufferEncoding;
+2 -2
View File
@@ -1,4 +1,4 @@
// Type definitions for nodegit 0.22
// Type definitions for nodegit 0.24
// Project: https://github.com/nodegit/nodegit
// Definitions by: Dolan Miu <https://github.com/dolanmiu>, Tobias Nießen <https://github.com/tniessen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -79,7 +79,7 @@ export { Refspec } from './ref-spec';
export { Reference } from './reference';
export { RemoteCallbacks } from './remote-callbacks';
export { Remote } from './remote';
export { Repository } from './repository';
export { Repository, RepositoryInitOptions } from './repository';
export { Reset } from './reset';
export { Revparse } from './rev-parse';
export { Revwalk } from './rev-walk';
+245 -211
View File
@@ -1,228 +1,262 @@
// Type definitions for obelisk.js v1.1.0
// Type definitions for obelisk.js 1.2
// Project: https://github.com/nosir/obelisk.js/
// Definitions by: Brian Drupieski <https://github.com/bdrupieski>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace obelisk {
export as namespace obelisk;
export var version: string;
export var author: string;
export var version: string;
export var author: string;
export class Matrix {
constructor(a?: number, b?: number, c?: number, d?: number, tx?: number, ty?: number);
export class Matrix {
constructor(a?: number, b?: number, c?: number, d?: number, tx?: number, ty?: number);
a: number;
b: number;
c: number;
d: number;
tx: number;
ty: number;
}
a: number;
b: number;
c: number;
d: number;
tx: number;
ty: number;
}
export class Point {
constructor(x?: number, y?: number);
export class Point {
constructor(x?: number, y?: number);
x: number;
y: number;
}
x: number;
y: number;
}
export class Point3D {
constructor(x?: number, y?: number, z?: number);
x: number;
y: number;
z: number;
toGlobalCoordinates(offset?: obelisk.Point): obelisk.Point;
}
export class ColorGeom {
static get32(color: number): number;
static applyBrightness(color: number, brightness: number, highlight?: boolean): number;
}
export class ColorPattern {
static GRASS_GREEN: number;
static YELLOW: number;
static WINE_RED: number;
static PINK: number;
static PURPLE: number;
static BLUE: number;
static GRAY: number;
static BLACK: number;
static FINE_COLORS: number[];
static getRandomComfortableColor(): number;
}
export class CanvasTool {
static getPixel(imageData: ImageData, x: number, y: number): number;
}
export class CanvasManager {
static defaultCanvas: HTMLCanvasElement;
static getDefaultCanvas(): HTMLCanvasElement;
static getNewCanvas(): HTMLCanvasElement;
}
export class AbstractColor {
constructor();
inner: number;
border: number;
borderHighlight: number;
left: number;
right: number;
horizontal: number;
leftSlope: number;
rightSlope: number;
}
export class CubeColor extends AbstractColor {
constructor(border?: number, borderHighlight?: number, left?: number, right?: number, horizontal?: number);
BRIGHTNESS_GAIN: number;
getByHorizontalColor(horizontal: number): CubeColor;
}
export class PyramidColor extends AbstractColor {
constructor(border?: number, borderHighlight?: number, left?: number, right?: number);
BRIGHTNESS_GAIN: number;
getByRightColor(horizontal: number): PyramidColor;
}
export class SideColor extends AbstractColor {
constructor(border?: number, inner?: number);
BRIGHTNESS_GAIN: number;
getByInnerColor(inner: number): SideColor;
}
export class SlopeColor extends AbstractColor {
constructor(
border?: number,
borderHighlight?: number,
left?: number,
right?: number,
leftSlope?: number,
rightSlope?: number,
);
BRIGHTNESS_GAIN: number;
getByHorizontalColor(horizontal: number): SlopeColor;
}
export class LineColor extends AbstractColor {
constructor(border?: number, inner?: number);
}
export class AbstractDimension {
constructor();
xAxis: number;
yAxis: number;
zAxis: number;
tall: boolean;
}
export class BrickDimension extends AbstractDimension {
constructor(xAxis?: number, yAxis?: number);
}
export class CubeDimension extends AbstractDimension {
constructor(xAxis?: number, yAxis?: number, zAxis?: number);
}
export class PyramidDimension extends AbstractDimension {
constructor(axis?: number, tall?: boolean);
}
export class SideXDimension extends AbstractDimension {
constructor(xAxis?: number, zAxis?: number);
}
export class SideYDimension extends AbstractDimension {
constructor(yAxis?: number, zAxis?: number);
}
export class Point3D {
constructor(x?: number, y?: number, z?: number);
export class SlopeDimension extends AbstractDimension {
constructor(xAxis?: number, yAxis?: number);
}
x: number;
y: number;
z: number;
export class LineXDimension extends AbstractDimension {
constructor(axis?: number);
}
toGlobalCoordinates(offset?: obelisk.Point): obelisk.Point;
}
export class LineYDimension extends AbstractDimension {
constructor(axis?: number);
}
export class LineZDimension extends AbstractDimension {
constructor(axis?: number);
}
export class BitmapData {
constructor(w: number, h: number, useDefaultCanvas?: boolean);
imageData: ImageData;
canvas: HTMLCanvasElement;
context: CanvasRenderingContext2D;
export class ColorGeom {
static get32(color: number): number;
static applyBrightness(color: number, brightness: number, highlight?: boolean): number;
}
setPixel(posX: number, posY: number, color: number): void;
setPixelByIndex(index: number, color: number): void;
checkPixelAvailable(x: number, y: number): boolean;
floodFill(posX: number, posY: number, color: number): void;
}
export class ColorPattern {
static GRASS_GREEN: number;
static YELLOW: number;
static WINE_RED: number;
static PINK: number;
static PURPLE: number;
static BLUE: number;
static GRAY: number;
static BLACK: number;
static FINE_COLORS: number[];
export class PixelObject {
constructor(primitive: AbstractPrimitive, point3D?: Point3D);
static getRandomComfortableColor(): number;
}
x: number;
y: number;
canvas: HTMLCanvasElement;
}
export class PixelView {
constructor(canvas: HTMLCanvasElement, point?: Point);
canvas: HTMLCanvasElement;
context: CanvasRenderingContext2D;
point: Point;
renderObject(primitive: AbstractPrimitive, point3D?: Point3D): void;
clear(): void;
}
export class AbstractPrimitive {
constructor();
canvas: HTMLCanvasElement;
w: number;
h: number;
dimension: AbstractDimension;
color: AbstractColor;
border: boolean;
bitmapData: BitmapData;
useDefaultCanvas: boolean;
matrix: Matrix;
}
export class CanvasTool {
static getPixel(imageData: ImageData, x: number, y: number): number;
}
export class CanvasManager {
static defaultCanvas: HTMLCanvasElement;
static getDefaultCanvas(): HTMLCanvasElement;
static getNewCanvas(): HTMLCanvasElement;
}
export class AbstractColor {
constructor();
inner: number;
border: number;
borderHighlight: number;
left: number;
right: number;
horizontal: number;
leftSlope: number;
rightSlope: number;
}
export class CubeColor extends AbstractColor {
constructor(border?: number, borderHighlight?: number, left?: number, right?: number, horizontal?: number);
BRIGHTNESS_GAIN: number;
getByHorizontalColor(horizontal: number): CubeColor;
}
export class PyramidColor extends AbstractColor {
constructor(border?: number, borderHighlight?: number, left?: number, right?: number);
BRIGHTNESS_GAIN: number;
getByRightColor(horizontal: number): PyramidColor;
}
export class SideColor extends AbstractColor {
constructor(border?: number, inner?: number);
BRIGHTNESS_GAIN: number;
getByInnerColor(inner: number): SideColor;
}
export class SlopeColor extends AbstractColor {
constructor(border?: number, borderHighlight?: number, left?: number, right?: number, leftSlope?: number, rightSlope?: number);
BRIGHTNESS_GAIN: number;
getByHorizontalColor(horizontal: number): SlopeColor;
}
export class AbstractDimension {
constructor();
xAxis: number;
yAxis: number;
zAxis: number;
tall: boolean;
}
export class BrickDimension extends AbstractDimension {
constructor(xAxis?: number, yAxis?: number);
}
export class CubeDimension extends AbstractDimension {
constructor(xAxis?: number, yAxis?: number, zAxis?: number);
}
export class PyramidDimension extends AbstractDimension {
constructor(axis?: number, tall?: boolean);
}
export class SideXDimension extends AbstractDimension {
constructor(xAxis?: number, zAxis?: number);
}
export class SideYDimension extends AbstractDimension {
constructor(yAxis?: number, zAxis?: number);
}
export class SlopeDimension extends AbstractDimension {
constructor(xAxis?: number, yAxis?: number);
}
export class BitmapData {
constructor(w: number, h: number, useDefaultCanvas?: boolean);
imageData: ImageData;
canvas: HTMLCanvasElement;
context : CanvasRenderingContext2D;
setPixel(posX: number, posY: number, color: number): void;
setPixelByIndex(index: number, color: number): void;
checkPixelAvailable(x: number, y: number): boolean;
floodFill(posX: number, posY: number, color: number): void;
}
export class PixelObject {
constructor(primitive: AbstractPrimitive, point3D?: Point3D);
x: number;
y: number;
canvas: HTMLCanvasElement;
}
export class PixelView {
constructor(canvas: HTMLCanvasElement, point?: Point);
canvas: HTMLCanvasElement;
context: CanvasRenderingContext2D;
point: Point;
renderObject(primitive: AbstractPrimitive, point3D?: Point3D): void;
clear(): void;
}
export class AbstractPrimitive {
constructor();
canvas: HTMLCanvasElement;
w: number;
h: number;
dimension: AbstractDimension;
color: AbstractColor;
border: boolean;
bitmapData: BitmapData;
useDefaultCanvas: boolean;
matrix: Matrix;
}
export class Brick extends AbstractPrimitive {
constructor(dimension?: BrickDimension, color?: SideColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class Cube extends AbstractPrimitive {
constructor(dimension?: CubeDimension, color?: CubeColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class Pyramid extends AbstractPrimitive {
constructor(dimension?: PyramidDimension, color?: PyramidColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class SideX extends AbstractPrimitive {
constructor(dimension?: SideXDimension, color?: SideColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class SideY extends AbstractPrimitive {
constructor(dimension?: SideYDimension, color?: SideColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class SlopeEast extends AbstractPrimitive {
constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class SlopeNorth extends AbstractPrimitive {
constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class SlopeSouth extends AbstractPrimitive {
constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class SlopeWest extends AbstractPrimitive {
constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class Brick extends AbstractPrimitive {
constructor(dimension?: BrickDimension, color?: SideColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class Cube extends AbstractPrimitive {
constructor(dimension?: CubeDimension, color?: CubeColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class Pyramid extends AbstractPrimitive {
constructor(dimension?: PyramidDimension, color?: PyramidColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class SideX extends AbstractPrimitive {
constructor(dimension?: SideXDimension, color?: SideColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class SideY extends AbstractPrimitive {
constructor(dimension?: SideYDimension, color?: SideColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class SlopeEast extends AbstractPrimitive {
constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class SlopeNorth extends AbstractPrimitive {
constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class SlopeSouth extends AbstractPrimitive {
constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class SlopeWest extends AbstractPrimitive {
constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean);
}
export class LineX extends AbstractPrimitive {
constructor(dimension?: LineXDimension, color?: LineColor, useDefaultCanvas?: boolean);
}
export class LineY extends AbstractPrimitive {
constructor(dimension?: LineYDimension, color?: LineColor, useDefaultCanvas?: boolean);
}
export class LineZ extends AbstractPrimitive {
constructor(dimension?: LineZDimension, color?: LineColor, useDefaultCanvas?: boolean);
}
+30 -1
View File
@@ -1,3 +1,5 @@
import * as obelisk from 'obelisk.js';
function test_brick() {
var canvas = <HTMLCanvasElement>document.getElementById('canvas-demo');
@@ -143,4 +145,31 @@ function test_gif_rendering() {
var floorDimension = new obelisk.CubeDimension((size - 2) * (WIDTH + 2), (size - 2) * 9, size);
var floor = new obelisk.Cube(floorDimension, new obelisk.CubeColor(), false);
pixelViewFloor.renderObject(floor, new obelisk.Point3D(-20, -30, 0));
}
}
function test_line_rendering() {
var canvas = document.getElementById('canvas-demo') as HTMLCanvasElement;
// create pixel view container in point
var point = new obelisk.Point(400, 200);
var pixelView = new obelisk.PixelView(canvas, point);
// create brick
var colorX = new obelisk.LineColor(obelisk.ColorPattern.PINK);
var colorY = new obelisk.LineColor(obelisk.ColorPattern.BLACK);
var colorZ = new obelisk.LineColor(obelisk.ColorPattern.BLUE);
var dimensionX = new obelisk.LineXDimension(100);
var dimensionY = new obelisk.LineYDimension(100);
var dimensionZ = new obelisk.LineZDimension(100);
var lineX = new obelisk.LineX(dimensionX, colorX);
var lineY = new obelisk.LineY(dimensionY, colorY);
var lineZ = new obelisk.LineZ(dimensionZ, colorZ);
// render in view
var p3D = new obelisk.Point3D(0, 0, 0);
pixelView.renderObject(lineX, p3D);
pixelView.renderObject(lineY, p3D);
pixelView.renderObject(lineZ, p3D);
}
+1 -1
View File
@@ -7,7 +7,7 @@
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"dt-header": true,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
+6 -6
View File
@@ -10844,8 +10844,8 @@ declare namespace Office {
* </tr>
* <tr>
* <td>Appointment items</td>
* <td>These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurence.</td>
* <td>IPM.Appointment,IPM.Appointment.Occurence</td>
* <td>These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurrence.</td>
* <td>IPM.Appointment,IPM.Appointment.Occurrence</td>
* </tr>
* <tr>
* <td>Message items</td>
@@ -12648,8 +12648,8 @@ declare namespace Office {
* </tr>
* <tr>
* <td>Appointment items</td>
* <td>These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurence.</td>
* <td>IPM.Appointment,IPM.Appointment.Occurence</td>
* <td>These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurrence.</td>
* <td>IPM.Appointment,IPM.Appointment.Occurrence</td>
* </tr>
* <tr>
* <td>Message items</td>
@@ -14303,8 +14303,8 @@ declare namespace Office {
* </tr>
* <tr>
* <td>Appointment items</td>
* <td>These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurence.</td>
* <td>IPM.Appointment,IPM.Appointment.Occurence</td>
* <td>These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurrence.</td>
* <td>IPM.Appointment,IPM.Appointment.Occurrence</td>
* </tr>
* <tr>
* <td>Message items</td>
+6 -6
View File
@@ -10844,8 +10844,8 @@ declare namespace Office {
* </tr>
* <tr>
* <td>Appointment items</td>
* <td>These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurence.</td>
* <td>IPM.Appointment,IPM.Appointment.Occurence</td>
* <td>These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurrence.</td>
* <td>IPM.Appointment,IPM.Appointment.Occurrence</td>
* </tr>
* <tr>
* <td>Message items</td>
@@ -12648,8 +12648,8 @@ declare namespace Office {
* </tr>
* <tr>
* <td>Appointment items</td>
* <td>These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurence.</td>
* <td>IPM.Appointment,IPM.Appointment.Occurence</td>
* <td>These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurrence.</td>
* <td>IPM.Appointment,IPM.Appointment.Occurrence</td>
* </tr>
* <tr>
* <td>Message items</td>
@@ -14303,8 +14303,8 @@ declare namespace Office {
* </tr>
* <tr>
* <td>Appointment items</td>
* <td>These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurence.</td>
* <td>IPM.Appointment,IPM.Appointment.Occurence</td>
* <td>These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurrence.</td>
* <td>IPM.Appointment,IPM.Appointment.Occurrence</td>
* </tr>
* <tr>
* <td>Message items</td>
+3 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for opossum 1.9
// Type definitions for opossum 1.10
// Project: https://github.com/nodeshift/opossum
// Definitions by: Quinn Langille <https://github.com/quinnlangille>
// Willy Zhang <https://github.com/merufm>
@@ -23,6 +23,7 @@ export class CircuitBreaker extends EventEmitter {
readonly closed: boolean;
readonly opened: boolean;
readonly halfOpen: boolean;
readonly isShutdown: boolean;
readonly status: Status;
readonly stats: Stats;
readonly hystrixStats: HystrixStats;
@@ -40,6 +41,7 @@ export class CircuitBreaker extends EventEmitter {
func: (...args: any[]) => Promise<any>,
interval?: number
): void;
shutdown(): void;
}
export enum Event {
+2
View File
@@ -39,6 +39,7 @@ breaker.closed; // $ExpectType boolean
breaker.opened; // $ExpectType boolean
breaker.halfOpen; // $ExpectType boolean
breaker.warmUp; // $ExpectType boolean
breaker.isShutdown; // $ExpectType boolean
breaker.volumeThreshold; // $ExpectType number
breaker.status.stats.latencyMean; // $ExpectType number
breaker.stats.latencyTimes; // $ExpectType number[]
@@ -49,6 +50,7 @@ breaker.open(); // $ExpectType void
breaker.close(); // $ExpectType void
breaker.disable(); // $ExpectType void
breaker.enable(); // $ExpectType void
breaker.shutdown(); // $ExpectType void
// The following are examples are from the libs README and official documentation
// https://nodeshift.github.io/opossum/index.html.
+21 -27
View File
@@ -21,26 +21,7 @@ declare module paper {
/**
* Gives access to paper's configurable settings.
*/
export var settings: {
/**
* controls whether newly created items are automatically inserted into the scene graph, by adding them to project.activeLayer — default: true
*/
insertItems: boolean;
/**
* controls what value newly created items have their item.applyMatrix property set to (Note that not all items can set this to false) — default: true
*/
applyMatrix: boolean;
/**
* the size of the curve handles when drawing selections — default: 4
*/
handleSize: number;
/*
* the default tolerance for hit- tests, when no value is specified — default: 0
*/
hitTolerance: number;
};
export var settings: Settings;
/**
* The currently active project.
@@ -1163,13 +1144,7 @@ declare module paper {
/**
* Gives access to paper's configurable settings.
*/
settings: {
applyMatrix: boolean;
handleSize: number;
hitTolerance: number;
};
settings: Settings;
/**
* The currently active project.
@@ -5481,6 +5456,25 @@ declare module paper {
type: 'mousedown' | 'mouseup' | 'mousedrag' | 'click' | 'doubleclick' | 'mousemove' | 'mouseenter' | 'mouseleave';
}
export interface Settings {
/**
* controls whether newly created items are automatically inserted into the scene graph, by adding them to project.activeLayer — default: true
*/
insertItems: boolean;
/**
* controls what value newly created items have their item.applyMatrix property set to (Note that not all items can set this to false) — default: true
*/
applyMatrix: boolean;
/**
* the size of the curve handles when drawing selections — default: 4
*/
handleSize: number;
/*
* the default tolerance for hit- tests, when no value is specified — default: 0
*/
hitTolerance: number;
}
}
declare module 'paper'
+4
View File
@@ -81,6 +81,10 @@ hitTestResults = paper.project.hitTestAll(hitTestPoint, hitOptionsInterfaceFull)
paper.view.scaling = new paper.Point(1, 1);
paper.settings.insertItems = true
const paperScope = new paper.PaperScope();
paperScope.settings.insertItems = false;
function Examples() {
function BooleanOperations(){
let text = new paper.PointText({
+262 -54
View File
@@ -4,37 +4,121 @@
// Rajab Shakirov <https://github.com/radziksh>
// Paito Anderson <https://github.com/PaitoAnderson>
// Andreas Richter <https://github.com/arichter83>
// Dale Fenton <https://github.com/dalevfenton>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
// TODO: <Token> components
// TypeScript Version: 2.9
import * as React from 'react';
import * as CSS from 'csstype';
export type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
export type StringPropertyNames<T extends object> = { [K in keyof T]: T[K] extends string ? K : never }[keyof T];
export interface TypeaheadFilterbyProps {
filterBy: string[];
labelKey: (string | (() => void));
multiple: boolean;
selected: any[];
caseSensitive: boolean;
ignoreDiacritics: boolean;
/* ---------------------------------------------------------------------------
Constants and Enumerated Types
--------------------------------------------------------------------------- */
export type TypeaheadModel = string|object;
export type TypeaheadBsSizes = 'large' | 'lg' | 'small' | 'sm';
export type TypeaheadAlign = 'justify' | 'left' | 'right';
// if options is an object, only let labelKey be a key of that object, whose value is a string
// or a custom label function that takes a single option and returns a string for the label
export type TypeaheadLabelKey<T extends TypeaheadModel> = T extends object ? (StringPropertyNames<T> | ((option: T) => string)) : never;
// don't allow onBlur, onChange, onFocus or onKeyDown as members of inputProps
// those props should be supplied directly to <Typeahead /> or <AsyncTypeahead />
export interface InputProps extends Omit<React.InputHTMLAttributes<'input'>, 'onBlur'|'onChange'|'onFocus'|'onKeyDown'> { }
/* ---------------------------------------------------------------------------
Typeahead Contexts
--------------------------------------------------------------------------- */
export interface TypeaheadContext<T extends TypeaheadModel> {
activeIndex?: number;
hintText?: string;
initialItem?: T;
isOnlyResult?: boolean;
onActiveItemChange?: (options: T) => void;
onAdd?: (option: T) => void;
onInitialItemChange?: (option: T) => void;
onMenuItemClick?: (option: T, e: Event) => void;
selectHintOnEnter?: boolean;
}
export interface TypeaheadState<T extends TypeaheadModel> {
activeIndex: number|null;
activeItem: T|null;
initialItem: T|null;
isFocused: boolean;
selected: T[];
showMenu: boolean;
shownResults: number;
text: string;
}
export interface TypeaheadMenuProps<T> {
export interface InputContainerPropsSingle<T extends TypeaheadModel> {
'aria-activedescendant': string;
'aria-autocomplete': 'list' | 'both';
'aria-expanded': boolean | 'true' | 'false';
'aria-haspopup': 'listbox';
'aria-owns': string;
autoComplete: string;
disabled: boolean;
inputRef: React.LegacyRef<HTMLInputElement>;
onBlur: (e: Event) => void;
onChange: (selected: T[]) => void;
onClick: (e: Event) => void;
onFocus: (e: Event) => void;
onKeyDown: (e: Event) => void;
placeholder: string|null;
role: 'combobox';
value: string;
}
export interface InputContainerPropsMultiple<T extends TypeaheadModel> extends Omit<InputContainerPropsSingle<T>, 'role'> {
inputClassName: string;
labelKey: TypeaheadLabelKey<T>;
onRemove: (e: Event) => void;
renderToken: (selectedItem: T, props: TypeaheadMenuProps<T>, index: number) => React.ReactNode;
role: '';
selected: T[];
}
export type HintedInputContextKeys = 'hintText' | 'initialItem' | 'onAdd' | 'selectHintOnEnter';
export interface HintedInputContext<T extends TypeaheadModel> extends Pick<TypeaheadContext<T>, HintedInputContextKeys> {}
export type MenuItemContextKeys = 'activeIndex' | 'isOnlyResult' | 'onActiveItemChange' | 'onInitialItemChange' | 'onMenuItemClick';
export interface MenuItemContext<T extends TypeaheadModel> extends Pick<TypeaheadContext<T>, MenuItemContextKeys> {}
export interface TokenContext {
active: boolean;
onBlur: (e: any) => void;
onClick: (e: any) => void;
onFocus: (e: any) => void;
onKeyDown: (e: any) => void;
}
/* ---------------------------------------------------------------------------
Typeahead Props and Component
--------------------------------------------------------------------------- */
export interface TypeaheadContainerProps<T extends TypeaheadModel> {
activeIndex: number | null;
activeItem: T | null;
initialItem: T | null;
isFocused: boolean;
selected: T[];
showMenu: boolean;
shownResults: number;
text: string;
}
export interface TypeaheadProps<T> {
/* For localized accessibility: Should return a string indicating the number of results for screen readers. Receives the current results. */
export interface TypeaheadProps<T extends TypeaheadModel> {
/* For localized accessibility: Should return a string indicating the number of results for screen readers.
Receives the current results. */
a11yNumResults?: () => void;
/* For localized accessibility: Should return a string indicating the number of selections for screen readers. Receives the current selections. */
/* For localized accessibility: Should return a string indicating the number of selections for screen readers.
Receives the current selections. */
a11yNumSelected?: () => void;
/* Specify menu alignment. The default value is justify, which makes the menu as wide as the input and truncates long values.
Specifying left or right will align the menu to that side and the width will be determined by the length of menu item values. */
align?: 'justify' | 'left' | 'right';
align?: TypeaheadAlign;
/* Allows the creation of new selections on the fly. Any new items will be added to the list of selections,
but not the list of original options unless handled as such by Typeahead's parent.
@@ -49,7 +133,7 @@ export interface TypeaheadProps<T> {
bodyContainer?: boolean;
/* Specify the size of the input. */
bsSize?: 'large' | 'lg' | 'small' | 'sm';
bsSize?: TypeaheadBsSizes;
/* Whether or not filtering should be case-sensitive. */
caseSensitive?: boolean;
@@ -60,6 +144,9 @@ export interface TypeaheadProps<T> {
/* The initial value displayed in the text input. */
defaultInputValue?: string;
/* Whether or not the menu is displayed upon initial render. */
defaultOpen?: boolean;
/* Specify any pre-selected options. Use only if you want the component to be uncontrolled. */
defaultSelected?: T[];
@@ -74,7 +161,10 @@ export interface TypeaheadProps<T> {
emptyLabel?: string;
/* Either an array of fields in option to search, or a custom filtering callback. */
filterBy?: (string[] | ((option: T | string, props: TypeaheadFilterbyProps) => boolean));
filterBy?: (string[] | ((option: T, props: AllTypeaheadOwnAndInjectedProps<T>) => boolean));
/* Whether or not to automatically adjust the position of the menu when it reaches the viewport boundaries. */
flip?: boolean;
/* Highlights the menu item if there is only one result and allows selecting that item by hitting enter.
Does not work with allowNew. */
@@ -84,7 +174,7 @@ export interface TypeaheadProps<T> {
ignoreDiacritics?: boolean;
/* Props to be applied directly to the input. onBlur, onChange, onFocus, and onKeyDown are ignored. */
inputProps?: object;
inputProps?: InputProps;
/* Bootstrap 4 only. Adds the `is-invalid` classname to the `form-control`. */
isInvalid?: boolean;
@@ -95,8 +185,9 @@ export interface TypeaheadProps<T> {
/* Bootstrap 4 only. Adds the `is-valid` classname to the `form-control`. */
isValid?: boolean;
/* Specify which option key to use for display or a render function. By default, the selector will use the label key. */
labelKey?: string | ((option: T | string) => string);
/* Specify which option key to use for display or a render function.
By default, the selector will use the label key. */
labelKey?: TypeaheadLabelKey<T>;
/* Maximum height of the dropdown menu. */
maxHeight?: string;
@@ -105,6 +196,9 @@ export interface TypeaheadProps<T> {
so as not to render too many DOM nodes in the case of large data sets. */
maxResults?: number;
/* Id applied to the top-level menu element. Required for accessibility. */
menuId?: string;
/* Number of input characters that must be entered before showing results. */
minLength?: number;
@@ -115,28 +209,35 @@ export interface TypeaheadProps<T> {
newSelectionPrefix?: string;
/* Invoked when the input is blurred. Receives an event. */
onBlur?: (e: Event) => any;
onBlur?: (e: Event) => void;
/* Invoked whenever items are added or removed. Receives an array of the selected options. */
onChange?: (selected: T[]) => any;
onChange?: (selected: T[]) => void;
/* Invoked when the input is focused. Receives an event. */
onFocus?: (e: Event) => any;
onFocus?: (e: Event) => void;
/* Invoked when the input value changes. Receives the string value of the input, as well as the original event. */
onInputChange?: (input: string, e: Event) => any;
onInputChange?: (input: string, e: Event) => void;
/* Invoked when a key is pressed. Receives an event. */
onKeyDown?: (e: Event) => any;
onKeyDown?: (e: Event) => void;
/* Invoked when the menu is hidden. */
onMenuHide?: (e: Event) => any;
/* DEPRECATED: Invoked when the menu is hidden. */
onMenuHide?: () => void;
/* Invoked when the menu is shown. */
onMenuShow?: (e: Event) => any;
/* DEPRECATED: Invoked when the menu is shown. */
onMenuShow?: () => void;
/* Invoked when menu visibility changes. */
onMenuToggle?: (show: boolean) => void;
/* Invoked when the pagination menu item is clicked. */
onPaginate?: (e: Event) => any;
onPaginate?: (e: Event, numResults: number) => void;
/* Whether or not the menu should be displayed. undefined allows the component to control visibility,
while true and false show and hide the menu, respectively. */
open?: boolean;
/* Full set of options, including any pre-selected options. */
options: T[];
@@ -151,13 +252,13 @@ export interface TypeaheadProps<T> {
placeholder?: string;
/* Callback for custom menu rendering. */
renderMenu?: (results: Array<T | string>, menuProps: any) => any;
renderMenu?: (results: T[], menuProps: any) => React.ReactNode;
/* Provides a hook for customized rendering of menu item contents. */
renderMenuItemChildren?: (option: T, props: TypeaheadMenuProps<T>, index: number) => any;
renderMenuItemChildren?: (option: T, props: TypeaheadMenuProps<T>, index: number) => React.ReactNode;
/* Provides a hook for customized rendering of tokens when multiple selections are enabled. */
renderToken?: (selectedItem: T | string, onRemove: () => void) => any;
renderToken?: (selectedItem: T, props: TypeaheadMenuProps<T>, index: number) => React.ReactNode;
/* The selected option(s) displayed in the input. Use this prop if you want to control the component via its parent. */
selected?: T[];
@@ -166,9 +267,13 @@ export interface TypeaheadProps<T> {
selectHintOnEnter?: boolean;
}
export const Typeahead: React.ClassicComponentClass<TypeaheadProps<any>>;
export type AllTypeaheadOwnAndInjectedProps<T extends TypeaheadModel> = TypeaheadProps<T> & TypeaheadContainerProps<T>;
export class Typeahead<T extends TypeaheadModel> extends React.Component<TypeaheadProps<T>> { }
export interface AsyncTypeaheadProps<T> extends TypeaheadProps<T> {
/* ---------------------------------------------------------------------------
AsyncTypeahead Props and Component
--------------------------------------------------------------------------- */
export interface AsyncTypeaheadProps<T extends TypeaheadModel> extends TypeaheadProps<T> {
/* Delay, in milliseconds, before performing search. */
delay?: number;
@@ -179,45 +284,148 @@ export interface AsyncTypeaheadProps<T> extends TypeaheadProps<T> {
onSearch: (query: string) => void;
/* Message displayed in the menu when there is no user input. */
promptText?: string;
promptText?: React.ReactNode;
/* Message to display in the menu while the request is pending. */
searchText?: string;
searchText?: React.ReactNode;
/* Whether or not the component should cache query results. */
useCache?: boolean;
}
export const AsyncTypeahead: React.ClassicComponentClass<AsyncTypeaheadProps<any>>;
export class AsyncTypeahead<T extends TypeaheadModel> extends React.Component<AsyncTypeaheadProps<T>> { }
export interface HighligherProps<T> {
key?: string;
search: string;
optionId?: any;
/* ---------------------------------------------------------------------------
TypeaheadInputSingle & TypeaheadInputMulti Props and Component
--------------------------------------------------------------------------- */
export interface BaseTypeaheadInputProps extends React.InputHTMLAttributes<'input'> {
type: 'text';
}
export const Highlighter: React.ClassicComponentClass<HighligherProps<any>>;
export interface TypeaheadSingleInputWithHocProps<T extends TypeaheadModel> extends
Omit<BaseTypeaheadInputProps, keyof InputContainerPropsSingle<T>>,
InputContainerPropsSingle<T> {}
export interface MenuProps<T> {
export interface TypeaheadMulitInputWithHocProps<T extends TypeaheadModel> extends
Omit<BaseTypeaheadInputProps, keyof InputContainerPropsMultiple<T>>,
HintedInputContext<T>,
InputContainerPropsMultiple<T> {}
export type TypeaheadInputPropKeys = 'bsSize'|'disabled'|'inputProps'|'labelKey'|'multiple'|
'onBlur'|'onChange'|'onFocus'|'onKeyDown'|'placeholder'|'renderToken'|'selected';
export type TypeaheadInputProps<T extends TypeaheadModel> = Pick<TypeaheadProps<T>, TypeaheadInputPropKeys>;
export class TypeaheadInputSingle<T extends TypeaheadModel> extends React.Component<TypeaheadSingleInputWithHocProps<T>> { }
export class TypeaheadInputMulti<T extends TypeaheadModel> extends React.Component<TypeaheadMulitInputWithHocProps<T>> { }
/* ---------------------------------------------------------------------------
Highlighter Props and Component
--------------------------------------------------------------------------- */
export interface HighligherProps {
children: React.ReactNode;
search: string;
}
export class Highlighter extends React.PureComponent<HighligherProps> { }
/* ---------------------------------------------------------------------------
ClearButton Props and Component
--------------------------------------------------------------------------- */
export interface ClearButtonProps extends React.HTMLAttributes<'button'> {
bsSize?: TypeaheadBsSizes;
label?: string;
onClick: React.HTMLAttributes<'button'>['onClick']; // make onClick requried
}
export const ClearButton: React.FunctionComponent<ClearButtonProps>;
/* ---------------------------------------------------------------------------
Loader Props and Component
--------------------------------------------------------------------------- */
export interface LoaderProps {
bsSize: TypeaheadBsSizes;
}
export const Loader: React.FunctionComponent<LoaderProps>;
/* ---------------------------------------------------------------------------
AutosizeInput Props and Component
--------------------------------------------------------------------------- */
export interface AutosizeInputProps extends Pick<React.InputHTMLAttributes<'input'>, 'className' | 'style'> {
inputClassName?: string;
inputRef?: React.LegacyRef<HTMLInputElement>;
inputStyle?: Pick<React.CSSProperties, 'boxSizing' | 'width'>;
style: React.CSSProperties;
}
export class AutosizeInput extends React.Component<AutosizeInputProps> { }
/* ---------------------------------------------------------------------------
Menu Props and Component
--------------------------------------------------------------------------- */
export interface MenuProps {
id: string;
className?: string;
emptyLabel?: string;
innerRef?: string;
innerRef?: React.LegacyRef<HTMLUListElement>;
maxHeight?: string;
style?: CSS.Properties;
style?: React.CSSProperties;
text?: string;
}
export const Menu: React.ClassicComponentClass<MenuProps<any>>;
export type MenuHeaderProps = Omit<React.HTMLProps<'li'>, 'className'>;
export interface MenuItemProps<T> {
export class Menu extends React.Component<MenuProps> {
static Divider: React.FunctionComponent;
static Header: React.FunctionComponent<MenuHeaderProps>;
}
/* ---------------------------------------------------------------------------
TypeaheadMenu Props and Component
--------------------------------------------------------------------------- */
// prop names that Typeahead provides to TypeaheadMenu
export type TypeaheadMenuPropsPick = 'labelKey' | 'newSelectionPrefix'| 'options' | 'renderMenuItemChildren';
export interface TypeaheadMenuProps<T extends TypeaheadModel> extends MenuProps, Pick<AllTypeaheadOwnAndInjectedProps<T>, TypeaheadMenuPropsPick> {}
export class TypeaheadMenu<T extends TypeaheadModel> extends React.Component<TypeaheadMenuProps<T>> { }
/* ---------------------------------------------------------------------------
Menu Item Props and Component
--------------------------------------------------------------------------- */
export interface BaseMenuItemProps extends React.HTMLProps<'li'> {
active?: boolean;
}
export class BaseMenuItem extends React.Component<BaseMenuItemProps> { }
export interface MenuItemProps<T extends TypeaheadModel> extends BaseMenuItemProps {
option: T;
position: number;
label?: string;
active?: boolean;
className?: string;
disabled?: boolean;
onClick?: (e: Event) => any;
onMouseDown?: (e: Event) => any;
}
export const MenuItem: React.ClassicComponentClass<MenuItemProps<any>>;
export class MenuItem<T extends TypeaheadModel> extends React.Component<MenuItemProps<T>> { }
/* ---------------------------------------------------------------------------
Overlay Props and Component
--------------------------------------------------------------------------- */
export type OverlayTypeaheadProps = Pick<TypeaheadProps<any>, 'align' | 'dropup' | 'flip' | 'onMenuHide' | 'onMenuShow' | 'onMenuToggle'>;
export interface OverlayProps extends OverlayTypeaheadProps {
children?: React.ReactNode;
className?: string;
container: HTMLElement;
referenceElement?: HTMLElement;
show?: boolean;
}
export class Overlay extends React.Component<OverlayProps> { }
/* ---------------------------------------------------------------------------
Token Props and Component
--------------------------------------------------------------------------- */
export interface TokenProps extends React.HTMLProps<'div'> {
active?: boolean;
onRemove?: () => void; // Token does not invoke onRemove with any parameters
}
export class Token extends React.Component<TokenProps> { }
@@ -1,6 +0,0 @@
{
"private": true,
"dependencies": {
"csstype": "^2.2.0"
}
}
@@ -1,25 +1,78 @@
import * as React from 'react';
import { Typeahead, Highlighter, Menu, MenuItem } from 'react-bootstrap-typeahead';
import { ClearButton, Typeahead, Highlighter, Menu, MenuItem, Token } from 'react-bootstrap-typeahead';
const options = [
{ name: 'Alabama', population: 4780127, capital: 'Montgomery', region: 'South' },
{ name: 'Alaska', population: 710249, capital: 'Juneau', region: 'West' },
{ name: 'Arizona', population: 6392307, capital: 'Phoenix', region: 'West' },
{ name: 'Arkansas', population: 2915958, capital: 'Little Rock', region: 'South' },
{ name: 'California', population: 37254503, capital: 'Sacramento', region: 'West' },
{ name: 'Colorado', population: 5029324, capital: 'Denver', region: 'West' },
interface State {
capital: string;
name: string;
population: number;
region: string;
setValue: (value: State) => void;
}
interface GroupedStates {
[key: string]: State[];
}
type StringPropertyNames<T> = { [K in keyof T]: T[K] extends string ? K : never }[keyof T];
type StateKeysValid = StringPropertyNames<State>;
const options: State[] = [
{ name: 'Alabama', population: 4780127, capital: 'Montgomery', region: 'South', setValue: () => {} },
{ name: 'Alaska', population: 710249, capital: 'Juneau', region: 'West', setValue: () => {} },
{ name: 'Arizona', population: 6392307, capital: 'Phoenix', region: 'West', setValue: () => {} },
{ name: 'Arkansas', population: 2915958, capital: 'Little Rock', region: 'South', setValue: () => {} },
{ name: 'California', population: 37254503, capital: 'Sacramento', region: 'West', setValue: () => {} },
{ name: 'Colorado', population: 5029324, capital: 'Denver', region: 'West', setValue: () => {} },
];
const stateNames = options.map(o => o.name);
const groups: GroupedStates = options.reduce((accum: GroupedStates, option: State) => {
const optKey = option.name.slice(0, 1).toLowerCase();
if (accum[optKey] !== undefined) {
accum[optKey].push(option);
} else {
accum[optKey] = [option];
}
return accum;
}, {});
class BasicExample extends React.Component {
state = {
multiple: false,
};
genCustomMenu = () => {
const menuItems = Object.keys(groups).reduce((accum, letter) => {
const header = [
<Menu.Divider key={`${letter}-start`} />,
<Menu.Header key={`${letter}-header`}>
{`States starting with: ${letter.toUpperCase()}`}
<ClearButton onClick={() => {}} />
</Menu.Header>,
<Menu.Divider key={`${letter}-end`} />,
];
const states = groups[letter].map((state: State, index: number) => {
return (<MenuItem key={state.name} position={index} option={state}>{state.name}</MenuItem>);
});
return [...accum, ...header, ...states];
}, [] as JSX.Element[]);
return menuItems;
}
render() {
const { multiple } = this.state;
return (
<div>
<Typeahead
options={stateNames}
placeholder="Choose a name"
/>
<Typeahead
options={stateNames}
placeholder="Choose a name"
multiple
filterBy={(option, props) => (props.text.indexOf(option) !== -1)}
/>
<Typeahead
labelKey="name"
multiple={multiple}
@@ -33,7 +86,7 @@ class BasicExample extends React.Component {
multiple={multiple}
options={options}
maxHeight='300px'
filterBy={(option, props) => (props.text.indexOf(option) !== -1) }
filterBy={(option, props) => (props.text.indexOf(option.name) !== -1) }
placeholder="Choose a state..."
/>
<Typeahead
@@ -41,7 +94,7 @@ class BasicExample extends React.Component {
multiple={multiple}
options={options}
maxHeight='300px'
filterBy={(option, {text}) => (text.indexOf(option) !== -1) }
filterBy={(option, {text}) => (text.indexOf(option.name) !== -1) }
placeholder="Choose a state..."
/>
<Typeahead
@@ -49,7 +102,7 @@ class BasicExample extends React.Component {
options={options}
placeholder="Choose a state..."
renderMenuItemChildren={ (option, props, index) =>
<Highlighter key="name" search={props.text}>
<Highlighter key="name" search={props.text || ""}>
{option.name} {index}
</Highlighter>
}
@@ -69,6 +122,23 @@ class BasicExample extends React.Component {
))}
</Menu>
</Typeahead>
<Typeahead
labelKey="name"
options={options}
placeholder="Choose a state..."
renderToken={(selectedItem, props, index) => {
return <Token
active
disabled={false}
tabIndex={5}
href="https://test.com"
onRemove={() => console.log(props.text)}>
{selectedItem.name}<ClearButton onClick={() => {}} />
</Token>;
}}
>
<Menu id="menu-id">{...this.genCustomMenu()}</Menu>
</Typeahead>
</div>
);
}
+10 -9
View File
@@ -4,6 +4,7 @@
// Ali Taheri <https://github.com/alitaheri>,
// Zheyang Song <https://github.com/ZheyangSong>,
// Andrew Hathaway <https://github.com/andrewhathaway>
// Manav Mishra <https://github.com/manav-m>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
@@ -12,11 +13,11 @@ import * as React from "react";
export as namespace ReactGridLayout;
export = ReactGridLayout;
declare class ReactGridLayout extends React.Component<ReactGridLayout.ReactGridLayoutProps> { }
declare class ReactGridLayout extends React.Component<
ReactGridLayout.ReactGridLayoutProps
> {}
declare namespace ReactGridLayout {
type Breakpoints = 'lg' | 'md' | 'sm' | 'xs' | 'xxs';
interface Layout {
/**
* A string corresponding to the component key.
@@ -85,9 +86,9 @@ declare namespace ReactGridLayout {
isResizable?: boolean;
}
type Layouts = {
[P in Breakpoints]?: Layout[];
};
interface Layouts {
[P: string]: Layout[];
}
type ItemCallback = (
layout: Layout[],
@@ -263,12 +264,12 @@ declare namespace ReactGridLayout {
*
* Breakpoint names are arbitrary but must match in the cols and layouts objects.
*/
breakpoints?: {[P in Breakpoints]: number };
breakpoints?: { [P: string]: number };
/**
* Number of cols. This is a breakpoint -> cols map, e.g. `{lg: 12, md: 10, ...}`.
*/
cols?: {[P in Breakpoints]: number };
cols?: { [P: string]: number };
/**
* layouts is an object mapping breakpoints to layouts.
@@ -298,7 +299,7 @@ declare namespace ReactGridLayout {
): void;
}
class Responsive extends React.Component<ResponsiveProps> { }
class Responsive extends React.Component<ResponsiveProps> {}
interface WidthProviderProps {
/**
@@ -54,6 +54,31 @@ class ResponsiveGridTest extends React.Component {
}
}
class ResponsiveGridTestWithCustomBreakpoints extends React.Component {
render() {
const layouts = {
lg: [
{ i: '1', x: 0, y: 0, w: 1, h: 2, static: true },
{ i: '2', x: 1, y: 0, w: 3, h: 2, minW: 2, maxW: 4 },
{ i: '3', x: 4, y: 0, w: 1, h: 2 }
]
};
return (
<Responsive
layouts={layouts}
width={800}
breakpoints={{ lg: 468, sm: 0 }}
cols={{ lg: 12, sm: 6 }}
>
<div key="1">a</div>
<div key="2">b</div>
<div key="3">c</div>
</Responsive>
);
}
}
class ResponsiveGridWidthProviderTest extends React.Component {
render() {
return (
+1 -1
View File
@@ -6,7 +6,7 @@ import * as ReactIs from 'react-is';
// Determining if a Component is Valid
interface CompProps {
forwardedRef: React.Ref<any> | null;
forwardedRef: React.Ref<any>;
children?: React.ReactNode;
}
+3 -2
View File
@@ -1,6 +1,7 @@
// Type definitions for react-json-tree v0.6.5
// Type definitions for react-json-tree 0.6
// Project: https://github.com/alexkuz/react-json-tree/
// Definitions by: Grant Nestor <https://github.com/gnestor>
// Zain Afzal <https://github.com/zainafzal08>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
@@ -18,7 +19,7 @@ export interface JSONTreeProps extends Props<JSONTreeComponent> {
sortObjectKeys?: Function | boolean;
shouldExpandNode?: (keyPath: (string | number)[], data: [any] | {}, level: number) => boolean;
getItemString?: (type: string, data: [any] | {}, itemType: string, itemString: string) => JSX.Element;
labelRenderer?: (raw: [string, string]) => JSX.Element;
labelRenderer?: (keyPath: string[], nodeType?: string, expanded?: boolean, expandable?: boolean) => JSX.Element;
valueRenderer?: (displayValue: string|number, rawValue?: string|number|boolean|null, ...keyPath: (string|number)[]) => JSX.Element;
postprocessValue?: (raw: string) => JSX.Element;
isCustomNode?: () => boolean;
-1
View File
@@ -7,7 +7,6 @@
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
+1
View File
@@ -1,6 +1,7 @@
// Type definitions for react-jss 8.6
// Project: https://github.com/cssinjs/react-jss#readme
// Definitions by: Sebastian Silbermann <https://github.com/eps1lon>
// James Lawrence <https://github.com/jlaw90>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import { createGenerateClassName, JSS, SheetsRegistry } from "jss";
+28 -20
View File
@@ -53,26 +53,33 @@ export type PropsOf<C> = C extends new (props: infer P) => React.Component
*/
export type PropInjector<InjectedProps, AdditionalProps = {}> = <
C extends React.ComponentType<ConsistentWith<PropsOf<C>, InjectedProps>>
>(
>(
component: C
) => React.ComponentType<
Omit<JSX.LibraryManagedAttributes<C, PropsOf<C>>, keyof InjectedProps> &
AdditionalProps
>;
AdditionalProps
>;
export interface CSSProperties extends CSS.Properties<number | string> {
// Allow functions that take the properties of the component and return a CSS value
export type DynamicCSSRule<Props> = {
[K in keyof CSS.Properties<number | string>]:
| CSS.Properties<number | string>[K]
| ((props: Props) => CSS.Properties<number | string>[K])
}[keyof CSS.Properties];
export interface CSSProperties<Props> {
// Allow pseudo selectors and media queries
[k: string]:
| CSS.Properties<number | string>[keyof CSS.Properties]
| CSSProperties;
| DynamicCSSRule<Props>
| CSSProperties<Props>;
}
export type Styles<ClassKey extends string = string> = Record<
export type Styles<ClassKey extends string = string, Props = {}> = Record<
ClassKey,
CSSProperties
>;
export type StyleCreator<C extends string = string, T extends {} = {}> = (
CSSProperties<Props>
>;
export type StyleCreator<C extends string = string, T extends {} = {}, Props = {}> = (
theme: T
) => Styles<C>;
) => Styles<C, Props>;
export interface Theming {
channel: string;
@@ -89,15 +96,16 @@ export interface InjectOptions extends CreateStyleSheetOptions {
export type ClassNameMap<C extends string> = Record<C, string>;
export type WithSheet<
S extends string | Styles | StyleCreator<string, any>,
GivenTheme = undefined
> = {
GivenTheme = undefined,
Props = {}
> = {
classes: ClassNameMap<
S extends string
? S
: S extends StyleCreator<infer C, any>
? C
: S extends Styles<infer C> ? C : never
>;
: S extends StyleCreator<infer C, any, Props>
? C
: S extends Styles<infer C, Props> ? C : never
>;
} & WithTheme<S extends StyleCreator<string, infer T> ? T : GivenTheme>;
export interface WithTheme<T> {
@@ -110,7 +118,7 @@ export interface StyledComponentProps<ClassKey extends string = string> {
innerRef?: React.Ref<any> | React.RefObject<any>;
}
export default function injectSheet<C extends string, T extends object>(
stylesOrCreator: Styles<C> | StyleCreator<C, T>,
export default function injectSheet<C extends string, T extends object, Props = {}>(
stylesOrCreator: Styles<C, Props> | StyleCreator<C, T, Props>,
options?: InjectOptions
): PropInjector<WithSheet<C, T>, StyledComponentProps<C>>;
): PropInjector<WithSheet<C, T, Props>, StyledComponentProps<C>>;
+34 -29
View File
@@ -17,42 +17,44 @@ interface MyTheme {
/**
* helper function to counter typescripts type widening
*/
function createStyles<C extends string>(styles: Styles<C>): Styles<C> {
return styles;
// tslint:disable-next-line:no-unnecessary-generics
function createStyles<Props = {}, C extends string = string>(styles: Styles<C, Props>): Styles<C> {
return styles as Styles<C>;
}
const styles = (theme: MyTheme) =>
createStyles({
myButton: {
color: theme.color.primary,
margin: 1,
"& span": {
fontWeight: "revert"
}
},
myLabel: {
fontStyle: "italic"
}
});
interface ButtonProps extends WithSheet<typeof styles> {
interface ButtonProps {
label: string;
active?: boolean;
}
const Button: React.SFC<ButtonProps> = ({ classes, children }) => {
const styles = (theme: MyTheme) => createStyles({
myButton: {
color: (props: ButtonProps) => props.active ? 'red' : theme.color.primary,
margin: 1,
"& span": {
fontWeight: "revert"
}
},
myLabel: {
fontStyle: "italic"
}
});
const Button: React.SFC<ButtonProps & WithSheet<typeof styles>> = ({active, classes, children}) => {
return (
<button className={classes.myButton}>
<span className={classes.myLabel}>{children}</span>
</button>
<>
<button className={classes.myButton}>
<span className={classes.myLabel}>{children}</span>
</button>
</>
);
};
const ManuallyStyles = () => {
return (
<Button
classes={{ myButton: "my-button", myLabel: "my-label" }}
classes={{myButton: "my-button", myLabel: "my-label"}}
label="Hello, World!"
theme={{ color: { primary: "red", secondary: "blue" } }}
theme={{color: {primary: "red", secondary: "blue"}}}
/>
);
};
@@ -67,7 +69,10 @@ const darkTheme: MyTheme = {
};
const App = () => (
<ThemeProvider theme={darkTheme}>
<StyledButton label="I'm dark" />
<>
<StyledButton label="I'm dark"/>
<StyledButton label="I'm active" active/>
</>
</ThemeProvider>
);
@@ -77,7 +82,7 @@ function ssrRender(req: any, res: { send: (text: string) => any }) {
const body = mockedRenderToString(
<JssProvider classNamePrefix="dt-" registry={sheets}>
<StyledButton label="I come from the server" />
<StyledButton label="I come from the server"/>
</JssProvider>
);
@@ -87,10 +92,10 @@ function ssrRender(req: any, res: { send: (text: string) => any }) {
return res.send(
mockedRenderToString(
<html>
<head>
<style type="text/css">{sheets.toString()}</style>
</head>
<body>{body}</body>
<head>
<style type="text/css">{sheets.toString()}</style>
</head>
<body>{body}</body>
</html>
)
);
+1 -1
View File
@@ -475,7 +475,7 @@ declare namespace React {
}
interface RefForwardingComponent<T, P = {}> {
(props: P & { children?: ReactNode }, ref: Ref<T> | null): ReactElement<any> | null;
(props: P & { children?: ReactNode }, ref: Ref<T>): ReactElement<any> | null;
propTypes?: WeakValidationMap<P>;
contextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
+13 -1
View File
@@ -12,6 +12,7 @@
// Harry Cruse <https://github.com/crusectrl>
// Andrew Palugniok <https://github.com/apalugniok>
// Robert Stigsson <https://github.com/RobertStigsson>
// Kosaku Kurino <https://github.com/kousaku-maron>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
@@ -451,12 +452,23 @@ export interface PieProps extends EventAttributes, Partial<PresentationAttribute
labelLine?: object | ContentRenderer<LineProps & any> | React.ReactElement<any> | boolean;
label?: {
offsetRadius: number;
} | React.ReactElement<any> | ContentRenderer<any> | boolean;
} | React.ReactElement<any> | ContentRenderer<PieLabelRenderProps> | boolean;
activeShape?: object | ContentRenderer<any> | React.ReactElement<any>;
activeIndex?: number | number[];
blendStroke?: boolean;
}
export interface PieLabelRenderProps extends PieProps {
name: string;
percent?: number;
stroke: string;
index?: number;
textAnchor: string;
x: number;
y: number;
[key: string]: any;
}
export class Pie extends React.Component<PieProps> { }
// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it).
+2 -2
View File
@@ -26,8 +26,8 @@ export default class LiveThread extends RedditContent<LiveThread> {
deleteUpdate(options: { id: string; }): Promise<this>;
editSettings(options: LiveThreadSettings): Promise<this>;
getContributors(): Promise<RedditUser[]>;
getDiscussions(options?: ListingOptions): Listing<Submission>;
getRecentUpdates(options?: ListingOptions): Listing<LiveUpdate>;
getDiscussions(options?: ListingOptions): Promise<Listing<Submission>>;
getRecentUpdates(options?: ListingOptions): Promise<Listing<LiveUpdate>>;
inviteContributor(options: { name: string; permissions: Permissions[]}): Promise<this>;
leaveContributor(): Promise<this>;
removeContributor(options: { name: string; }): Promise<this>;
+8 -8
View File
@@ -100,18 +100,18 @@ export default class RedditUser extends RedditContent<RedditUser> {
assignFlair(options: any): Promise<this>;
friend(options: any): Promise<this>;
getComments(options?: any): Listing<Comment>;
getDownvotedContent(options?: any): Listing<Comment | Submission>;
getComments(options?: any): Promise<Listing<Comment>>;
getDownvotedContent(options?: any): Promise<Listing<Comment | Submission>>;
getFriendInformation(): Promise<any>;
getGildedContent(options?: any): Listing<Comment | Submission>;
getHiddenContent(options?: any): Listing<Comment | Submission>;
getGildedContent(options?: any): Promise<Listing<Comment | Submission>>;
getHiddenContent(options?: any): Promise<Listing<Comment | Submission>>;
getMultireddit(name: string): MultiReddit;
getMultireddits(): Promise<MultiReddit[]>;
getOverview(options?: any): Listing<Comment | Submission>;
getSavedContent(options?: any): Listing<Comment | Submission>;
getSubmissions(options?: any): Listing<Submission>;
getOverview(options?: any): Promise<Listing<Comment | Submission>>;
getSavedContent(options?: any): Promise<Listing<Comment | Submission>>;
getSubmissions(options?: any): Promise<Listing<Submission>>;
getTrophies(): Promise<any>;
getUpvotedContent(options?: any): Listing<Comment | Submission>;
getUpvotedContent(options?: any): Promise<Listing<Comment | Submission>>;
giveGold(months: string): Promise<any>;
unfriend(): Promise<any>;
}
+2 -3
View File
@@ -1,8 +1,7 @@
import { Sort } from '../..';
import Comment from './Comment';
import Listing, { ListingOptions } from './Listing';
import RedditUser from './RedditUser';
import Subreddit, { FlairTemplate } from './Subreddit';
import { FlairTemplate } from './Subreddit';
import VoteableContent, { RichTextFlair } from './VoteableContent';
interface Media {
@@ -113,7 +112,7 @@ export default class Submission extends VoteableContent<Submission> {
assignFlair(options: { text: string; cssClass: string; }): Promise<this>;
disableContestMode(): Promise<this>;
enableContestMode(): Promise<this>;
getDuplicates(options?: ListingOptions): Listing<Submission>;
getDuplicates(options?: ListingOptions): Promise<Listing<Submission>>;
getLinkFlairTemplates(): Promise<FlairTemplate[]>;
/* @deprecated */ getRelated(options?: ListingOptions): Submission;
hide(): Promise<this>;
+23 -23
View File
@@ -1,12 +1,12 @@
import { Sort, ModAction, SubmitSelfPostOptions, SubmitLinkOptions, BaseSearchOptions } from '../..';
import { BaseSearchOptions, ModAction, Sort, SubmitLinkOptions, SubmitSelfPostOptions } from '../..';
import Comment from './Comment';
import Listing, { ListingOptions } from './Listing';
import PrivateMessage from './PrivateMessage';
import RedditContent from './RedditContent';
import RedditUser from './RedditUser';
import Submission from './Submission';
import WikiPage, { WikiPageRevision } from './WikiPage';
import { RichTextFlair } from './VoteableContent';
import WikiPage, { WikiPageRevision } from './WikiPage';
export default class Subreddit extends RedditContent<Subreddit> {
accounts_active_is_fuzzed: boolean;
@@ -108,40 +108,40 @@ export default class Subreddit extends RedditContent<Subreddit> {
deleteImage(options: { imageName: string; }): Promise<this>;
deleteUserFlair(name: string): Promise<this>;
editSettings(options: SubredditSettings): Promise<this>;
getBannedUsers(options?: ListingOptions & { name?: string }): Listing<BannedUser>;
getContributors(options?: ListingOptions & { name?: string }): Listing<Contributor>;
getControversial(options?: ListingOptions & { time?: string }): Listing<Submission>;
getEdited(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing<Submission | Comment>;
getHot(options?: ListingOptions): Listing<Submission>;
getBannedUsers(options?: ListingOptions & { name?: string }): Promise<Listing<BannedUser>>;
getContributors(options?: ListingOptions & { name?: string }): Promise<Listing<Contributor>>;
getControversial(options?: ListingOptions & { time?: string }): Promise<Listing<Submission>>;
getEdited(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise<Listing<Submission | Comment>>;
getHot(options?: ListingOptions): Promise<Listing<Submission>>;
getLinkFlairTemplates(linkId: string): Promise<FlairTemplate[]>;
getModerationLog(opts?: ListingOptions & { mods?: string[]; type?: ModActionType}): Listing<ModAction>;
getModerationLog(opts?: ListingOptions & { mods?: string[]; type?: ModActionType}): Promise<Listing<ModAction>>;
getModerators(options?: ListingOptions & { name?: string }): RedditUser[];
getModmail(options?: ListingOptions): Listing<PrivateMessage>;
getModqueue(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing<Submission | Comment>;
getMutedUsers(options?: ListingOptions & { name?: string }): Listing<MutedUser>;
getModmail(options?: ListingOptions): Promise<Listing<PrivateMessage>>;
getModqueue(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise<Listing<Submission | Comment>>;
getMutedUsers(options?: ListingOptions & { name?: string }): Promise<Listing<MutedUser>>;
getMyFlair(): Promise<FlairTemplate>;
getNew(options?: ListingOptions): Listing<Submission>;
getNewComments(options?: ListingOptions): Listing<Comment>;
getNew(options?: ListingOptions): Promise<Listing<Submission>>;
getNewComments(options?: ListingOptions): Promise<Listing<Comment>>;
getRandomSubmission(): Promise<Submission>;
getRecommendedSubreddits(options?: { omit?: string[]; }): Promise<Subreddit[]>;
getReports(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing<Submission | Comment>;
getRising(options?: ListingOptions): Listing<Submission>;
getReports(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise<Listing<Submission | Comment>>;
getRising(options?: ListingOptions): Promise<Listing<Submission>>;
getRules(): Promise<{ rules: Rule[]; site_rules: string[] }>;
getSettings(): Promise<SubredditSettings>;
getSpam(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing<Submission | Comment>;
getSpam(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise<Listing<Submission | Comment>>;
getSticky(options?: { num?: number }): Promise<Submission>;
getStylesheet(): Promise<string>;
getSubmitText(): Promise<string>;
getTop(options?: ListingOptions & { time?: Timespan }): Listing<Submission>;
getUnmoderated(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing<Submission | Comment>;
getTop(options?: ListingOptions & { time?: Timespan }): Promise<Listing<Submission>>;
getUnmoderated(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise<Listing<Submission | Comment>>;
getUserFlair(name: string): Promise<FlairTemplate>;
getUserFlairList(options?: ListingOptions & { name?: string; }): Listing<UserFlair>;
getUserFlairList(options?: ListingOptions & { name?: string; }): Promise<Listing<UserFlair>>;
getUserFlairTemplates(): Promise<FlairTemplate[]>;
getWikiBannedUsers(options?: ListingOptions & { name?: string }): Listing<BannedUser>;
getWikiContributors(options?: ListingOptions & { name?: string }): Listing<Contributor>;
getWikiBannedUsers(options?: ListingOptions & { name?: string }): Promise<Listing<BannedUser>>;
getWikiContributors(options?: ListingOptions & { name?: string }): Promise<Listing<Contributor>>;
getWikiPage(name: string): WikiPage;
getWikiPages(): Promise<WikiPage[]>;
getWikiRevisions(options?: ListingOptions): Listing<WikiPageRevision>;
getWikiRevisions(options?: ListingOptions): Promise<Listing<WikiPageRevision>>;
hideMyFlair(): Promise<this>;
inviteModerator(options: { name: string; permissions?: ModeratorPermission[]; }): Promise<this>;
leaveContributor(): Promise<this>;
@@ -151,7 +151,7 @@ export default class Subreddit extends RedditContent<Subreddit> {
removeModerator(options: { name: string; }): Promise<this>;
removeWikiContributor(options: { name: string; }): Promise<this>;
revokeModeratorInvite(options: { name: string; }): Promise<this>;
search(options: BaseSearchOptions): Listing<Submission>;
search(options: BaseSearchOptions): Promise<Listing<Submission>>;
selectMyFlair(options: { flair_template_id: string; text?: string; }): Promise<this>;
setModeratorPermissions(options: { name: string; permissions: ModeratorPermission; }): Promise<this>;
setMultipleUserFlairs(flairs: Array<{
+2 -2
View File
@@ -13,8 +13,8 @@ export default class WikiPage extends RedditContent<WikiPage> {
addEditor(options: { name: string; }): Promise<this>;
edit(options: EditOptions): Promise<this>;
editSettings(options: Settings): Promise<this>;
getDiscussions(options?: ListingOptions): Listing<Submission>;
getRevisions(options?: ListingOptions): Listing<WikiPageRevision>;
getDiscussions(options?: ListingOptions): Promise<Listing<Submission>>;
getRevisions(options?: ListingOptions): Promise<Listing<WikiPageRevision>>;
getSettings(): Promise<Settings>;
hideRevision(options: { id: string; }): Promise<this>;
removeEditor(options: { name: string; }): Promise<this>;
+4
View File
@@ -81,3 +81,7 @@ export function submissionSearch(query: string, subreddit: string): Promise<List
export function subredditSearch(query: string): Promise<Listing<Subreddit>> {
return r.searchSubreddits({ query });
}
export function getHotFromSubreddit(subreddit: string): Promise<Listing<Submission>> {
return r.getSubreddit(subreddit).getHot({ limit: 10 });
}
+6 -1
View File
@@ -1628,6 +1628,11 @@ export interface TransferOptions {
* Called every time a part of a file was transferred
*/
step?: (total_transferred: number, chunk: number, total: number) => void;
/**
* Integer or string representing the file mode to set for the uploaded file.
*/
mode?: number | string;
}
export interface ReadStreamOptions {
@@ -1703,4 +1708,4 @@ export interface ParsedKey {
export interface ReadFileOptions {
encoding?: string;
flag?: string;
}
}
+3 -1
View File
@@ -102,4 +102,6 @@ sftp.createReadStream("path");
sftp.createWriteStream("path");
sftp.data(0, buffer);
sftp.fastGet("remotePath", "localPath", () => {});
sftp.fastPut("localPath", "remotePath", () => {});
sftp.fastGet("remotePath", "localPath", { concurrency: 64, chunkSize: 32768, step: () => {} }, () => {});
sftp.fastPut("localPath", "remotePath", () => {});
sftp.fastPut("localPath", "remotePath", { concurrency: 64, chunkSize: 32768, step: () => {}, mode: '0755' }, () => {});
+4
View File
@@ -17,5 +17,9 @@ export type WithNotesOptions = string | {
markdownOptions?: MarkedOptions;
};
// It would be preferable to infer the argument types, but that requires TS v 3.1
// export function withNotes(...args: StoryDecorator extends (...a: infer A) => any ? A : never): ReturnType<StoryDecorator>;
export function withNotes(story: RenderFunction, context: { kind: string, story: string }): ReturnType<StoryDecorator>;
// Less-preferred but still supported:
export function withNotes(options?: WithNotesOptions): StoryDecorator;
export function withMarkdownNotes(markdown: string, options?: MarkedOptions): StoryDecorator;
@@ -1,8 +1,11 @@
import * as React from 'react';
import { storiesOf } from '@storybook/react';
import { addDecorator, storiesOf } from '@storybook/react';
import { withNotes, withMarkdownNotes, } from '@storybook/addon-notes';
// New, preferred global registration:
addDecorator(withNotes);
const SIMPLE_MARKDOWN = `
## Markdown for component
+15
View File
@@ -0,0 +1,15 @@
// Type definitions for text-clipper 1.2
// Project: https://github.com/arendjr/text-clipper
// Definitions by: Krzysztof Grzybek <https://github.com/krzysztof-grzybek>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface Options {
breakWords?: boolean;
html?: boolean;
imageWeight?: number;
indicator?: string;
maxLines?: number;
}
declare function clip(string: string, maxLength: number, options?: Options): string;
export = clip;
+5
View File
@@ -0,0 +1,5 @@
import clip = require('text-clipper');
clip('text', 123); // $ExpectType string
clip('text', 123, { breakWords: true, html: false }); // $ExpectType string
clip('text', 123, { imageWeight: 123, indicator: 'something', maxLines: 321 }); // $ExpectType string
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"text-clipper-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1
View File
@@ -867,6 +867,7 @@ export class BufferGeometry extends EventDispatcher {
boundingBox: Box3;
boundingSphere: Sphere;
drawRange: { start: number, count: number };
userData: {[key: string]: any};
getIndex(): BufferAttribute;
setIndex( index: BufferAttribute|number[] ): void;
+18
View File
@@ -0,0 +1,18 @@
// Type definitions for uuidv4 2.0
// Project: https://github.com/thenativeweb/uuidv4#readme
// Definitions by: Rindo Hinase <https://github.com/Hinaser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = uuidv4;
declare function uuidv4(): string;
declare namespace uuidv4 {
type EmptyUUIDv4 = '00000000-0000-0000-0000-000000000000';
function is(value: string): boolean;
function empty(): string;
function fromString(text: string): string;
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"strictFunctionTypes": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"uuidv4-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+13
View File
@@ -0,0 +1,13 @@
import * as uuidv4 from 'uuidv4'; // uuidv4 is () => string
// $ExpectType string
uuidv4();
// $ExpectType string
uuidv4.empty();
// $ExpectType boolean
uuidv4.is('00000000-0000-0000-0000-000000000000');
// $ExpectType string
uuidv4.fromString("test");
+4 -4
View File
@@ -459,7 +459,7 @@ export class DataSet<T extends DataItem | DataGroup | Node | Edge> {
* @returns When no item is found, null is returned when a single item was requested,
* and and empty Array is returned in case of multiple id's.
*/
get(id: IdType, options?: DataSelectionOptions<T>): T;
get(id: IdType, options?: DataSelectionOptions<T>): T|null;
/**
* Get multiple items from the DataSet.
@@ -494,7 +494,7 @@ export class DataSet<T extends DataItem | DataGroup | Node | Edge> {
* @param [options] Optional options.
* @returns The mapped items.
*/
map(callback: (item: T, id: IdType) => any, options?: DataSelectionOptions<T>): any[];
map<M>(callback: (item: T, id: IdType) => M, options?: DataSelectionOptions<T>): M[];
/**
* Find the item with maximum value of specified field.
@@ -589,7 +589,7 @@ export interface DataSelectionOptions<T> {
/**
* Order the items by a field name or custom sort function.
*/
order?: string | any;
order?: string | ((a: T, b: T) => number);
/**
* Determine the type of output of the get function.
@@ -597,7 +597,7 @@ export interface DataSelectionOptions<T> {
* The default returnType is an Array.
* The Object type will return a JSON object with the ID's as keys.
*/
returnType?: string;
returnType?: "Array" | "Object";
}
export class DataView<T extends DataItem | DataGroup> {
+3 -1
View File
@@ -8,6 +8,7 @@
// Vincent Pizzo <https://github.com/vincentjames501>
// Robert Bullen <https://github.com/robertbullen>
// Yusuke Sato <https://github.com/sat0yu>
// Dan Rumney <https://github.com/dancrumb>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
@@ -66,7 +67,8 @@ export interface Schema<T> {
strict(isStrict: boolean): this;
strip(strip: boolean): this;
withMutation(fn: (current: this) => void): void;
default(value?: any): this;
default(value: any): this;
default(): T;
nullable(isNullable: boolean): this;
required(message?: TestOptionsMessage): this;
notRequired(): this;