diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 0380b02e1e..8c7f823a07 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -4293,6 +4293,7 @@ /types/timer-machine/ @dolanmiu /types/timezone-js/ @bonnici /types/tinajs__tina/ @Jimexist +/types/tinajs__tina-redux/ @Jimexist /types/tinder/ @pingec /types/tiny-slider-react/ @screendriver /types/tinycolor2/ @M-Zuber @geertjansen @nvh diff --git a/types/agenda/agenda-tests.ts b/types/agenda/agenda-tests.ts index e4de026c0e..2c011efaf7 100644 --- a/types/agenda/agenda-tests.ts +++ b/types/agenda/agenda-tests.ts @@ -67,6 +67,9 @@ var mongoConnectionString = "mongodb://127.0.0.1/agenda"; await job.save(); const jobs = await agenda.jobs({ name: 'printAnalyticsReport' }); + jobs.forEach((job) => { + job.save(); + }); let numRemoved = await agenda.cancel({ name: 'printAnalyticsReport' }); diff --git a/types/agenda/index.d.ts b/types/agenda/index.d.ts index d728a76032..be07b84aaf 100644 --- a/types/agenda/index.d.ts +++ b/types/agenda/index.d.ts @@ -96,7 +96,7 @@ declare class Agenda extends EventEmitter { * Find all Jobs matching `query` and pass same back in cb(). * @param query */ - jobs(query: any): Promise; + jobs(query: any): Promise[]>; /** * Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want diff --git a/types/agent-base/agent-base-tests.ts b/types/agent-base/agent-base-tests.ts new file mode 100644 index 0000000000..116ff8af96 --- /dev/null +++ b/types/agent-base/agent-base-tests.ts @@ -0,0 +1,23 @@ +import agent = require('agent-base'); + +agent(); // $ExpectType Agent +agent({ timeout: 1000 }); // $ExpectType Agent + +agent((req, opts) => {}); // $ExpectType Agent +agent((req, opts) => {}, { timeout: 1000 }); // $ExpectType Agent + +agent(async (req, opts) => {}); // $ExpectType Agent +agent(async (req, opts) => {}, { timeout: 1000 }); // $ExpectType Agent + +agent(0); // $ExpectError +agent(1); // $ExpectError +agent(''); // $ExpectError +agent(true); // $ExpectError +agent(null); // $ExpectError + +agent((req, opts) => {}, 0); // $ExpectError +agent((req, opts) => {}, 1); // $ExpectError +agent((req, opts) => {}, ''); // $ExpectError +agent((req, opts) => {}, true); // $ExpectError +agent((req, opts) => {}, null); // $ExpectError +agent((req, opts) => {}, (req, opts) => {}); // $ExpectError diff --git a/types/agent-base/index.d.ts b/types/agent-base/index.d.ts new file mode 100644 index 0000000000..0b1e4d3018 --- /dev/null +++ b/types/agent-base/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for agent-base 4.2 +// Project: https://github.com/TooTallNate/node-agent-base#readme +// Definitions by: Christopher Quadflieg +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import { EventEmitter } from 'events'; + +declare namespace Agent { + type AgentCallback = ( + req?: any, + opts?: { + secureEndpoint: boolean; + } + ) => void; + + interface AgentOptions { + timeout?: number; + host?: string; + port?: number; + [key: string]: any; + } + + interface Agent extends EventEmitter { + _promisifiedCallback: boolean; + timeout: number | null; + options?: AgentOptions; + callback: AgentCallback; + addRequest: (req?: any, opts?: any) => void; + freeSocket: (socket: any, opts: any) => void; + } +} + +/** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + */ +declare function Agent(opts?: Agent.AgentOptions): Agent.Agent; +declare function Agent( + callback: Agent.AgentCallback, + opts?: Agent.AgentOptions +): Agent.Agent; + +export = Agent; diff --git a/types/agent-base/tsconfig.json b/types/agent-base/tsconfig.json new file mode 100644 index 0000000000..dc6db21f70 --- /dev/null +++ b/types/agent-base/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "agent-base-tests.ts" + ] +} diff --git a/types/agent-base/tslint.json b/types/agent-base/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/agent-base/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/angular-desktop-notification/index.d.ts b/types/angular-desktop-notification/index.d.ts index 6281396b66..2e017da49b 100644 --- a/types/angular-desktop-notification/index.d.ts +++ b/types/angular-desktop-notification/index.d.ts @@ -22,7 +22,7 @@ declare module 'angular' { * This is an experimental technology * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/badge */ - badge?: USVString; + badge?: string; /** * The data read-only property of the Notification interface returns a structured clone of the notification's data, @@ -40,7 +40,7 @@ declare module 'angular' { * Note: This feature is available in Web Workers. * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/image */ - image?: USVString; + image?: string; /** * The renotify read-only property of the Notification interface specifies whether the user should be notified after a diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index 963b5deae6..f2aad6bb59 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -731,11 +731,12 @@ function test_angular_forEach() { this.push(`${key}: ${value}`); }, log); // expect(log).toEqual(['name: misko', 'gender: male']); - // $ExpectType NodeListOf - angular.forEach(document.getElementsByTagName('img'), (value, key, obj) => { + // TODO: Set minimum version to ts3.1 where this is always HTMLCollectionOf + type Collection = NodeListOf | HTMLCollectionOf; + const collection: Collection = angular.forEach(document.getElementsByTagName('img'), (value, key, obj) => { value; // $ExpectType HTMLImageElement key; // $ExpectType number - obj; // $ExpectType NodeListOf + const collection: Collection = obj; }); // $ExpectType number[] angular.forEach([1, 2, 3], (value, key, obj) => { diff --git a/types/arangodb/arangodb-tests.ts b/types/arangodb/arangodb-tests.ts index 7e0fd6383e..98315235ea 100644 --- a/types/arangodb/arangodb-tests.ts +++ b/types/arangodb/arangodb-tests.ts @@ -96,3 +96,13 @@ console.log( RETURN u `.toArray() ); + +const view = db._view("yolo")!; +view.properties({ + locale: "C", + commit: { + consolidate: { + bytes: { segmentThreshold: 20 } + } + } +}); diff --git a/types/arangodb/index.d.ts b/types/arangodb/index.d.ts index 5c3f56020f..be738e6717 100644 --- a/types/arangodb/index.d.ts +++ b/types/arangodb/index.d.ts @@ -837,11 +837,68 @@ declare namespace ArangoDB { // Views - interface View { - // TODO - [key: string]: any; + interface ArangoSearchView { + _dbName: string; + _id: string; + name(): string; + type(): ViewType; + rename(newName: string): void; + properties( + newProperties?: ArangoSearchViewPropertiesOptions + ): ArangoSearchViewProperties; + } + + interface ArangoSearchViewConsolidate { + threshold: number; + segmentThreshold: number; + } + + interface ArangoSearchViewCollectionLink { + analyzers?: string[]; + fields?: { [key: string]: ArangoSearchViewCollectionLink | undefined }; + includeAllFields?: boolean; + trackListPositions?: boolean; + storeValues?: "none" | "id"; + } + + interface ArangoSearchViewProperties { + id: string; + name: string; + type: "arangosearch"; + commit: { + cleanupIntervalStep: number; + commitIntervalMsec: number; + consolidate: { + bytes?: ArangoSearchViewConsolidate; + bytes_accum?: ArangoSearchViewConsolidate; + count?: ArangoSearchViewConsolidate; + fill?: ArangoSearchViewConsolidate; + }; + }; + locale: string; + links: { + [key: string]: ArangoSearchViewCollectionLink | undefined; + }; + } + + interface ArangoSearchViewPropertiesOptions { + locale?: string; + commit?: { + consolidate?: + | "none" + | { + count?: Partial; + bytes?: Partial; + bytes_accum?: Partial; + fill?: Partial; + }; + commitIntervalMsec?: number; + cleanupIntervalStep?: number; + }; + links?: { + [key: string]: ArangoSearchViewCollectionLink | undefined; + }; } - type ViewProperties = object; // TODO // Global @@ -923,13 +980,13 @@ declare namespace ArangoDB { ): DocumentMetadata; // Views - _view(name: string): View | null; - _views(): View[]; + _view(name: string): ArangoSearchView | null; + _views(): ArangoSearchView[]; _createView( name: string, type: ViewType, - properties: ViewProperties - ): View; + properties: ArangoSearchViewPropertiesOptions + ): ArangoSearchView; _dropView(name: string): void; // Global @@ -1392,7 +1449,7 @@ declare module "@arangodb/foxx/router" { } declare module "@arangodb/foxx/graphql" { - import { GraphQLSchema, formatError } from "graphql"; + import { formatError, GraphQLSchema } from "graphql"; type GraphQLModule = object; type GraphQLFormatErrorFunction = typeof formatError; interface GraphQLOptions { diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index b0dea303cd..12201df0ba 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -741,7 +741,7 @@ context.fail(error); context.fail(str); /* Handler */ -let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; +const handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; /* In node8.10 runtime, handlers may return a promise for the result value, so existing async * handlers that return Promise before calling the callback will now have a `null` result. @@ -749,7 +749,7 @@ let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AW * since the upgrade effort should be pretty low in most cases, and it points them at a nicer solution. */ // $ExpectError -let legacyAsyncHandler: AWSLambda.APIGatewayProxyHandler = async ( +const legacyAsyncHandler: AWSLambda.APIGatewayProxyHandler = async ( event: AWSLambda.APIGatewayProxyEvent, context: AWSLambda.Context, cb: AWSLambda.Callback, @@ -757,7 +757,7 @@ let legacyAsyncHandler: AWSLambda.APIGatewayProxyHandler = async ( cb(null, { statusCode: 200, body: 'No longer valid' }); }; -let node8AsyncHandler: AWSLambda.APIGatewayProxyHandler = async ( +const node8AsyncHandler: AWSLambda.APIGatewayProxyHandler = async ( event: AWSLambda.APIGatewayProxyEvent, context: AWSLambda.Context, cb: AWSLambda.Callback, @@ -765,7 +765,7 @@ let node8AsyncHandler: AWSLambda.APIGatewayProxyHandler = async ( return { statusCode: 200, body: 'Is now valid!' }; }; -let inferredHandler: AWSLambda.S3Handler = (event, context, cb) => { +const inferredHandler: AWSLambda.S3Handler = (event, context, cb) => { // $ExpectType S3Event event; str = event.Records[0].eventName; @@ -782,35 +782,35 @@ let inferredHandler: AWSLambda.S3Handler = (event, context, cb) => { }; // Test using default Callback type still works. -let defaultCallbackHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; +const defaultCallbackHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; // Specific types let s3Handler: AWSLambda.S3Handler = (event: AWSLambda.S3Event, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; // Test old name -let s3CreateHandler: AWSLambda.S3Handler = (event: AWSLambda.S3CreateEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const s3CreateHandler: AWSLambda.S3Handler = (event: AWSLambda.S3CreateEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; s3Handler = s3CreateHandler; -let dynamoDBStreamHandler: AWSLambda.DynamoDBStreamHandler = (event: AWSLambda.DynamoDBStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const dynamoDBStreamHandler: AWSLambda.DynamoDBStreamHandler = (event: AWSLambda.DynamoDBStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; -let snsHandler: AWSLambda.SNSHandler = (event: AWSLambda.SNSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const snsHandler: AWSLambda.SNSHandler = (event: AWSLambda.SNSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; -let cognitoUserPoolHandler: AWSLambda.CognitoUserPoolTriggerHandler = (event: AWSLambda.CognitoUserPoolEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const cognitoUserPoolHandler: AWSLambda.CognitoUserPoolTriggerHandler = (event: AWSLambda.CognitoUserPoolEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; -let cloudFormationCustomResourceHandler: AWSLambda.CloudFormationCustomResourceHandler = +const cloudFormationCustomResourceHandler: AWSLambda.CloudFormationCustomResourceHandler = (event: AWSLambda.CloudFormationCustomResourceEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; -let cloudWatchLogsHandler: AWSLambda.CloudWatchLogsHandler = (event: AWSLambda.CloudWatchLogsEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const cloudWatchLogsHandler: AWSLambda.CloudWatchLogsHandler = (event: AWSLambda.CloudWatchLogsEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; -let scheduledHandler: AWSLambda.ScheduledHandler = (event: AWSLambda.ScheduledEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const scheduledHandler: AWSLambda.ScheduledHandler = (event: AWSLambda.ScheduledEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; let apiGtwProxyHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.APIGatewayProxyEvent, context: AWSLambda.Context, cb: AWSLambda.APIGatewayProxyCallback) => { }; // Test old names -let proxyHandler: AWSLambda.ProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => { }; +const proxyHandler: AWSLambda.ProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => { }; apiGtwProxyHandler = proxyHandler; -let codePipelineHandler: AWSLambda.CodePipelineHandler = (event: AWSLambda.CodePipelineEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const codePipelineHandler: AWSLambda.CodePipelineHandler = (event: AWSLambda.CodePipelineEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; -let cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => { +const cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => { cb(); cb(null); cb(new Error('')); @@ -820,14 +820,14 @@ let cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLa cb(null, { }); }; -let cloudFrontResponseHandler: AWSLambda.CloudFrontResponseHandler = (event: AWSLambda.CloudFrontResponseEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontResponseCallback) => { }; +const cloudFrontResponseHandler: AWSLambda.CloudFrontResponseHandler = (event: AWSLambda.CloudFrontResponseEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontResponseCallback) => { }; -let customAuthorizerHandler: AWSLambda.CustomAuthorizerHandler = (event: AWSLambda.CustomAuthorizerEvent, context: AWSLambda.Context, cb: AWSLambda.CustomAuthorizerCallback) => { }; +const customAuthorizerHandler: AWSLambda.CustomAuthorizerHandler = (event: AWSLambda.CustomAuthorizerEvent, context: AWSLambda.Context, cb: AWSLambda.CustomAuthorizerCallback) => { }; interface CustomEvent { eventString: string; eventBool: boolean; } interface CustomResult { resultString: string; resultBool?: boolean; } type CustomCallback = AWSLambda.Callback; -let customHandler: AWSLambda.Handler = (event, context, cb) => { +const customHandler: AWSLambda.Handler = (event, context, cb) => { // $ExpectType CustomEvent event; str = event.eventString; @@ -841,9 +841,9 @@ let customHandler: AWSLambda.Handler = (event, contex cb(null, { resultString: bool }); }; -let kinesisStreamHandler: AWSLambda.KinesisStreamHandler = (event: AWSLambda.KinesisStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; +const kinesisStreamHandler: AWSLambda.KinesisStreamHandler = (event: AWSLambda.KinesisStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; -let SQSMessageHandler: AWSLambda.SQSHandler = (event: AWSLambda.SQSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; +const SQSMessageHandler: AWSLambda.SQSHandler = (event: AWSLambda.SQSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; // See https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-sqs const SQSEvent: AWSLambda.SQSEvent = { @@ -867,7 +867,7 @@ const SQSEvent: AWSLambda.SQSEvent = { ] }; -let SQSMessageLegacyAsyncHandler: AWSLambda.SQSHandler = async ( +const SQSMessageLegacyAsyncHandler: AWSLambda.SQSHandler = async ( event: AWSLambda.SQSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback, @@ -886,7 +886,7 @@ let SQSMessageLegacyAsyncHandler: AWSLambda.SQSHandler = async ( cb(new Error()); }; -let SQSMessageNode8AsyncHandler: AWSLambda.SQSHandler = async ( +const SQSMessageNode8AsyncHandler: AWSLambda.SQSHandler = async ( event: AWSLambda.SQSEvent, context: AWSLambda.Context ) => { @@ -899,3 +899,26 @@ let SQSMessageNode8AsyncHandler: AWSLambda.SQSHandler = async ( str = context.functionName; return; }; + +const firehoseEventHandler: AWSLambda.FirehoseTransformationHandler = ( + event: AWSLambda.FirehoseTransformationEvent, + context: AWSLambda.Context, + callback: AWSLambda.FirehoseTransformationCallback +) => { + // $ExpectType FirehoseTransformationEvent + event; + str = event.records[0].recordId; + + // $ExpectType Context + context; + str = context.functionName; + callback(null, { + records: [ + { + recordId: event.records[0].recordId, + result: 'Ok' as AWSLambda.FirehoseRecordTransformationStatus, + data: 'eyJmb28iOiJiYXIifQ==', + } + ] + }); +}; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index e124f98f75..db6a5a89f3 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -20,6 +20,7 @@ // Aneil Mallavarapu // Jeremy Nagel // Louis Larry +// Daniel Papukchiev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -212,27 +213,27 @@ export type S3CreateEvent = S3Event; // old name export interface CognitoUserPoolTriggerEvent { version: number; triggerSource: - | "PreSignUp_SignUp" - | "PostConfirmation_ConfirmSignUp" - | "PreAuthentication_Authentication" - | "PostAuthentication_Authentication" - | "CustomMessage_SignUp" - | "CustomMessage_AdminCreateUser" - | "CustomMessage_ResendCode" - | "CustomMessage_ForgotPassword" - | "CustomMessage_UpdateUserAttribute" - | "CustomMessage_VerifyUserAttribute" - | "CustomMessage_Authentication" - | "DefineAuthChallenge_Authentication" - | "CreateAuthChallenge_Authentication" - | "VerifyAuthChallengeResponse_Authentication" - | "PreSignUp_AdminCreateUser" - | "PostConfirmation_ConfirmForgotPassword" - | "TokenGeneration_HostedAuth" - | "TokenGeneration_Authentication" - | "TokenGeneration_NewPasswordChallenge" - | "TokenGeneration_AuthenticateDevice" - | "TokenGeneration_RefreshTokens"; + | "PreSignUp_SignUp" + | "PostConfirmation_ConfirmSignUp" + | "PreAuthentication_Authentication" + | "PostAuthentication_Authentication" + | "CustomMessage_SignUp" + | "CustomMessage_AdminCreateUser" + | "CustomMessage_ResendCode" + | "CustomMessage_ForgotPassword" + | "CustomMessage_UpdateUserAttribute" + | "CustomMessage_VerifyUserAttribute" + | "CustomMessage_Authentication" + | "DefineAuthChallenge_Authentication" + | "CreateAuthChallenge_Authentication" + | "VerifyAuthChallengeResponse_Authentication" + | "PreSignUp_AdminCreateUser" + | "PostConfirmation_ConfirmForgotPassword" + | "TokenGeneration_HostedAuth" + | "TokenGeneration_Authentication" + | "TokenGeneration_NewPasswordChallenge" + | "TokenGeneration_AuthenticateDevice" + | "TokenGeneration_RefreshTokens"; region: string; userPoolId: string; userName?: string; @@ -241,8 +242,8 @@ export interface CognitoUserPoolTriggerEvent { clientId: string; }; request: { - userAttributes: {[key: string]: string}; - validationData?: {[key: string]: string}; + userAttributes: { [key: string]: string }; + validationData?: { [key: string]: string }; codeParameter?: string; usernameParameter?: string; newDeviceUsed?: boolean; @@ -252,8 +253,8 @@ export interface CognitoUserPoolTriggerEvent { challengeMetaData?: string; }>; challengeName?: string; - privateChallengeParameters?: {[key: string]: string}; - challengeAnswer?: {[key: string]: string}; + privateChallengeParameters?: { [key: string]: string }; + challengeAnswer?: { [key: string]: string }; }; response: { autoConfirmUser?: boolean; @@ -263,8 +264,8 @@ export interface CognitoUserPoolTriggerEvent { challengeName?: string; issueTokens?: boolean; failAuthentication?: boolean; - publicChallengeParameters?: {[key: string]: string}; - privateChallengeParameters?: {[key: string]: string}; + publicChallengeParameters?: { [key: string]: string }; + privateChallengeParameters?: { [key: string]: string }; challengeMetaData?: string; answerCorrect?: boolean; }; @@ -550,7 +551,7 @@ export interface CodePipelineEvent { inputArtifacts: Artifact[]; outputArtifacts: Artifact[]; artifactCredentials: Credentials; - encryptionKey?: EncryptionKey & {type: 'KMS'}; + encryptionKey?: EncryptionKey & { type: 'KMS' }; continuationToken?: string; }; }; @@ -645,6 +646,47 @@ export interface KinesisStreamEvent { Records: KinesisStreamRecord[]; } +// Kinesis Data Firehose Event +// https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-kinesis-firehose +// https://docs.aws.amazon.com/firehose/latest/dev/data-transformation.html +// https://aws.amazon.com/blogs/compute/amazon-kinesis-firehose-data-transformation-with-aws-lambda/ +// Examples in the lambda blueprints +export interface FirehoseTransformationEvent { + invocationId: string; + deliveryStreamArn: string; + region: string; + records: FirehoseTransformationEventRecord[]; +} + +export interface FirehoseTransformationEventRecord { + recordId: string; + approximateArrivalTimestamp: number; + /** Base64 encoded */ + data: string; + kinesisRecordMetadata?: FirehoseRecordMetadata; +} + +export interface FirehoseRecordMetadata { + shardId: string; + partitionKey: string; + approximateArrivalTimestamp: string; + sequenceNumber: string; + subsequenceNumber: string; +} + +export type FirehoseRecordTransformationStatus = 'Ok' | 'Dropped' | 'ProcessingFailed'; + +export interface FirehoseTransformationResultRecord { + recordId: string; + result: FirehoseRecordTransformationStatus; + /** Encode in Base64 */ + data: string; +} + +export interface FirehoseTransformationResult { + records: FirehoseTransformationResultRecord[]; +} + // SQS // https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html#supported-event-source-sqs export interface SQSRecord { @@ -657,7 +699,7 @@ export interface SQSRecord { eventSource: string; eventSourceARN: string; awsRegion: string; - } +} export interface SQSEvent { Records: SQSRecord[]; @@ -757,7 +799,8 @@ export type CloudFrontResponseCallback = Callback; export type KinesisStreamHandler = Handler; -// TODO: Kinesis Firehose +export type FirehoseTransformationCallback = Callback; +export type FirehoseTransformationHandler = Handler; export type CustomAuthorizerHandler = Handler; export type CustomAuthorizerCallback = Callback; diff --git a/types/babel__core/index.d.ts b/types/babel__core/index.d.ts index 84f49c20fc..277228341b 100644 --- a/types/babel__core/index.d.ts +++ b/types/babel__core/index.d.ts @@ -10,10 +10,10 @@ import { GeneratorOptions } from "@babel/generator"; import traverse, { Visitor, NodePath } from "@babel/traverse"; import template from "@babel/template"; import * as t from "@babel/types"; -import { BabylonOptions } from "babylon"; +import { ParseOptions } from "@babel/parser"; export { - BabylonOptions, + ParseOptions, GeneratorOptions, t as types, template, @@ -217,7 +217,7 @@ export interface TransformOptions { * * Default: `{}` */ - parserOpts?: BabylonOptions | null; + parserOpts?: ParseOptions | null; /** * List of plugins to load and use diff --git a/types/babel__core/tsconfig.json b/types/babel__core/tsconfig.json index 22eb208383..2f96e019cb 100644 --- a/types/babel__core/tsconfig.json +++ b/types/babel__core/tsconfig.json @@ -22,6 +22,9 @@ "@babel/generator": [ "babel__generator" ], + "@babel/parser": [ + "babel__parser" + ], "@babel/template": [ "babel__template" ], diff --git a/types/backbone.marionette/backbone.marionette-tests.ts b/types/backbone.marionette/backbone.marionette-tests.ts index c6400b2672..2b86849622 100644 --- a/types/backbone.marionette/backbone.marionette-tests.ts +++ b/types/backbone.marionette/backbone.marionette-tests.ts @@ -135,6 +135,15 @@ class MyView extends Marionette.View { } } +class MyOtherView extends MyView { + private readonly foo: string; + + constructor(model: MyModel) { + super(model); + this.foo = 'bar'; + } +} + class MainRegion extends Marionette.Region { constructor() { super(); @@ -185,10 +194,20 @@ class MyHtmlElRegion extends Marionette.Region { } } -class MyCollectionView extends Marionette.CollectionView { +class MyCollectionView extends Marionette.CollectionView { constructor() { super(); + + this.childView = (model: MyModel) => { + if (model.get('isFoo')) { + return MyView; + } + + return MyOtherView; + }; + this.childView = MyView; + this.childViewEvents = { render() { console.log('a childView has been rendered'); @@ -282,7 +301,7 @@ function CollectionViewTests() { cv.collection.add(new MyModel()); app.mainRegion.show(cv); cv.emptyView = MyView; - const view: Marionette.CollectionView = cv.destroy(); + const view: Marionette.CollectionView = cv.destroy(); } class MyController { diff --git a/types/backbone.marionette/index.d.ts b/types/backbone.marionette/index.d.ts index 0b717c9bb1..bacd045ba1 100644 --- a/types/backbone.marionette/index.d.ts +++ b/types/backbone.marionette/index.d.ts @@ -3,7 +3,8 @@ // Definitions by: Zeeshan Hamid , // Natan Vivo , // Sven Tschui , -// Volker Nauruhn +// Volker Nauruhn , +// Ard Timmerman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -1157,7 +1158,7 @@ export interface CollectionViewOptions< /** * Specify a child view to use. */ - childView?: (() => typeof Backbone.View) | typeof Backbone.View; + childView?: ((model: TModel) => typeof Backbone.View) | typeof Backbone.View; /** * Define options to pass to the childView constructor. @@ -1219,7 +1220,7 @@ export class CollectionView { new(...args: any[]): TView }) | { new(...args: any[]): TView }; + childView: ((model: TModel) => { new(...args: any[]): TView }) | { new(...args: any[]): TView }; /** * Define options to pass to the childView constructor. diff --git a/types/blazy/blazy-tests.ts b/types/blazy/blazy-tests.ts index 835b0e6472..e3aedaabd4 100644 --- a/types/blazy/blazy-tests.ts +++ b/types/blazy/blazy-tests.ts @@ -38,7 +38,7 @@ var tester: BlazyInstance = new Blazy({ /* Functions tests */ tester.revalidate(); -var elements = document.getElementsByTagName('img'); +var elements = document.getElementsByTagName('img'); tester.load(elements, true); tester.destroy(); diff --git a/types/blazy/index.d.ts b/types/blazy/index.d.ts index 8a7183366d..661f651c0b 100644 --- a/types/blazy/index.d.ts +++ b/types/blazy/index.d.ts @@ -53,7 +53,7 @@ interface BlazyInstance { * Forces the given element(s) to load if not collapsed. If you also want to load a collapsed/hidden elements you can add true as the second parameter. * You can pass a single element or a list of elements. Tested with getElementById, getElementsByClassName, querySelectorAll, querySelector and jQuery selector. */ - load(elements: Element|Element[]|HTMLElement|HTMLElement[]|NodeList, force: boolean): void; + load(elements: Element|Element[]|HTMLElement|HTMLElement[]|HTMLCollection|NodeList, force: boolean): void; /** * Unbind events and resets image array. diff --git a/types/bootstrap/bootstrap-tests.ts b/types/bootstrap/bootstrap-tests.ts index f0bbbea7f2..9a80afc654 100755 --- a/types/bootstrap/bootstrap-tests.ts +++ b/types/bootstrap/bootstrap-tests.ts @@ -1,3 +1,5 @@ +declare let aHtmlElement: HTMLElement; + // -------------------------------------------------------------------------------------- // Alert // -------------------------------------------------------------------------------------- @@ -78,7 +80,7 @@ $("#collapse").collapse({ }); $("#collapse").collapse({ - parent: document.body, + parent: aHtmlElement, }); $("#collapse").collapse({ @@ -122,11 +124,11 @@ $("#dropdown").dropdown({ }); $("#dropdown").dropdown({ - boundary: document.body, + boundary: aHtmlElement, }); $("#dropdown").dropdown({ - reference: document.body, + reference: aHtmlElement, }); // -------------------------------------------------------------------------------------- @@ -340,5 +342,5 @@ $("#tooltip").tooltip({ }); $("#tooltip").tooltip({ - boundary: document.body, + boundary: aHtmlElement, }); diff --git a/types/bricks.js/bricks.js-tests.ts b/types/bricks.js/bricks.js-tests.ts index dbef221df0..b916e97aca 100644 --- a/types/bricks.js/bricks.js-tests.ts +++ b/types/bricks.js/bricks.js-tests.ts @@ -1,7 +1,7 @@ import Bricks from 'bricks.js'; const bricks = Bricks({ - container: document.body.firstChild!, + container: document.body!.firstChild!, packed: 'packed', sizes: [ { columns: 2, gutter: 10 }, diff --git a/types/bull/bull-tests.tsx b/types/bull/bull-tests.tsx index c2e0d3161f..a8c7f403a7 100644 --- a/types/bull/bull-tests.tsx +++ b/types/bull/bull-tests.tsx @@ -6,7 +6,10 @@ import Redis = require("ioredis"); import Queue = require("bull"); const videoQueue = new Queue('video transcoding', 'redis://127.0.0.1:6379'); -const audioQueue = new Queue('audio transcoding', {redis: {port: 6379, host: '127.0.0.1'}}); // Specify Redis connection using object +const audioQueue = new Queue('audio transcoding', { + redis: {port: 6379, host: '127.0.0.1'}, // Specify Redis connection using object + settings: {}, +}); const imageQueue: Queue.Queue<{ image: string }> = new Queue('image transcoding'); videoQueue.process((job, done) => { diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index 6ed6fa88e7..a11ae0257a 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -88,7 +88,7 @@ declare namespace Bull { /** * Define a custom backoff strategy */ - backoffStrategies: { + backoffStrategies?: { [key: string]: (attemptsMade: number, err: typeof Error) => number; }; } diff --git a/types/bull/tsconfig.json b/types/bull/tsconfig.json index 3ce6f08792..7dbd4e7b61 100644 --- a/types/bull/tsconfig.json +++ b/types/bull/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/cesium/index.d.ts b/types/cesium/index.d.ts index f2bb11479c..6c34023eae 100644 --- a/types/cesium/index.d.ts +++ b/types/cesium/index.d.ts @@ -3593,7 +3593,7 @@ declare namespace Cesium { cull?: boolean; asynchronous?: boolean; debugShowBoundingVolume?: boolean; - shadows: ShadowMode + shadows?: ShadowMode }); destroy(): void; getGeometryInstanceAttributes(id: any): any; diff --git a/types/clipboard-js/clipboard-js-tests.ts b/types/clipboard-js/clipboard-js-tests.ts index ef1bfbdf5d..bcc576b7c9 100644 --- a/types/clipboard-js/clipboard-js-tests.ts +++ b/types/clipboard-js/clipboard-js-tests.ts @@ -1,4 +1,4 @@ clipboard.copy("Hello World"); -clipboard.copy(document.body).then(() => console.log("success")); +clipboard.copy(document.body!).then(() => console.log("success")); clipboard.paste().then(val => console.log(val)); diff --git a/types/clipboard/clipboard-tests.ts b/types/clipboard/clipboard-tests.ts index a2ae8f9354..1a9a170087 100644 --- a/types/clipboard/clipboard-tests.ts +++ b/types/clipboard/clipboard-tests.ts @@ -14,6 +14,12 @@ const cb5 = new ClipboardJS(".btn", { action: elem => "copy", target: elem => null }); +const cb6 = new ClipboardJS(".btn", { + action: elem => "copy", + text: trigger => trigger.getAttribute('aria-label'), + target: trigger => trigger.nextElementSibling, + container: document.getElementById('modal') +}); cb1.destroy(); ClipboardJS.isSupported(); diff --git a/types/clipboard/index.d.ts b/types/clipboard/index.d.ts index 2405c0c6f0..ceb15b885b 100644 --- a/types/clipboard/index.d.ts +++ b/types/clipboard/index.d.ts @@ -49,6 +49,14 @@ declare namespace ClipboardJS { * @returns Text to be copied. */ text?(elem: Element): string; + + /** + * For use in Bootstrap Modals or with any + * other library that changes the focus + * you'll want to set the focused element + * as the container value. + */ + container?: Element; } interface Event { diff --git a/types/couchbase/couchbase-tests.ts b/types/couchbase/couchbase-tests.ts index d04b71c907..e6ea7c12d3 100644 --- a/types/couchbase/couchbase-tests.ts +++ b/types/couchbase/couchbase-tests.ts @@ -31,6 +31,11 @@ bucket.manager().createPrimaryIndex(function() { }); }); +// Ensure bucket.upsert is composable with normal callbacks +function composable(callback: (err?: Error) => void) { + bucket.upsert('key', {value: 1}, callback); +} + // From https://developer.couchbase.com/documentation/server/current/sdk/nodejs/n1ql-queries-with-sdk.html function n1ql_a() { const n1qlquery = N1qlQuery.fromString('SELECT name, email FROM users WHERE name=$1'); diff --git a/types/couchbase/index.d.ts b/types/couchbase/index.d.ts index f55ac6dbe9..813ee8f110 100644 --- a/types/couchbase/index.d.ts +++ b/types/couchbase/index.d.ts @@ -2019,10 +2019,10 @@ declare namespace Bucket { */ interface OpCallback { /** - * @param error The error for the operation. This can either be an Error object or a value which evaluates to false (null, undefined, 0 or false). + * @param error The error for the operation. This can either be an Error object or a value which evaluates to false. * @param result The result of the operation that was executed. This usually contains at least a cas property, and on some operations will contain a value property as well. */ - (error: CouchbaseError | number, result: any): void; + (error: CouchbaseError | null, result: any): void; } /** diff --git a/types/cqrs-domain/index.d.ts b/types/cqrs-domain/index.d.ts index f826b45ffd..33db11b857 100644 --- a/types/cqrs-domain/index.d.ts +++ b/types/cqrs-domain/index.d.ts @@ -252,7 +252,7 @@ declare namespace Domain { /** * @param data is the command data - * @callback callback is optional, if not defined as function argument you can throw errors or return errors here (sync way) + * @param callback is optional, if not defined as function argument you can throw errors or return errors here (sync way) */ type preLoadConditionHandler = (data: any, callback?: (err: string | Error) => string | Error) => void | string | Error; @@ -295,7 +295,7 @@ declare namespace Domain { /** * @param data is the command data * @param aggregate is the aggregate object - * @callback callback is optional, if not defined as function argument you can throw errors or return errors here (sync way) + * @param callback is optional, if not defined as function argument you can throw errors or return errors here (sync way) */ type preConditionHandler = (data: any, aggregate: AggregateModel, callback?: (err: string | Error) => string | Error) => void | string | Error; diff --git a/types/cssnano/cssnano-tests.ts b/types/cssnano/cssnano-tests.ts new file mode 100644 index 0000000000..17828e1b02 --- /dev/null +++ b/types/cssnano/cssnano-tests.ts @@ -0,0 +1,17 @@ +import cssnano = require('cssnano'); +import { Transformer } from 'postcss'; + +const nano1: Transformer = cssnano(); +const nano2: Transformer = cssnano({ + configFile: '/path/to/config', +}); +const nano3: Transformer = cssnano({ + preset: 'default', +}); +const nano4: Transformer = cssnano({ + preset: ['default', { + discardComments: { + removeAll: true, + }, + }], +}); diff --git a/types/cssnano/index.d.ts b/types/cssnano/index.d.ts new file mode 100644 index 0000000000..bf298f1854 --- /dev/null +++ b/types/cssnano/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for cssnano 4.0 +// Project: https://github.com/cssnano/cssnano +// Definitions by: Armando Meziat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { Plugin } from 'postcss'; + +declare namespace cssnano { + interface CssNanoOptions { + configFile?: string; + preset?: [string, object] | string; + } + + type CssNano = Plugin; +} + +declare const cssnano: cssnano.CssNano; +export = cssnano; diff --git a/types/cssnano/package.json b/types/cssnano/package.json new file mode 100644 index 0000000000..3c7b1f0f76 --- /dev/null +++ b/types/cssnano/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "5 - 7" + } +} diff --git a/types/cssnano/tsconfig.json b/types/cssnano/tsconfig.json new file mode 100644 index 0000000000..5667012b67 --- /dev/null +++ b/types/cssnano/tsconfig.json @@ -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", + "cssnano-tests.ts" + ] +} diff --git a/types/cssnano/tslint.json b/types/cssnano/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cssnano/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/d3-dispatch/d3-dispatch-tests.ts b/types/d3-dispatch/d3-dispatch-tests.ts index 4e8d2cfb31..b4f44ad4d2 100644 --- a/types/d3-dispatch/d3-dispatch-tests.ts +++ b/types/d3-dispatch/d3-dispatch-tests.ts @@ -47,12 +47,12 @@ undef = dispatch.on('unknown') as undefined; dispatch.on('bar', dispatch.on('bar')!); dispatch.call('foo'); -dispatch.call('foo', document.body); -dispatch.call('foo', document.body, { a: 3, b: 'test' }, 1); +dispatch.call('foo', document.body!); +dispatch.call('foo', document.body!, { a: 3, b: 'test' }, 1); dispatch.apply('bar'); -dispatch.apply('bar', document.body); -dispatch.apply('bar', document.body, [{ a: 3, b: 'test' }, 1]); +dispatch.apply('bar', document.body!); +dispatch.apply('bar', document.body!, [{ a: 3, b: 'test' }, 1]); dispatch.on('bar', null); diff --git a/types/d3-hierarchy/d3-hierarchy-tests.ts b/types/d3-hierarchy/d3-hierarchy-tests.ts index 65b1f5c392..b75b9fbbd0 100644 --- a/types/d3-hierarchy/d3-hierarchy-tests.ts +++ b/types/d3-hierarchy/d3-hierarchy-tests.ts @@ -189,6 +189,10 @@ stratificatorizer = d3Hierarchy.stratify(); // id(...) +stratificatorizer = stratificatorizer.id((d) => { + return d.name; // d is of type TabularHierarchyDatum +}); + stratificatorizer = stratificatorizer.id((d, i, data) => { console.log('Length of tabular array: ', data.length); console.log('Name of first entry in tabular array: ', data[0].name); // data of type Array @@ -199,6 +203,10 @@ idStringAccessor = stratificatorizer.id(); // parentId(...) +stratificatorizer = stratificatorizer.parentId((d) => { + return d.parentId; // d is of type TabularHierarchyDatum +}); + stratificatorizer = stratificatorizer.parentId((d, i, data) => { console.log('Length of tabular array: ', data.length); console.log('Name of first entry in tabular array: ', data[0].name); // data of type Array @@ -225,14 +233,12 @@ clusterLayout = d3Hierarchy.cluster(); // size() ---------------------------------------------------------------- -clusterLayout = clusterLayout.size(null); clusterLayout = clusterLayout.size([200, 200]); size = clusterLayout.size(); // nodeSize() ------------------------------------------------------------ -clusterLayout = clusterLayout.nodeSize(null); clusterLayout = clusterLayout.nodeSize([10, 10]); size = clusterLayout.nodeSize(); @@ -358,14 +364,12 @@ treeLayout = d3Hierarchy.tree(); // size() ---------------------------------------------------------------- -treeLayout = treeLayout.size(null); treeLayout = treeLayout.size([200, 200]); size = treeLayout.size(); // nodeSize() ------------------------------------------------------------ -treeLayout = treeLayout.nodeSize(null); treeLayout = treeLayout.nodeSize([10, 10]); size = treeLayout.nodeSize(); @@ -416,7 +420,6 @@ tilingFn = treemapLayout.tile(); // size() ---------------------------------------------------------------- -treemapLayout = treemapLayout.size(null); treemapLayout = treemapLayout.size([400, 200]); size = treemapLayout.size(); @@ -635,7 +638,6 @@ partitionLayout = d3Hierarchy.partition(); // size() ---------------------------------------------------------------- -partitionLayout = partitionLayout.size(null); partitionLayout = partitionLayout.size([400, 200]); size = partitionLayout.size(); @@ -674,7 +676,6 @@ packLayout = d3Hierarchy.pack(); // size() ---------------------------------------------------------------- -packLayout = packLayout.size(null); packLayout = packLayout.size([400, 400]); size = packLayout.size(); diff --git a/types/d3-hierarchy/index.d.ts b/types/d3-hierarchy/index.d.ts index 440a779217..bdb7b652d5 100644 --- a/types/d3-hierarchy/index.d.ts +++ b/types/d3-hierarchy/index.d.ts @@ -1,65 +1,208 @@ // Type definitions for D3JS d3-hierarchy module 1.1 // Project: https://github.com/d3/d3-hierarchy/ -// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov +// Definitions by: Tom Wanzek +// Alex Ford +// Boris Yankov +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.1.1 +// Last module patch version validated against: 1.1.6 // ----------------------------------------------------------------------- // Hierarchy // ----------------------------------------------------------------------- export interface HierarchyLink { + /** + * The source of the link. + */ source: HierarchyNode; + + /** + * The target of the link. + */ target: HierarchyNode; } export interface HierarchyNode { - data: Datum; - readonly depth: number; - readonly height: number; - parent: HierarchyNode | null; - children?: Array>; /** - * Aggregated numeric value as calculated by sum(value) or count(), - * if previously invoked. + * The associated data, as specified to the constructor. + */ + data: Datum; + + /** + * Zero for the root node, and increasing by one for each descendant generation. + */ + readonly depth: number; + + /** + * Zero for leaf nodes, and the greatest distance from any descendant leaf for internal nodes. + */ + readonly height: number; + + /** + * The parent node, or null for the root node. + */ + parent: this | null; + + /** + * An array of child nodes, if any; undefined for leaf nodes. + */ + children?: this[]; + + /** + * Aggregated numeric value as calculated by `sum(value)` or `count()`, if previously invoked. */ readonly value?: number; + /** - * Optional Node Id string set by StratifyOperator, if - * hierarchical data was created from tabular data using stratify() + * Optional node id string set by `StratifyOperator`, if hierarchical data was created from tabular data using stratify(). */ readonly id?: string; - ancestors(): Array>; - descendants(): Array>; - leaves(): Array>; - path(target: HierarchyNode): Array>; + + /** + * Returns the array of ancestors nodes, starting with this node, then followed by each parent up to the root. + */ + ancestors(): this[]; + + /** + * Returns the array of descendant nodes, starting with this node, then followed by each child in topological order. + */ + descendants(): this[]; + + /** + * Returns the array of leaf nodes in traversal order; leaves are nodes with no children. + */ + leaves(): this[]; + + /** + * Returns the shortest path through the hierarchy from this node to the specified target node. + * The path starts at this node, ascends to the least common ancestor of this node and the target node, and then descends to the target node. + * + * @param target The target node. + */ + path(target: this): this[]; + + /** + * Returns an array of links for this node, where each link is an object that defines source and target properties. + * The source of each link is the parent node, and the target is a child node. + */ links(): Array>; + + /** + * Evaluates the specified value function for this node and each descendant in post-order traversal, and returns this node. + * The `node.value` property of each node is set to the numeric value returned by the specified function plus the combined value of all descendants. + * + * @param value The value function is passed the node’s data, and must return a non-negative number. + */ sum(value: (d: Datum) => number): this; + + /** + * Computes the number of leaves under this node and assigns it to `node.value`, and similarly for every descendant of node. + * If this node is a leaf, its count is one. Returns this node. + */ count(): this; - sort(compare: (a: HierarchyNode, b: HierarchyNode) => number): this; - each(func: (node: HierarchyNode) => void): this; - eachAfter(func: (node: HierarchyNode) => void): this; - eachBefore(func: (node: HierarchyNode) => void): this; - copy(): HierarchyNode; + + /** + * Sorts the children of this node, if any, and each of this node’s descendants’ children, + * in pre-order traversal using the specified compare function, and returns this node. + * + * @param compare The compare function is passed two nodes a and b to compare. + * If a should be before b, the function must return a value less than zero; + * if b should be before a, the function must return a value greater than zero; + * otherwise, the relative order of a and b are not specified. See `array.sort` for more. + */ + sort(compare: (a: this, b: this) => number): this; + + /** + * Invokes the specified function for node and each descendant in breadth-first order, + * such that a given node is only visited if all nodes of lesser depth have already been visited, + * as well as all preceding nodes of the same depth. + * + * @param func The specified function is passed the current node. + */ + each(func: (node: this) => void): this; + + /** + * Invokes the specified function for node and each descendant in post-order traversal, + * such that a given node is only visited after all of its descendants have already been visited. + * + * @param func The specified function is passed the current node. + */ + eachAfter(func: (node: this) => void): this; + + /** + * Invokes the specified function for node and each descendant in pre-order traversal, + * such that a given node is only visited after all of its ancestors have already been visited. + * + * @param func The specified function is passed the current node. + */ + eachBefore(func: (node: this) => void): this; + + /** + * Return a deep copy of the subtree starting at this node. The returned deep copy shares the same data, however. + * The returned node is the root of a new tree; the returned node’s parent is always null and its depth is always zero. + */ + copy(): this; } +/** + * Constructs a root node from the specified hierarchical data. + * + * @param data The root specified data. + * @param children The specified children accessor function invoked for each datum, starting with the root data. + * Must return an array of data representing the children, and return null or undefined if the current datum has no children. + * If children is not specified, it defaults to: `(d) => d.children`. + */ export function hierarchy(data: Datum, children?: (d: Datum) => (Datum[] | null)): HierarchyNode; // ----------------------------------------------------------------------- // Stratify // ----------------------------------------------------------------------- -// TODO: Review the comment in the API documentation related to 'reserved properties': id, parentId, children. If this is referring to the element on node, it should be 'parent'? - export interface StratifyOperator { + /** + * Generates a new hierarchy from the specified tabular data. Each node in the returned object has a shallow copy of the properties + * from the corresponding data object, excluding the following reserved properties: id, parentId, children. + * + * @param data The root specified data. + * @throws Error on missing id, ambiguous id, cycle, multiple roots or no root. + */ (data: Datum[]): HierarchyNode; + + /** + * Returns the current id accessor, which defaults to: `(d) => d.id`. + */ id(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined); + /** + * Sets the id accessor to the given function. + * The id accessor is invoked for each element in the input data passed to the stratify operator. + * The returned string is then used to identify the node's relationships in conjunction with the parent id. + * For leaf nodes, the id may be undefined, null or the empty string; otherwise, the id must be unique. + * + * @param id The id accessor. + */ id(id: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this; + + /** + * Returns the current parent id accessor, which defaults to: `(d) => d.parentId`. + */ parentId(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined); + /** + * Sets the parent id accessor to the given function. + * The parent id accessor is invoked for each element in the input data passed to the stratify operator. + * The returned string is then used to identify the node's relationships in conjunction with the id. + * For the root node, the parent id should be undefined, null or the empty string. + * There must be exactly one root node in the input data, and no circular relationships. + * + * @param parentId The parent id accessor. + */ parentId(parentId: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this; } +/** + * Constructs a new stratify operator with the default settings. + */ export function stratify(): StratifyOperator; // ----------------------------------------------------------------------- @@ -67,52 +210,86 @@ export function stratify(): StratifyOperator; // ----------------------------------------------------------------------- export interface HierarchyPointLink { + /** + * The source of the link. + */ source: HierarchyPointNode; + + /** + * The target of the link. + */ target: HierarchyPointNode; } -export interface HierarchyPointNode { +export interface HierarchyPointNode extends HierarchyNode { + /** + * The x-coordinate of the node. + */ x: number; + + /** + * The y-coordinate of the node. + */ y: number; - data: Datum; - readonly depth: number; - readonly height: number; - parent: HierarchyPointNode | null; - children?: Array>; + /** - * Aggregated numeric value as calculated by sum(value) or count(), - * if previously invoked. + * Returns an array of links for this node, where each link is an object that defines source and target properties. + * The source of each link is the parent node, and the target is a child node. */ - readonly value?: number; - /** - * Optional Node Id string set by StratifyOperator, if - * hierarchical data was created from tabular data using stratify() - */ - readonly id?: string; - ancestors(): Array>; - descendants(): Array>; - leaves(): Array>; - path(target: HierarchyPointNode): Array>; links(): Array>; - sum(value: (d: Datum) => number): this; - count(): this; - sort(compare: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this; - each(func: (node: HierarchyPointNode) => void): this; - eachAfter(func: (node: HierarchyPointNode) => void): this; - eachBefore(func: (node: HierarchyPointNode) => void): this; - copy(): HierarchyPointNode; } export interface ClusterLayout { + /** + * Lays out the specified root hierarchy. + * You may want to call `root.sort` before passing the hierarchy to the cluster layout. + * + * @param root The specified root hierarchy. + */ (root: HierarchyNode): HierarchyPointNode; + + /** + * Returns the current layout size, which defaults to [1, 1]. A layout size of null indicates that a node size will be used instead. + */ size(): [number, number] | null; + /** + * Sets this cluster layout’s size to the specified [width, height] array and returns the cluster layout. + * The size represent an arbitrary coordinate system; for example, to produce a radial layout, + * a size of [360, radius] corresponds to a breadth of 360° and a depth of radius. + * + * @param size The specified two-element size array. + */ size(size: [number, number]): this; + + /** + * Returns the current node size, which defaults to null. A node size of null indicates that a layout size will be used instead. + */ nodeSize(): [number, number] | null; + /** + * Sets this cluster layout’s node size to the specified [width, height] array and returns this cluster layout. + * When a node size is specified, the root node is always positioned at <0, 0>. + * + * @param size The specified two-element size array. + */ nodeSize(size: [number, number]): this; + + /** + * Returns the current separation accessor, which defaults to: `(a, b) => a.parent == b.parent ? 1 : 2`. + */ separation(): (a: HierarchyPointNode, b: HierarchyPointNode) => number; + /** + * Sets the separation accessor to the specified function and returns this cluster layout. + * The separation accessor is used to separate neighboring leaves. + * + * @param separation The separation function is passed two leaves a and b, and must return the desired separation. + * The nodes are typically siblings, though the nodes may be more distantly related if the layout decides to place such nodes adjacent. + */ separation(separation: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this; } +/** + * Creates a new cluster layout with default settings. + */ export function cluster(): ClusterLayout; // ----------------------------------------------------------------------- @@ -120,15 +297,56 @@ export function cluster(): ClusterLayout; // ----------------------------------------------------------------------- export interface TreeLayout { + /** + * Lays out the specified root hierarchy. + * You may want to call `root.sort` before passing the hierarchy to the tree layout. + * + * @param root The specified root hierarchy. + */ (root: HierarchyNode): HierarchyPointNode; + + /** + * Returns the current layout size, which defaults to [1, 1]. A layout size of null indicates that a node size will be used instead. + */ size(): [number, number] | null; + /** + * Sets this tree layout’s size to the specified [width, height] array and returns the tree layout. + * The size represent an arbitrary coordinate system; for example, to produce a radial layout, + * a size of [360, radius] corresponds to a breadth of 360° and a depth of radius. + * + * @param size The specified two-element size array. + */ size(size: [number, number]): this; + + /** + * Returns the current node size, which defaults to null. A node size of null indicates that a layout size will be used instead. + */ nodeSize(): [number, number] | null; + /** + * Sets this tree layout’s node size to the specified [width, height] array and returns this tree layout. + * When a node size is specified, the root node is always positioned at <0, 0>. + * + * @param size The specified two-element size array. + */ nodeSize(size: [number, number]): this; + + /** + * Returns the current separation accessor, which defaults to: `(a, b) => a.parent == b.parent ? 1 : 2`. + */ separation(): (a: HierarchyPointNode, b: HierarchyPointNode) => number; + /** + * Sets the separation accessor to the specified function and returns this tree layout. + * The separation accessor is used to separate neighboring nodes. + * + * @param separation The separation function is passed two nodes a and b, and must return the desired separation. + * The nodes are typically siblings, though the nodes may be more distantly related if the layout decides to place such nodes adjacent. + */ separation(separation: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this; } +/** + * Creates a new tree layout with default settings. + */ export function tree(): TreeLayout; // ----------------------------------------------------------------------- @@ -136,91 +354,283 @@ export function tree(): TreeLayout; // ----------------------------------------------------------------------- export interface HierarchyRectangularLink { + /** + * The source of the link. + */ source: HierarchyRectangularNode; + + /** + * The target of the link. + */ target: HierarchyRectangularNode; } -export interface HierarchyRectangularNode { +export interface HierarchyRectangularNode extends HierarchyNode { + /** + * The left edge of the rectangle. + */ x0: number; + + /** + * The top edge of the rectangle + */ y0: number; + + /** + * The right edge of the rectangle. + */ x1: number; + + /** + * The bottom edge of the rectangle. + */ y1: number; - data: Datum; - readonly depth: number; - readonly height: number; - parent: HierarchyRectangularNode | null; - children?: Array>; + /** - * Aggregated numeric value as calculated by sum(value) or count(), - * if previously invoked. + * Returns an array of links for this node, where each link is an object that defines source and target properties. + * The source of each link is the parent node, and the target is a child node. */ - readonly value?: number; - /** - * Optional Node Id string set by StratifyOperator, if - * hierarchical data was created from tabular data using stratify() - */ - readonly id?: string; - ancestors(): Array>; - descendants(): Array>; - leaves(): Array>; - path(target: HierarchyRectangularNode): Array>; links(): Array>; - sum(value: (d: Datum) => number): this; - count(): this; - sort(compare: (a: HierarchyRectangularNode, b: HierarchyRectangularNode) => number): this; - each(func: (node: HierarchyRectangularNode) => void): this; - eachAfter(func: (node: HierarchyRectangularNode) => void): this; - eachBefore(func: (node: HierarchyRectangularNode) => void): this; - copy(): HierarchyRectangularNode; } export interface TreemapLayout { + /** + * Lays out the specified root hierarchy. + * You must call `root.sum` before passing the hierarchy to the treemap layout. + * You probably also want to call `root.sort` to order the hierarchy before computing the layout. + * + * @param root The specified root hierarchy. + */ (root: HierarchyNode): HierarchyRectangularNode; + + /** + * Returns the current tiling method, which defaults to `d3.treemapSquarify` with the golden ratio. + */ tile(): (node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number) => void; + /** + * Sets the tiling method to the specified function and returns this treemap layout. + * + * @param tile The specified tiling function. + */ tile(tile: (node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number) => void): this; + + /** + * Returns the current size, which defaults to [1, 1]. + */ size(): [number, number]; + /** + * Sets this treemap layout’s size to the specified [width, height] array and returns this treemap layout. + * + * @param size The specified two-element size array. + */ size(size: [number, number]): this; + + /** + * Returns the current rounding state, which defaults to false. + */ round(): boolean; + /** + * Enables or disables rounding according to the given boolean and returns this treemap layout. + * + * @param round The specified boolean flag. + */ round(round: boolean): this; + + /** + * Returns the current inner padding function. + */ padding(): (node: HierarchyRectangularNode) => number; + /** + * Sets the inner and outer padding to the specified number and returns this treemap layout. + * + * @param padding The specified padding value. + */ padding(padding: number): this; + /** + * Sets the inner and outer padding to the specified function and returns this treemap layout. + * + * @param padding The specified padding function. + */ padding(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current inner padding function, which defaults to the constant zero. + */ paddingInner(): (node: HierarchyRectangularNode) => number; + /** + * Sets the inner padding to the specified number and returns this treemap layout. + * The inner padding is used to separate a node’s adjacent children. + * + * @param padding The specified inner padding value. + */ paddingInner(padding: number): this; + /** + * Sets the inner padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The inner padding is used to separate a node’s adjacent children. + * + * @param padding The specified inner padding function. + */ paddingInner(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current top padding function. + */ paddingOuter(): (node: HierarchyRectangularNode) => number; + /** + * Sets the top, right, bottom and left padding to the specified function and returns this treemap layout. + * + * @param padding The specified padding outer value. + */ paddingOuter(padding: number): this; + /** + * Sets the top, right, bottom and left padding to the specified function and returns this treemap layout. + * + * @param padding The specified padding outer function. + */ paddingOuter(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current top padding function, which defaults to the constant zero. + */ paddingTop(): (node: HierarchyRectangularNode) => number; + /** + * Sets the top padding to the specified number and returns this treemap layout. + * The top padding is used to separate the top edge of a node from its children. + * + * @param padding The specified top padding value. + */ paddingTop(padding: number): this; + /** + * Sets the top padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The top padding is used to separate the top edge of a node from its children. + * + * @param padding The specified top padding function. + */ paddingTop(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current right padding function, which defaults to the constant zero. + */ paddingRight(): (node: HierarchyRectangularNode) => number; + /** + * Sets the right padding to the specified number and returns this treemap layout. + * The right padding is used to separate the right edge of a node from its children. + * + * @param padding The specified right padding value. + */ paddingRight(padding: number): this; + /** + * Sets the right padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The right padding is used to separate the right edge of a node from its children. + * + * @param padding The specified right padding function. + */ paddingRight(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current bottom padding function, which defaults to the constant zero. + */ paddingBottom(): (node: HierarchyRectangularNode) => number; + /** + * Sets the bottom padding to the specified number and returns this treemap layout. + * The bottom padding is used to separate the bottom edge of a node from its children. + * + * @param padding The specified bottom padding value. + */ paddingBottom(padding: number): this; + /** + * Sets the bottom padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The bottom padding is used to separate the bottom edge of a node from its children. + * + * @param padding The specified bottom padding function. + */ paddingBottom(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current left padding function, which defaults to the constant zero. + */ paddingLeft(): (node: HierarchyRectangularNode) => number; + /** + * Sets the left padding to the specified number and returns this treemap layout. + * The left padding is used to separate the left edge of a node from its children. + * + * @param padding The specified left padding value. + */ paddingLeft(padding: number): this; + /** + * Sets the left padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The left padding is used to separate the left edge of a node from its children. + * + * @param padding The specified left padding function. + */ paddingLeft(padding: (node: HierarchyRectangularNode) => number): this; } +/** + * Creates a new treemap layout with default settings. + */ export function treemap(): TreemapLayout; -// Tiling functions --------------------------------------------------------------------------------- +// Tiling functions ----------------------------------------------------------------------- +/** + * Recursively partitions the specified nodes into an approximately-balanced binary tree, + * choosing horizontal partitioning for wide rectangles and vertical partitioning for tall rectangles. + */ export function treemapBinary(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void; + +/** + * Divides the rectangular area specified by x0, y0, x1, y1 horizontally according the value of each of the specified node’s children. + * The children are positioned in order, starting with the left edge (x0) of the given rectangle. + * If the sum of the children’s values is less than the specified node’s value (i.e., if the specified node has a non-zero internal value), + * the remaining empty space will be positioned on the right edge (x1) of the given rectangle. + */ export function treemapDice(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void; + +/** + * Divides the rectangular area specified by x0, y0, x1, y1 vertically according the value of each of the specified node’s children. + * The children are positioned in order, starting with the top edge (y0) of the given rectangle. + * If the sum of the children’s values is less than the specified node’s value (i.e., if the specified node has a non-zero internal value), + * the remaining empty space will be positioned on the bottom edge (y1) of the given rectangle. + */ export function treemapSlice(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void; + +/** + * If the specified node has odd depth, delegates to treemapSlice; otherwise delegates to treemapDice. + */ export function treemapSliceDice(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void; // TODO: Test Factory code export interface RatioSquarifyTilingFactory { (node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void; + + /** + * Specifies the desired aspect ratio of the generated rectangles. + * Note that the orientation of the generated rectangles (tall or wide) is not implied by the ratio. + * Furthermore, the rectangles ratio are not guaranteed to have the exact specified aspect ratio. + * If not specified, the aspect ratio defaults to the golden ratio, φ = (1 + sqrt(5)) / 2, per Kong et al. + * + * @param ratio The specified ratio value greater than or equal to one. + */ ratio(ratio: number): RatioSquarifyTilingFactory; } +/** + * Implements the squarified treemap algorithm by Bruls et al., which seeks to produce rectangles of a given aspect ratio. + */ export const treemapSquarify: RatioSquarifyTilingFactory; + +/** + * Like `d3.treemapSquarify`, except preserves the topology (node adjacencies) of the previous layout computed by `d3.treemapResquarify`, + * if there is one and it used the same target aspect ratio. This tiling method is good for animating changes to treemaps because + * it only changes node sizes and not their relative positions, thus avoiding distracting shuffling and occlusion. + * The downside of a stable update, however, is a suboptimal layout for subsequent updates: only the first layout uses the Bruls et al. squarified algorithm. + */ export const treemapResquarify: RatioSquarifyTilingFactory; // ----------------------------------------------------------------------- @@ -228,15 +638,53 @@ export const treemapResquarify: RatioSquarifyTilingFactory; // ----------------------------------------------------------------------- export interface PartitionLayout { + /** + * Lays out the specified root hierarchy. + * You must call `root.sum` before passing the hierarchy to the partition layout. + * You probably also want to call `root.sort` to order the hierarchy before computing the layout. + * + * @param root The specified root hierarchy. + */ (root: HierarchyNode): HierarchyRectangularNode; + + /** + * Returns the current size, which defaults to [1, 1]. + */ size(): [number, number]; + /** + * Sets this partition layout’s size to the specified [width, height] array and returns this partition layout. + * + * @param size The specified two-element size array. + */ size(size: [number, number]): this; + + /** + * Returns the current rounding state, which defaults to false. + */ round(): boolean; + /** + * Enables or disables rounding according to the given boolean and returns this partition layout. + * + * @param round The specified boolean flag. + */ round(round: boolean): this; + + /** + * Returns the current padding, which defaults to zero. + */ padding(): number; + /** + * Sets the padding to the specified number and returns this partition layout. + * The padding is used to separate a node’s adjacent children. + * + * @param padding The specified padding value. + */ padding(padding: number): this; } +/** + * Creates a new partition layout with the default settings. + */ export function partition(): PartitionLayout; // ----------------------------------------------------------------------- @@ -244,54 +692,110 @@ export function partition(): PartitionLayout; // ----------------------------------------------------------------------- export interface HierarchyCircularLink { + /** + * The source of the link. + */ source: HierarchyCircularNode; + + /** + * The target of the link. + */ target: HierarchyCircularNode; } -export interface HierarchyCircularNode { +export interface HierarchyCircularNode extends HierarchyNode { + /** + * The x-coordinate of the circle’s center. + */ x: number; + + /** + * The y-coordinate of the circle’s center. + */ y: number; + + /** + * The radius of the circle. + */ r: number; - data: Datum; - readonly depth: number; - readonly height: number; - parent: HierarchyCircularNode | null; - children?: Array>; + /** - * Aggregated numeric value as calculated by sum(value) or count(), - * if previously invoked. + * Returns an array of links for this node, where each link is an object that defines source and target properties. + * The source of each link is the parent node, and the target is a child node. */ - readonly value?: number; - /** - * Optional Node Id string set by StratifyOperator, if - * hierarchical data was created from tabular data using stratify() - */ - readonly id?: string; - ancestors(): Array>; - descendants(): Array>; - leaves(): Array>; - path(target: HierarchyCircularNode): Array>; links(): Array>; - sum(value: (d: Datum) => number): this; - count(): this; - sort(compare: (a: HierarchyCircularNode, b: HierarchyCircularNode) => number): this; - each(func: (node: HierarchyCircularNode) => void): this; - eachAfter(func: (node: HierarchyCircularNode) => void): this; - eachBefore(func: (node: HierarchyCircularNode) => void): this; - copy(): HierarchyCircularNode; } export interface PackLayout { + /** + * Lays out the specified root hierarchy. + * You must call `root.sum` before passing the hierarchy to the pack layout. + * You probably also want to call `root.sort` to order the hierarchy before computing the layout. + * + * @param root The specified root hierarchy. + */ (root: HierarchyNode): HierarchyCircularNode; + + /** + * Returns the current radius accessor, which defaults to null. + */ radius(): null | ((node: HierarchyCircularNode) => number); + /** + * Sets the pack layout’s radius accessor to the specified function and returns this pack layout. + * If the radius accessor is null, the radius of each leaf circle is derived from the leaf `node.value` (computed by `node.sum`); + * the radii are then scaled proportionally to fit the layout size. + * If the radius accessor is not null, the radius of each leaf circle is specified exactly by the function. + * + * @param radius The specified radius accessor. + */ radius(radius: (node: HierarchyCircularNode) => number): this; + + /** + * Returns the current size, which defaults to [1, 1]. + */ size(): [number, number]; + /** + * Sets this pack layout’s size to the specified [width, height] array and returns this pack layout. + * + * @param size The specified two-element size array. + */ size(size: [number, number]): this; + + /** + * Returns the current padding accessor, which defaults to the constant zero. + */ padding(): (node: HierarchyCircularNode) => number; + /** + * Sets this pack layout’s padding accessor to the specified number and returns this pack layout. + * Returns the current padding accessor, which defaults to the constant zero. + * + * When siblings are packed, tangent siblings will be separated by approximately the specified padding; + * the enclosing parent circle will also be separated from its children by approximately the specified padding. + * If an explicit radius is not specified, the padding is approximate because a two-pass algorithm + * is needed to fit within the layout size: the circles are first packed without padding; + * a scaling factor is computed and applied to the specified padding; and lastly the circles are re-packed with padding. + * + * @param padding The specified padding value. + */ padding(padding: number): this; + /** + * Sets this pack layout’s padding accessor to the specified function and returns this pack layout. + * Returns the current padding accessor, which defaults to the constant zero. + * + * When siblings are packed, tangent siblings will be separated by approximately the specified padding; + * the enclosing parent circle will also be separated from its children by approximately the specified padding. + * If an explicit radius is not specified, the padding is approximate because a two-pass algorithm + * is needed to fit within the layout size: the circles are first packed without padding; + * a scaling factor is computed and applied to the specified padding; and lastly the circles are re-packed with padding. + * + * @param padding The specified padding function. + */ padding(padding: (node: HierarchyCircularNode) => number): this; } +/** + * Creates a new pack layout with the default settings. + */ export function pack(): PackLayout; // ----------------------------------------------------------------------- @@ -299,8 +803,19 @@ export function pack(): PackLayout; // ----------------------------------------------------------------------- export interface PackCircle { + /** + * The radius of the circle. + */ r: number; + + /** + * The x-coordinate of the circle’s center. + */ x?: number; + + /** + * The y-coordinate of the circle’s center. + */ y?: number; } @@ -309,6 +824,19 @@ export interface PackCircle { // For invocation of packEnclose the x and y coordinates are mandatory. It seems easier to just comment // on the mandatory nature, then to create separate interfaces and having to deal with recasting. +/** + * Packs the specified array of circles, each of which must have a `circle.r` property specifying the circle’s radius. + * The circles are positioned according to the front-chain packing algorithm by Wang et al. + * + * @param circles The specified array of circles to pack. + */ export function packSiblings(circles: Datum[]): Datum[]; +/** + * Computes the smallest circle that encloses the specified array of circles, each of which must have + * a `circle.r` property specifying the circle’s radius, and `circle.x` and `circle.y` properties specifying the circle’s center. + * The enclosing circle is computed using the Matoušek-Sharir-Welzl algorithm. (See also Apollonius’ Problem.) + * + * @param circles The specified array of circles to pack. + */ export function packEnclose(circles: Datum[]): { r: number, x: number, y: number }; diff --git a/types/deku/deku-tests.ts b/types/deku/deku-tests.ts index d123c7b8f7..d0467adead 100644 --- a/types/deku/deku-tests.ts +++ b/types/deku/deku-tests.ts @@ -24,7 +24,7 @@ }) } - let render = createApp(document.body) + let render = createApp(document.body!) function main(state: any){ let vnode = view(state, (action: any) => main({ count: 0 })) @@ -43,7 +43,7 @@ return element('div', { class: `size-${ props.size }` }) } - const render = createApp(document.body) + const render = createApp(document.body!) render(element(App, { size: 'small' })) @@ -82,11 +82,11 @@ (function (){ const { createApp, element } = deku - let render: Function = createApp(document.body) + let render: Function = createApp(document.body!) render(element('div')) - render = createApp(document.body, (action: any) => { + render = createApp(document.body!, (action: any) => { render(element('div')) }) diff --git a/types/detect-node/detect-node-tests.ts b/types/detect-node/detect-node-tests.ts new file mode 100644 index 0000000000..01a81a356b --- /dev/null +++ b/types/detect-node/detect-node-tests.ts @@ -0,0 +1,3 @@ +import isNode = require("detect-node"); + +isNode; diff --git a/types/detect-node/index.d.ts b/types/detect-node/index.d.ts new file mode 100644 index 0000000000..38fd280f1e --- /dev/null +++ b/types/detect-node/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for detect-node 2.0 +// Project: https://github.com/iliakan/detect-node +// Definitions by: Leonid Logvinov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +declare const isNode: boolean; +export = isNode; diff --git a/types/detect-node/tsconfig.json b/types/detect-node/tsconfig.json new file mode 100644 index 0000000000..e853bcf92c --- /dev/null +++ b/types/detect-node/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "detect-node-tests.ts"] +} diff --git a/types/detect-node/tslint.json b/types/detect-node/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/detect-node/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/downloadjs/downloadjs-tests.ts b/types/downloadjs/downloadjs-tests.ts index 00bb5395ef..da110af46d 100644 --- a/types/downloadjs/downloadjs-tests.ts +++ b/types/downloadjs/downloadjs-tests.ts @@ -7,6 +7,6 @@ download(new Blob(['hello world']), 'dlTextBlob.txt', 'text/plain'); download('/robots.txt'); -download(document.documentElement.outerHTML, 'dlHTML.html', 'text/html'); +download(document.documentElement!.outerHTML, 'dlHTML.html', 'text/html'); download(new Blob(['hello world'.bold()]), 'dlHtmlBlob.html', 'text/html'); download('/diff6.png'); diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index 3583889a74..93babaa0a7 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -328,11 +328,11 @@ declare module 'ember' { */ resolveRegistration(fullName: string): Function; /** - * Registers a factory that can be used for dependency injection (with + * Registers a factory or value that can be used for dependency injection (with * `inject`) or for service lookup. Each factory is registered with * a full name including two parts: `type:name`. */ - register(fullName: string, factory: Function, options?: { singleton?: boolean, instantiate?: boolean }): any; + register(fullName: string, factory: any, options?: { singleton?: boolean, instantiate?: boolean }): any; /** * Unregister a factory. */ @@ -3372,7 +3372,48 @@ declare module 'ember' { /** * The Router service is the public API that provides component/view layer access to the router. */ - class RouterService extends Ember.Service { + export class RouterService extends Ember.Service { + // + /** + Name of the current route. + This property represent the logical name of the route, + which is comma separated. + For the following router: + ```app/router.js + Router.map(function() { + this.route('about'); + this.route('blog', function () { + this.route('post', { path: ':post_id' }); + }); + }); + ``` + It will return: + * `index` when you visit `/` + * `about` when you visit `/about` + * `blog.index` when you visit `/blog` + * `blog.post` when you visit `/blog/some-post-id` + */ + readonly currentRouteName: string; + // + /** + Current URL for the application. + This property represent the URL path for this route. + For the following router: + ```app/router.js + Router.map(function() { + this.route('about'); + this.route('blog', function () { + this.route('post', { path: ':post_id' }); + }); + }); + ``` + It will return: + * `/` when you visit `/` + * `/about` when you visit `/about` + * `/blog` when you visit `/blog` + * `/blog/some-post-id` when you visit `/blog/some-post-id` + */ + readonly currentURL: string; // /** * Determines whether a route is active. @@ -3776,6 +3817,11 @@ declare module '@ember/routing/router' { export default class EmberRouter extends Ember.Router { } } +declare module '@ember/routing/router-service' { + import { RouterService } from 'ember'; + export default class extends RouterService { } +} + declare module '@ember/runloop' { import Ember from 'ember'; export const begin: typeof Ember.run.begin; diff --git a/types/ember/test/application-instance.ts b/types/ember/test/application-instance.ts index 9881e4815a..9ae22e5f26 100644 --- a/types/ember/test/application-instance.ts +++ b/types/ember/test/application-instance.ts @@ -1,4 +1,5 @@ import ApplicationInstance from '@ember/application/instance'; +import hbs from 'htmlbars-inline-precompile'; const appInstance = ApplicationInstance.create(); appInstance.register('some:injection', class Foo {}); @@ -11,6 +12,8 @@ appInstance.register('some:injection', class Foo {}, { instantiate: false, }); +appInstance.register('templates:foo/bar', hbs`

Hello World

`); + appInstance.register('some:injection', class Foo {}, { singleton: false, instantiate: true, diff --git a/types/ember/test/router.ts b/types/ember/test/router.ts index ff5f4c554f..760e9ed5bc 100755 --- a/types/ember/test/router.ts +++ b/types/ember/test/router.ts @@ -1,4 +1,5 @@ import Ember from 'ember'; +import { assertType } from './lib/assert'; const AppRouter = Ember.Router.extend({ }); @@ -25,6 +26,12 @@ AppRouter.map(function() { const RouterServiceConsumer = Ember.Service.extend({ router: Ember.inject.service('router'), + currentRouteName() { + const x: string = Ember.get(this, 'router').currentRouteName; + }, + currentURL() { + const x: string = Ember.get(this, 'router').currentURL; + }, transitionWithoutModel() { Ember.get(this, 'router') .transitionTo('some-route'); diff --git a/types/error-subclass/error-subclass-tests.ts b/types/error-subclass/error-subclass-tests.ts new file mode 100644 index 0000000000..9944bba159 --- /dev/null +++ b/types/error-subclass/error-subclass-tests.ts @@ -0,0 +1,7 @@ +import ErrorSubclass from 'error-subclass'; + +class ExampleError extends ErrorSubclass { + static displayName = 'ExampleError'; +} + +throw new ExampleError('Something went wrong!'); diff --git a/types/error-subclass/index.d.ts b/types/error-subclass/index.d.ts new file mode 100644 index 0000000000..55add2c057 --- /dev/null +++ b/types/error-subclass/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for error-subclass 2.2 +// Project: https://github.com/spudly/error-subclass#readme +// Definitions by: Fitbit +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default class ErrorSubclass extends Error { + static displayName: string; +} diff --git a/types/error-subclass/tsconfig.json b/types/error-subclass/tsconfig.json new file mode 100644 index 0000000000..1574ebeea2 --- /dev/null +++ b/types/error-subclass/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "error-subclass-tests.ts" + ] +} diff --git a/types/error-subclass/tslint.json b/types/error-subclass/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/error-subclass/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/espruino/espruino-tests.ts b/types/espruino/espruino-tests.ts index 32f044796d..c1bafc9048 100644 --- a/types/espruino/espruino-tests.ts +++ b/types/espruino/espruino-tests.ts @@ -10,5 +10,8 @@ wifi.startAP('ssid', { password: 'pass', authMode: 'wpa_wpa2' }, err => { console.log("created"); }); +digitalWrite(D2, false); +digitalWrite(D2, true); + I2C1.setup({ scl: D4, sda: D0 }); Serial2.setup(9600, { rx: D16, tx: D17 }); diff --git a/types/espruino/index.d.ts b/types/espruino/index.d.ts index 61cf72f173..cb6151e85a 100644 --- a/types/espruino/index.d.ts +++ b/types/espruino/index.d.ts @@ -3600,7 +3600,7 @@ declare function digitalPulse(pin: Pin, value: boolean, time: any): void; * @param value * @url http://www.espruino.com/Reference#l__global_digitalWrite */ -declare function digitalWrite(pin: Pin, value: number): void; +declare function digitalWrite(pin: Pin, value: number | boolean): void; /** *

Get the digital value of the given pin.

diff --git a/types/eth-lightwallet/eth-lightwallet-tests.ts b/types/eth-lightwallet/eth-lightwallet-tests.ts new file mode 100644 index 0000000000..4907c73cbf --- /dev/null +++ b/types/eth-lightwallet/eth-lightwallet-tests.ts @@ -0,0 +1,3 @@ +import * as lw from "eth-lightwallet"; + +lw.keystore.createVault({}); diff --git a/types/eth-lightwallet/index.d.ts b/types/eth-lightwallet/index.d.ts new file mode 100644 index 0000000000..f55e71884e --- /dev/null +++ b/types/eth-lightwallet/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for eth-lightwallet 3.0 +// Project: https://github.com/ConsenSys/eth-lightwallet#readme +// Definitions by: Leonid Logvinov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +export interface ECSignatureBuffer { + v: number; + r: Buffer; + s: Buffer; +} +export namespace signing { + function signTx( + keystore: keystore, + pwDerivedKey: Uint8Array, + rawTx: string, + signingAddress: string + ): string; + function signMsg( + keystore: keystore, + pwDerivedKey: Uint8Array, + rawMsg: string, + signingAddress: string + ): ECSignatureBuffer; + function signMsgHash( + keystore: keystore, + pwDerivedKey: Uint8Array, + msgHash: string, + signingAddress: string + ): ECSignatureBuffer; + function concatSig(signature: any): string; +} + +export class keystore { + static createVault( + options: any, + callback?: (error: Error, keystore: keystore) => void + ): keystore; + static generateRandomSeed(): string; + static isSeedValid(seed: string): boolean; + static deserialize(keystore: string): keystore; + serialize(): string; + keyFromPassword( + password: string, + callback?: (error: Error, pwDerivedKey: Uint8Array) => void + ): Uint8Array; + isDerivedKeyCorrect(pwDerivedKey: Uint8Array): boolean; + generateNewAddress( + pwDerivedKey: Uint8Array, + numberOfAddresses: number + ): void; + getSeed(pwDerivedKey: Uint8Array): string; + exportPrivateKey(address: string, pwDerivedKey: Uint8Array): string; + getAddresses(): string[]; +} + +export interface VaultOptions { + password: string; + seedPhrase: string; + salt?: string; + hdPathString: string; +} diff --git a/types/eth-lightwallet/tsconfig.json b/types/eth-lightwallet/tsconfig.json new file mode 100644 index 0000000000..80eab8563a --- /dev/null +++ b/types/eth-lightwallet/tsconfig.json @@ -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", + "eth-lightwallet-tests.ts" + ] +} diff --git a/types/eth-lightwallet/tslint.json b/types/eth-lightwallet/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/eth-lightwallet/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/figlet/figlet-tests.ts b/types/figlet/figlet-tests.ts new file mode 100644 index 0000000000..676fb9003f --- /dev/null +++ b/types/figlet/figlet-tests.ts @@ -0,0 +1,95 @@ +import figlet = require('figlet'); + +figlet('abc', (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +figlet('My World', '1Row', (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +// $ExpectError +figlet('fweGWEPewfe', 'What is the font? I cannot get it'); +// $ExpectError +figlet('qweoqw'); +// $ExpectError +figlet('qweoqw', '1Row'); +// $ExpectError +figlet('qweoqw', '1Row', undefined as any, undefined as any); + +figlet.text('tokiyo tomare', (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +figlet.text('Hi', 'Flower Power', (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +figlet.text('Annyeong', { + font: 'Fun Face', + horizontalLayout: 'full', + verticalLayout: 'fitted', +}, (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +figlet.text('Oreehe', { + font: 'Fun Face', + // $ExpectError + value: 'abc', +}, undefined as any); +// $ExpectError +figlet.text('It cannot make sense'); + +// $ExpectType string +figlet.textSync('test text'); +// $ExpectType string +figlet.textSync('text desu', 'Fuzzy'); +// $ExpectType string +figlet.textSync('oho', { + font: 'Invita', +}); +// $ExpectError +figlet.textSync(); + +figlet.metadata('JS Block Letters', (err, fontOptions, headerComment) => { + // $ExpectType Error | null + err; + // $ExpectType FontOptions | undefined + fontOptions; + // $ExpectType string | undefined + headerComment; +}); +// $ExpectError +figlet.metadata('This is random font name which cannot make sense', undefined as any); +// $ExpectError +figlet.metadata('Alligator', undefined as any, undefined as any); + +// $ExpectType Defaults +figlet.defaults(); +// $ExpectType Defaults +figlet.defaults({}); +// $ExpectType Defaults +figlet.defaults({ + font: 'Patorjk\'s Cheese' +}); + +figlet.fonts((err, fonts) => { + // $ExpectType Error | null + err; + // $ExpectType Fonts[] | undefined + fonts; +}); + +// $ExpectType Fonts[] +figlet.fontsSync(); diff --git a/types/figlet/index.d.ts b/types/figlet/index.d.ts new file mode 100644 index 0000000000..07bb706066 --- /dev/null +++ b/types/figlet/index.d.ts @@ -0,0 +1,406 @@ +// Type definitions for figlet 1.2 +// Project: https://github.com/patorjk/figlet.js +// Definitions by: Junyoung Clare Jang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.1 + +declare namespace figlet { + type Fonts = + | '1Row' + | '3-D' + | '3D Diagonal' + | '3D-ASCII' + | '3x5' + | '4Max' + | '5 Line Oblique' + | 'AMC 3 Line' + | 'AMC 3 Liv1' + | 'AMC AAA01' + | 'AMC Neko' + | 'AMC Razor' + | 'AMC Razor2' + | 'AMC Slash' + | 'AMC Slider' + | 'AMC Thin' + | 'AMC Tubes' + | 'AMC Untitled' + | 'ANSI Shadow' + | 'ASCII New Roman' + | 'Acrobatic' + | 'Alligator' + | 'Alligator2' + | 'Alpha' + | 'Alphabet' + | 'Arrows' + | 'Avatar' + | 'B1FF' + | 'B1FF' + | 'Banner' + | 'Banner3-D' + | 'Banner3' + | 'Banner4' + | 'Barbwire' + | 'Basic' + | 'Bear' + | 'Bell' + | 'Benjamin' + | 'Big Chief' + | 'Big Money-ne' + | 'Big Money-nw' + | 'Big Money-se' + | 'Big Money-sw' + | 'Big' + | 'Bigfig' + | 'Binary' + | 'Block' + | 'Blocks' + | 'Bloody' + | 'Bolger' + | 'Braced' + | 'Bright' + | 'Broadway KB' + | 'Broadway' + | 'Bubble' + | 'Bulbhead' + | 'Caligraphy' + | 'Caligraphy2' + | 'Calvin S' + | 'Cards' + | 'Catwalk' + | 'Chiseled' + | 'Chunky' + | 'Coinstak' + | 'Cola' + | 'Colossal' + | 'Computer' + | 'Contessa' + | 'Contrast' + | 'Cosmike' + | 'Crawford' + | 'Crawford2' + | 'Crazy' + | 'Cricket' + | 'Cursive' + | 'Cyberlarge' + | 'Cybermedium' + | 'Cybersmall' + | 'Cygnet' + | 'DANC4' + | 'DOS Rebel' + | 'DWhistled' + | 'Dancing Font' + | 'Decimal' + | 'Def Leppard' + | 'Delta Corps Priest 1' + | 'Diamond' + | 'Diet Cola' + | 'Digital' + | 'Doh' + | 'Doom' + | 'Dot Matrix' + | 'Double Shorts' + | 'Double' + | 'Dr Pepper' + | 'Efti Chess' + | 'Efti Font' + | 'Efti Italic' + | 'Efti Piti' + | 'Efti Robot' + | 'Efti Wall' + | 'Efti Water' + | 'Electronic' + | 'Elite' + | 'Epic' + | 'Fender' + | 'Filter' + | 'Fire Font-k' + | 'Fire Font-s' + | 'Flipped' + | 'Flower Power' + | 'Four Tops' + | 'Fraktur' + | 'Fun Face' + | 'Fun Faces' + | 'Fuzzy' + | 'Georgi16' + | 'Georgia11' + | 'Ghost' + | 'Ghoulish' + | 'Glenyn' + | 'Goofy' + | 'Gothic' + | 'Graceful' + | 'Gradient' + | 'Graffiti' + | 'Greek' + | 'Heart Left' + | 'Heart Right' + | 'Henry 3D' + | 'Hex' + | 'Hieroglyphs' + | 'Hollywood' + | 'Horizontal Left' + | 'Horizontal Right' + | 'ICL-1900' + | 'Impossible' + | 'Invita' + | 'Isometric1' + | 'Isometric2' + | 'Isometric3' + | 'Isometric4' + | 'Italic' + | 'Ivrit' + | 'JS Block Letters' + | 'JS Bracket Letters' + | 'JS Capital Curves' + | 'JS Cursive' + | 'JS Stick Letters' + | 'Jacky' + | 'Jazmine' + | 'Jerusalem' + | 'Katakana' + | 'Kban' + | 'Keyboard' + | 'Knob' + | 'Konto Slant' + | 'Konto' + | 'LCD' + | 'Larry 3D 2' + | 'Larry 3D' + | 'Lean' + | 'Letters' + | 'Lil Devil' + | 'Line Blocks' + | 'Linux' + | 'Lockergnome' + | 'Madrid' + | 'Marquee' + | 'Maxfour' + | 'Merlin1' + | 'Merlin2' + | 'Mike' + | 'Mini' + | 'Mirror' + | 'Mnemonic' + | 'Modular' + | 'Morse' + | 'Morse2' + | 'Moscow' + | 'Mshebrew210' + | 'Muzzle' + | 'NScript' + | 'NT Greek' + | 'NV Script' + | 'Nancyj-Fancy' + | 'Nancyj-Improved' + | 'Nancyj-Underlined' + | 'Nancyj' + | 'Nipples' + | 'O8' + | 'OS2' + | 'Octal' + | 'Ogre' + | 'Old Banner' + | 'Patorjk\'s Cheese' + | 'Patorjk-HeX' + | 'Pawp' + | 'Peaks Slant' + | 'Peaks' + | 'Pebbles' + | 'Pepper' + | 'Poison' + | 'Puffy' + | 'Puzzle' + | 'Pyramid' + | 'Rammstein' + | 'Rectangles' + | 'Red Phoenix' + | 'Relief' + | 'Relief2' + | 'Reverse' + | 'Roman' + | 'Rot13' + | 'Rot13' + | 'Rotated' + | 'Rounded' + | 'Rowan Cap' + | 'Rozzo' + | 'Runic' + | 'Runyc' + | 'S Blood' + | 'SL Script' + | 'Santa Clara' + | 'Script' + | 'Serifcap' + | 'Shadow' + | 'Shimrod' + | 'Short' + | 'Slant Relief' + | 'Slant' + | 'Slide' + | 'Small Caps' + | 'Small Isometric1' + | 'Small Keyboard' + | 'Small Poison' + | 'Small Script' + | 'Small Shadow' + | 'Small Slant' + | 'Small Tengwar' + | 'Small' + | 'Soft' + | 'Speed' + | 'Spliff' + | 'Stacey' + | 'Stampate' + | 'Stampatello' + | 'Standard' + | 'Star Strips' + | 'Star Wars' + | 'Stellar' + | 'Stforek' + | 'Stick Letters' + | 'Stop' + | 'Straight' + | 'Stronger Than All' + | 'Sub-Zero' + | 'Swamp Land' + | 'Swan' + | 'Sweet' + | 'THIS' + | 'Tanja' + | 'Tengwar' + | 'Term' + | 'Test1' + | 'The Edge' + | 'Thick' + | 'Thin' + | 'Thorned' + | 'Three Point' + | 'Ticks Slant' + | 'Ticks' + | 'Tiles' + | 'Tinker-Toy' + | 'Tombstone' + | 'Train' + | 'Trek' + | 'Tsalagi' + | 'Tubular' + | 'Twisted' + | 'Two Point' + | 'USA Flag' + | 'Univers' + | 'Varsity' + | 'Wavy' + | 'Weird' + | 'Wet Letter' + | 'Whimsy' + | 'Wow' + ; + + type KerningMethods = + | 'default' + | 'full' + | 'fitted' + | 'controlled smushing' + | 'universal smushing' + ; + type PrintDirection = number; + + interface FittingRules { + vLayout: number; + vRule5: boolean; + vRule4: boolean; + vRule3: boolean; + vRule2: boolean; + vRule1: boolean; + hLayout: number; + hRule6: boolean; + hRule5: boolean; + hRule4: boolean; + hRule3: boolean; + hRule2: boolean; + hRule1: boolean; + } + + interface Options { + font?: Fonts; + horizontalLayout?: KerningMethods; + verticalLayout?: KerningMethods; + printDirection?: PrintDirection; + showHardBlanks?: boolean; + } + interface FontOptions { + hardBlank: string; + height: number; + baseline: number; + maxLength: number; + oldLayout: number; + numCommentLines: number; + printDirection: PrintDirection; + fullLayout: number | null; + codeTagCount: number | null; + fittingRules: FittingRules; + } + interface Defaults { + font: Fonts; + fontPath: string; + } + + function text(txt: string, cb: (error: Error | null, result?: string) => void): void; + function text(txt: string, font: Fonts, cb: (error: Error | null, result?: string) => void): void; + /** + * @desc + * This `unified-signatures` is disabled because `Fonts` type is too long + */ + // tslint:disable-next-line: unified-signatures + function text(txt: string, options: Options | undefined, cb: (error: Error | null, result?: string) => void): void; + + function textSync(txt: string, font?: Fonts): string; + /** + * @desc + * This `unified-signatures` is disabled because `Fonts` type is too long + */ + // tslint:disable-next-line: unified-signatures + function textSync(txt: string, options: Options): string; + + function metadata(font: Fonts, cb: (error: Error | null, fontOptions?: FontOptions, headerComment?: string) => void): void; + + function defaults(opt?: Partial): Defaults; + + function loadFont(font: Fonts, cb: (error: Error | null, fontOptions?: FontOptions) => void): void; + /** + * @todo + * Use 'node' namespace to add following methods only in node environment. + */ + /** + * @warn + * This method works in node environment only. + * In browser environment, this method does not work. + */ + function loadFontSync(font: Fonts): FontOptions; + /** + * @warn + * This method exists in node environment only. + * In browser environment, this method does not exist. + */ + function fonts(cb: (error: Error | null, fontList?: Fonts[]) => void): void; + /** + * @warn + * This method exists in node environment only. + * In browser environment, this method does not exist. + */ + function fontsSync(): Fonts[]; +} + +declare function figlet(txt: string, cb: (error: Error | null, result?: string) => void): void; +declare function figlet(txt: string, font: figlet.Fonts, cb: (error: Error | null, result?: string) => void): void; +/** + * @desc + * This `unified-signatures` is disabled because `Fonts` type is too long + */ +// tslint:disable-next-line: unified-signatures +declare function figlet(txt: string, options: figlet.Options | undefined, cb: (error: Error | null, result?: string) => void): void; + +export as namespace figlet; +export = figlet; diff --git a/types/figlet/tsconfig.json b/types/figlet/tsconfig.json new file mode 100644 index 0000000000..946bec6c7d --- /dev/null +++ b/types/figlet/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "figlet-tests.ts" + ] +} diff --git a/types/figlet/tslint.json b/types/figlet/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/figlet/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/find/find-tests.ts b/types/find/find-tests.ts index c6c1cd04f5..3ca401f69a 100644 --- a/types/find/find-tests.ts +++ b/types/find/find-tests.ts @@ -16,9 +16,9 @@ find.file(regexPattern, rootDir, (dirs: string[]): void => { }).error(errorCb); find.fileSync(rootDir); // $ExpectType string[] find.fileSync(stringPattern, rootDir); // $ExpectType string[] find.fileSync(regexPattern, rootDir); // $ExpectType string[] -find.eachFile(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachFile(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachFile(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachfile(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachfile(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachfile(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream find.dir(stringPattern, rootDir, (dirs: string[]): void => { }).error(emptyCb); // $ExpectType void find.dir(stringPattern, rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType void @@ -27,6 +27,6 @@ find.dir(rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType find.dirSync(rootDir); // $ExpectType string[] find.dirSync(stringPattern, rootDir); // $ExpectType string[] find.dirSync(regexPattern, rootDir); // $ExpectType string[] -find.eachDir(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachDir(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachDir(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachdir(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachdir(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachdir(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream diff --git a/types/find/index.d.ts b/types/find/index.d.ts index 61166669db..1ffb2f8aee 100644 --- a/types/find/index.d.ts +++ b/types/find/index.d.ts @@ -45,7 +45,7 @@ export function file(pattern: string | RegExp, root: string, callback: (files: s * @param root The root directory * @param callback A callback that accepts each file separately */ -export function eachFile(root: string, callback: (file: string) => void): FindEachStream; +export function eachfile(root: string, callback: (file: string) => void): FindEachStream; /** * Find all files that match a glob pattern in a given directory asynchronously. @@ -53,7 +53,7 @@ export function eachFile(root: string, callback: (file: string) => void): FindEa * @param root The root directory * @param callback A callback that accepts an array of the found files */ -export function eachFile(pattern: string | RegExp, root: string, callback: (file: string) => void): FindEachStream; +export function eachfile(pattern: string | RegExp, root: string, callback: (file: string) => void): FindEachStream; /** * Find all files in a given directory synchronously. @@ -105,7 +105,7 @@ export function dirSync(pattern: string | RegExp, root: string): string[]; * @param root The root directory * @param callback A callback that accepts each of the found directories separately */ -export function eachDir(root: string, callback: (directory: string) => void): FindEachStream; +export function eachdir(root: string, callback: (directory: string) => void): FindEachStream; /** * Find all directories that match a glob pattern in a given directory asynchronously. @@ -113,4 +113,4 @@ export function eachDir(root: string, callback: (directory: string) => void): Fi * @param root The root directory * @param callback A callback that accepts each of the found directories separately */ -export function eachDir(pattern: string | RegExp, root: string, callback: (directory: string) => void): FindEachStream; +export function eachdir(pattern: string | RegExp, root: string, callback: (directory: string) => void): FindEachStream; diff --git a/types/generic-pool/generic-pool-tests.ts b/types/generic-pool/generic-pool-tests.ts index 6cf0292709..09a1e611ea 100644 --- a/types/generic-pool/generic-pool-tests.ts +++ b/types/generic-pool/generic-pool-tests.ts @@ -41,6 +41,8 @@ const opts = { const pool = genericPool.createPool(factory, opts); +pool.start(); + pool.use((conn: Connection) => 'test') .then((result: string) => { }); diff --git a/types/generic-pool/index.d.ts b/types/generic-pool/index.d.ts index 8cae9ce37c..e50682ab12 100644 --- a/types/generic-pool/index.d.ts +++ b/types/generic-pool/index.d.ts @@ -17,6 +17,7 @@ export class Pool extends EventEmitter { max: number; min: number; + start(): void; acquire(priority?: number): PromiseLike; release(resource: T): void; destroy(resource: T): void; diff --git a/types/gl-matrix/gl-matrix-tests.ts b/types/gl-matrix/gl-matrix-tests.ts index c929323764..cf9c4ef616 100644 --- a/types/gl-matrix/gl-matrix-tests.ts +++ b/types/gl-matrix/gl-matrix-tests.ts @@ -79,6 +79,7 @@ outVec2 = vec2.transformMat2d(outVec2, vec2A, mat2dA); outVec2 = vec2.transformMat3(outVec2, vec2A, mat3A); outVec2 = vec2.transformMat4(outVec2, vec2A, mat4A); vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); +outVal = vec2.angle(vec2A, vec2B); outStr = vec2.str(vec2A); outBool = vec2.exactEquals(vec2A, vec2B); outBool = vec2.equals(vec2A, vec2B); diff --git a/types/gl-matrix/index.d.ts b/types/gl-matrix/index.d.ts index cad714796d..2c86b6a057 100644 --- a/types/gl-matrix/index.d.ts +++ b/types/gl-matrix/index.d.ts @@ -431,6 +431,14 @@ declare module 'gl-matrix' { public static forEach(a: Float32Array, stride: number, offset: number, count: number, fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; + /** + * Get the angle between two 2D vectors + * @param a The first operand + * @param b The second operand + * @returns The angle in radians + */ + public static angle(a: vec2 | number[], b: vec2 | number[]): number; + /** * Perform some operation over an array of vec2s. * diff --git a/types/gl-texture2d/index.d.ts b/types/gl-texture2d/index.d.ts index 4d979d99f9..59f92b8555 100644 --- a/types/gl-texture2d/index.d.ts +++ b/types/gl-texture2d/index.d.ts @@ -6,6 +6,8 @@ import ndarray = require("ndarray"); +type GLenum = number; + type InputType = ImageData | HTMLCanvasElement | HTMLImageElement | HTMLVideoElement; interface RawObject { diff --git a/types/google-cloud__pubsub/index.d.ts b/types/google-cloud__pubsub/index.d.ts index 130e62a5e4..9375b55860 100644 --- a/types/google-cloud__pubsub/index.d.ts +++ b/types/google-cloud__pubsub/index.d.ts @@ -1,7 +1,8 @@ // Type definitions for @google-cloud/pubsub 0.18 -// Project: https://github.com/GoogleCloudPlatform/google-cloud-node/tree/master/packages/pubsub +// Project: https://github.com/googleapis/nodejs-pubsub // Definitions by: Paul Huynh // LunaPg +// Marco Siviero // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -115,11 +116,15 @@ declare namespace PubSub { interface Publisher { publish(data: Buffer, callback: Publisher.PublishCallback): void; - publish(data: Buffer, attributes: object, callback: Publisher.PublishCallback): void; - publish(data: Buffer, attributes?: object): Promise; + publish(data: Buffer, attributes: Publisher.Attributes, callback: Publisher.PublishCallback): void; + publish(data: Buffer, attributes?: Publisher.Attributes): Promise; } namespace Publisher { type PublishCallback = (error: Error | null, messageId: string) => void; + + interface Attributes { + [key: string]: string | Buffer | ArrayBuffer; + } } interface Snapshot { diff --git a/types/gradient-string/gradient-string-tests.ts b/types/gradient-string/gradient-string-tests.ts new file mode 100644 index 0000000000..7216a0862f --- /dev/null +++ b/types/gradient-string/gradient-string-tests.ts @@ -0,0 +1,42 @@ +import tinycolor = require('tinycolor2'); +import gradient = require('gradient-string'); + +// $ExpectType string +gradient('cyan', 'pink')('Hello world!'); + +// $ExpectType Gradient +gradient('red', 'green', 'blue'); +// $ExpectType Gradient +gradient(['#FF0000', '#00FF00', '#0000FF']); + +// $ExpectType Gradient +gradient([ + tinycolor('#FFBB65'), // tinycolor object + {r: 0, g: 255, b: 0}, // RGB object + {h: 240, s: 1, v: 1, a: 1}, // HSVa object + 'rgb(120, 120, 0)', // RGB CSS string + 'gold' // named color +]); + +// $ExpectType string +gradient.rainbow('I love gradient-strings!'); + +// $ExpectType string +gradient('orange', 'yellow').multiline([ + " __", + "<(o )___", + " ( ._> /", + " `---'", +].join('\n')); + +// $ExpectType string +gradient.atlas.multiline('Multi line\nstring'); +// $ExpectType string +gradient('cyan', 'pink').multiline('Multi line\nstring', {interpolation: 'hsv'}); + +// $ExpectType Gradient +gradient([ + {color: '#d8e0de', pos: 0}, + {color: '#255B53', pos: 0.8}, + {color: '#000000', pos: 1}, +]); diff --git a/types/gradient-string/index.d.ts b/types/gradient-string/index.d.ts new file mode 100644 index 0000000000..0191700b19 --- /dev/null +++ b/types/gradient-string/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for gradient-string 1.1 +// Project: https://github.com/bokub/gradient-string +// Definitions by: Junyoung Clare Jang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import tinycolor = require('tinycolor2'); + +declare namespace gradient { + interface PositionedColorInput { + color: tinycolor.ColorInput; + pos: number; + } + + interface Gradient { + (message?: string, opt?: Options): string; + multiline(message?: string, opt?: Options): string; + } + + interface Options { + interpolation?: string; + hsvSpin?: string; + } + + const atlas: Gradient; + const cristal: Gradient; + const teen: Gradient; + const mind: Gradient; + const morning: Gradient; + const vice: Gradient; + const passion: Gradient; + const fruit: Gradient; + const instagram: Gradient; + const retro: Gradient; + const summer: Gradient; + const rainbow: Gradient; + const pastel: Gradient; +} + +declare function gradient(colors: tinycolor.ColorInput[] | gradient.PositionedColorInput[]): gradient.Gradient; +declare function gradient(...colors: tinycolor.ColorInput[]): gradient.Gradient; +declare function gradient(...colors: gradient.PositionedColorInput[]): gradient.Gradient; +export = gradient; diff --git a/types/gradient-string/tsconfig.json b/types/gradient-string/tsconfig.json new file mode 100644 index 0000000000..d0e3833686 --- /dev/null +++ b/types/gradient-string/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gradient-string-tests.ts" + ] +} diff --git a/types/gradient-string/tslint.json b/types/gradient-string/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/gradient-string/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/gulp-imagemin/gulp-imagemin-tests.ts b/types/gulp-imagemin/gulp-imagemin-tests.ts new file mode 100644 index 0000000000..7fc1d86311 --- /dev/null +++ b/types/gulp-imagemin/gulp-imagemin-tests.ts @@ -0,0 +1,20 @@ +import * as GulpImagemin from 'gulp-imagemin'; + +GulpImagemin(); + +GulpImagemin([ + GulpImagemin.gifsicle({ interlaced: true }), + GulpImagemin.jpegtran({ progressive: true }), + GulpImagemin.optipng({ optimizationLevel: 5 }), + GulpImagemin.svgo({ + plugins: [{ removeViewBox: true }, { cleanupIDs: false }] + }) +]); + +GulpImagemin({ verbose: true }); + +GulpImagemin([ + GulpImagemin.svgo({ + plugins: [{ removeViewBox: true }] + }) +], { verbose: true }); diff --git a/types/gulp-imagemin/index.d.ts b/types/gulp-imagemin/index.d.ts new file mode 100644 index 0000000000..42c1ef8d5c --- /dev/null +++ b/types/gulp-imagemin/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for gulp-imagemin 4.1 +// Project: https://github.com/sindresorhus/gulp-imagemin#readme +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Transform } from 'stream'; + +declare function imagemin(pluginsOrOptions?: imagemin.Plugin[] | imagemin.Options): Transform; +declare function imagemin(plugins?: imagemin.Plugin[], options?: imagemin.Options): Transform; + +declare namespace imagemin { + interface Options { + verbose?: boolean; + } + + type Plugin = (input: any) => Promise; + type PluginFactory = (options?: any) => Plugin; + + const gifsicle: PluginFactory; + const jpegtran: PluginFactory; + const optipng: PluginFactory; + const svgo: PluginFactory; +} + +export = imagemin; diff --git a/types/gulp-imagemin/tsconfig.json b/types/gulp-imagemin/tsconfig.json new file mode 100644 index 0000000000..1b35a74382 --- /dev/null +++ b/types/gulp-imagemin/tsconfig.json @@ -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", + "gulp-imagemin-tests.ts" + ] +} diff --git a/types/gulp-imagemin/tslint.json b/types/gulp-imagemin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-imagemin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gulp-template/gulp-template-tests.ts b/types/gulp-template/gulp-template-tests.ts new file mode 100644 index 0000000000..9e5011074c --- /dev/null +++ b/types/gulp-template/gulp-template-tests.ts @@ -0,0 +1,20 @@ +import gulp = require('gulp'); +import gulpTemplate = require('gulp-template'); + +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ a: 'A' }, { sourceURL: 'https://www.example.com' }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ b: 'B' }, { escape: /x/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ c: 'C' }, { evaluate: /y/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ d: 'D' }, { imports: /z/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ e: 'E' }, { interpolate: /w/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ f: 'F' }, { variable: 'some-var' }))); + +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ g: 'G' }, { badOption: 'some-var' }))); // $ExpectError + +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ sourceURL: 'https://www.example.com' }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ escape: /x/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ evaluate: /y/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ imports: /z/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ interpolate: /w/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ variable: 'some-var' }))); + +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ badOption: 'some-var' }))); // $ExpectError diff --git a/types/gulp-template/index.d.ts b/types/gulp-template/index.d.ts new file mode 100644 index 0000000000..a2270eb387 --- /dev/null +++ b/types/gulp-template/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for gulp-template 5.0 +// Project: https://github.com/sindresorhus/gulp-template#readme +// Definitions by: Peter Safranek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +/// + +import * as _ from 'lodash'; +import * as stream from 'stream'; + +declare function gulpTemplate(data: any, options: _.TemplateOptions): stream.Transform; + +declare namespace gulpTemplate { + function precompile(options: _.TemplateOptions): stream.Transform; +} + +export = gulpTemplate; diff --git a/types/gulp-template/tsconfig.json b/types/gulp-template/tsconfig.json new file mode 100644 index 0000000000..0666e34adc --- /dev/null +++ b/types/gulp-template/tsconfig.json @@ -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", + "gulp-template-tests.ts" + ] +} diff --git a/types/gulp-template/tslint.json b/types/gulp-template/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-template/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 5815f7218b..23aaf3608c 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -451,7 +451,7 @@ export interface Request extends Podium { * An object where each key is the name assigned by a route pre-handler methods function. The values are the raw values provided to the continuation function as argument. For the wrapped response * object, use responses. */ - readonly pre: Util.Dictionary; + readonly pre: Util.Dictionary; /** * Access: read / write (see limitations below). @@ -463,7 +463,7 @@ export interface Request extends Podium { /** * Same as pre but represented as the response object created by the pre method. */ - readonly preResponses: Util.Dictionary; + readonly preResponses: Util.Dictionary; /** * By default the object outputted from node's URL parse() method. Might also be set indirectly via request.setUrl in which case it may be a string (if url is set to an object with the query diff --git a/types/history/index.d.ts b/types/history/index.d.ts index eb15aaa0fc..1c7b35b8f2 100644 --- a/types/history/index.d.ts +++ b/types/history/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for history 4.6.2 +// Type definitions for history 4.7.2 // Project: https://github.com/mjackson/history // Definitions by: Sergey Buturlakin , Nathan Brown , Young Rok Kim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export as namespace History; export type Action = 'PUSH' | 'POP' | 'REPLACE'; @@ -23,24 +24,24 @@ export interface History { createHref(location: LocationDescriptorObject): Href; } -export interface Location { +export interface Location { pathname: Pathname; search: Search; - state: LocationState; + state: S; hash: Hash; key?: LocationKey; } -export interface LocationDescriptorObject { +export interface LocationDescriptorObject { pathname?: Pathname; search?: Search; - state?: LocationState; + state?: S; hash?: Hash; key?: LocationKey; } export namespace History { - export type LocationDescriptor = Path | LocationDescriptorObject; + export type LocationDescriptor = Path | LocationDescriptorObject; export type LocationKey = string; export type LocationListener = (location: Location, action: Action) => void; export type LocationState = any; @@ -53,7 +54,7 @@ export namespace History { export type Href = string; } -export type LocationDescriptor = History.LocationDescriptor; +export type LocationDescriptor = History.LocationDescriptor; export type LocationKey = History.LocationKey; export type LocationListener = History.LocationListener; export type LocationState = History.LocationState; diff --git a/types/hoist-non-react-statics/hoist-non-react-statics-tests.tsx b/types/hoist-non-react-statics/hoist-non-react-statics-tests.tsx new file mode 100644 index 0000000000..9767614bcc --- /dev/null +++ b/types/hoist-non-react-statics/hoist-non-react-statics-tests.tsx @@ -0,0 +1,45 @@ +import * as React from 'react'; +import * as PropTypes from 'prop-types'; + +import hoistNonReactStatics = require('hoist-non-react-statics'); + +class A extends React.Component<{x: number, y?: number}> { + static a = 'a'; + + static propTypes = { + m: PropTypes.number.isRequired + }; + + getA() { + return A.a; + } +} + +class B extends React.Component { + static b = 'b'; + + static propTypes = { + n: PropTypes.number.isRequired + }; + + getB() { + return B.b; + } +} + +const C = hoistNonReactStatics(A, B); + +C.a !== C.b; + +C.propTypes.m; +C.prototype.getA(); + +C.propTypes.n; // $ExpectError +C.prototype.getB(); // $ExpectError + +; + +const D = hoistNonReactStatics(A, B, { a: true, b: true }); + +D.a; +D.b; // $ExpectError diff --git a/types/hoist-non-react-statics/index.d.ts b/types/hoist-non-react-statics/index.d.ts new file mode 100644 index 0000000000..414c4c41f0 --- /dev/null +++ b/types/hoist-non-react-statics/index.d.ts @@ -0,0 +1,50 @@ +// Type definitions for hoist-non-react-statics 3.0 +// Project: https://github.com/mridgway/hoist-non-react-statics#readme +// Definitions by: JounQin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +interface REACT_STATICS { + childContextTypes: true; + contextTypes: true; + defaultProps: true; + displayName: true; + getDefaultProps: true; + getDerivedStateFromProps: true; + mixins: true; + propTypes: true; + type: true; +} + +interface KNOWN_STATICS { + name: true; + length: true; + prototype: true; + caller: true; + callee: true; + arguments: true; + arity: true; +} + +declare function hoistNonReactStatics< + T extends React.ComponentType, + S extends React.ComponentType, + C extends { + [key: string]: true + } = {} +>( + TargetComponent: T, + SourceComponent: S, + customStatic?: C, +): T & + { + [key in Exclude< + keyof S, + // only extends static properties, exclude instance properties and known react statics + keyof REACT_STATICS | keyof KNOWN_STATICS | keyof C + >]: S[key] + }; + +export = hoistNonReactStatics; diff --git a/types/hoist-non-react-statics/tsconfig.json b/types/hoist-non-react-statics/tsconfig.json new file mode 100644 index 0000000000..e0d62444e2 --- /dev/null +++ b/types/hoist-non-react-statics/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" + }, + "files": [ + "index.d.ts", + "hoist-non-react-statics-tests.tsx" + ] +} diff --git a/types/hoist-non-react-statics/tslint.json b/types/hoist-non-react-statics/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hoist-non-react-statics/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts b/types/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts index eadfcea369..174a871b9f 100644 --- a/types/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts +++ b/types/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts @@ -19,7 +19,7 @@ const options: LngDetector.DetectorOptions = { cookieDomain: "myDomain", // optional htmlTag with lang attribute, the default is: - htmlTag: document.documentElement + htmlTag: document.documentElement! }; i18next.use(LngDetector).init({ diff --git a/types/jquery.fileupload/index.d.ts b/types/jquery.fileupload/index.d.ts index 6ca998d41a..28bbf3c969 100644 --- a/types/jquery.fileupload/index.d.ts +++ b/types/jquery.fileupload/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jQuery File Upload Plugin 5.40.1 +// Type definitions for jQuery File Upload Plugin 9.22.0 // Project: https://github.com/blueimp/jQuery-File-Upload // Definitions by: Rob Alarcon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,7 +6,7 @@ /// -// Interface options for the plugin +// Interface options for the plugin interface JQueryFileInputOptions { /** @@ -106,8 +106,8 @@ interface JQueryFileInputOptions { */ redirectParamName?: string; - // The HTTP request method must be "POST" or "PUT" - type?: string, + // The HTTP request method must be "POST" or "PUT" + type?: string, /** * Set the following option to the location of a postMessage window, @@ -199,7 +199,7 @@ interface JQueryFileInputOptions { * handlers using jQuery's Deferred callbacks: * data.submit().done(func).fail(func).always(func); */ - add?: (e: JQueryEventObject, data: JQueryFileInputOptions) => void; + add?: (e: JQueryEventObject, data: JqueryFileUploadAddObject) => void; // The plugin options are used as settings object for the ajax calls. // The following are jQuery ajax settings required for the file uploads: @@ -209,7 +209,7 @@ interface JQueryFileInputOptions { cache?: boolean; timeout?: number; - + active?: Function; progress?: (e: JQueryEventObject, data: JQueryFileUploadProgressObject) => void; send?: (e: JQueryEventObject, data: JQueryFileUploadProgressObject) => void; @@ -217,13 +217,13 @@ interface JQueryFileInputOptions { // Validation /** - * The maximum allowed file size in bytes. - * Type: integer - * Default: undefined - * Example: 10000000 // 10 MB - * Note: This option has only an effect for browsers supporting the File API. - * @see https://github.com/blueimp/jQuery-File-Upload/wiki/Options#maxfilesize - */ + * The maximum allowed file size in bytes. + * Type: integer + * Default: undefined + * Example: 10000000 // 10 MB + * Note: This option has only an effect for browsers supporting the File API. + * @see https://github.com/blueimp/jQuery-File-Upload/wiki/Options#maxfilesize + */ maxFileSize?: number; // Other callbacks: @@ -243,7 +243,7 @@ interface JQueryFileInputOptions { chunkfail?: (e: JQueryEventObject, data: JQueryFileUploadChunkObject) => void; chunkalways?: (e: JQueryEventObject, data: JQueryFileUploadChunkObject) => void; - // Others + // Others url?: string; files?: any; @@ -263,6 +263,12 @@ interface JQuery { fileupload(action: string, message:string, settings: JQueryFileInputOptions | string): JQueryFileUpload; } +interface JqueryFileUploadEnhancedPromise extends JQueryPromise{ + success: JQueryPromise['done'], + error: JQueryPromise['fail'], + complete: JQueryPromise['always'], +} + interface JQuerySupport { fileInput?: boolean; } @@ -275,6 +281,20 @@ interface JQueryFileUploadChangeObject { originalFiles: File[]; } +interface JqueryFileUploadConvenienceObject { + abort: () => JqueryFileUploadEnhancedPromise; + process: (resolveFunc?: Function, rejectFunc?: Function) => JqueryFileUploadEnhancedPromise; + processing: () => JqueryFileUploadEnhancedPromise; + progress: () => JqueryFileUploadEnhancedPromise; + response: () => JqueryFileUploadEnhancedPromise; + submit(): JqueryFileUploadEnhancedPromise; + state: () => JqueryFileUploadEnhancedPromise; +} + +interface JqueryFileUploadAddObject extends JQueryFileUploadChangeObject, JqueryFileUploadConvenienceObject { + paramName?: string | string[]; +} + interface JQueryFileUploadProgressAllObject { loaded?: number; total?: number; @@ -304,4 +324,4 @@ interface JQueryFileUploadProgressObject extends JQueryFileInputOptions, JQueryF } interface JQueryFileUploadDone extends JQueryFileInputOptions, JQueryFileUploadXhr { -} +} \ No newline at end of file diff --git a/types/jquery.gridster/index.d.ts b/types/jquery.gridster/index.d.ts index c91fd6f9e4..0106b448c6 100644 --- a/types/jquery.gridster/index.d.ts +++ b/types/jquery.gridster/index.d.ts @@ -10,23 +10,23 @@ gridster-0.1.0.d.ts may be freely distributed under the MIT license. Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/gridster.d.ts Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @@ -104,7 +104,7 @@ interface GridsterOptions { * Base widget dimensions in pixels. The first index for the width and the second for the height. * Default = [400, 225] **/ - widget_base_dimensions?: number[]; + widget_base_dimensions?: ('auto'|number)[]; /** * Add more columns in addition to those that have been calculated. @@ -292,7 +292,7 @@ interface Gridster { * @return Returns the instance of the Gridster class. **/ enable(): Gridster; - + /** * Disables dragging. * @return Returns the instance of the Gridster class. diff --git a/types/jquery.gridster/jquery.gridster-tests.ts b/types/jquery.gridster/jquery.gridster-tests.ts index 4dc3e3f27e..6703dea785 100644 --- a/types/jquery.gridster/jquery.gridster-tests.ts +++ b/types/jquery.gridster/jquery.gridster-tests.ts @@ -28,6 +28,9 @@ var position = coords.col + coords.row; options.widget_base_dimensions = [100, 200]; gridster.resize_widget_dimensions(options); +options.widget_base_dimensions = ['auto', 200]; +gridster.resize_widget_dimensions(options); + gridster.set_widget_min_size(0, [1, 2]); function noOptions() { @@ -48,13 +51,13 @@ function widgetSelectorString() { }; var grid: Gridster = $('.gridster ul').gridster(opts).data('gridster') -} +} function withNamespace() { var grid: Gridster = $('.gridster ul').gridster({ namespace: 'custom-gridster' }).data('gridster') -} +} function withStylesheet() { var grid: Gridster = $('.gridster ul').gridster({ diff --git a/types/jquery.notify/jquery.notify-tests.ts b/types/jquery.notify/jquery.notify-tests.ts index 1af31996a1..1d872e92fa 100644 --- a/types/jquery.notify/jquery.notify-tests.ts +++ b/types/jquery.notify/jquery.notify-tests.ts @@ -1,4 +1,4 @@ -let $container: JQueryNotifyWidget = $("").appendTo(document.body).notify(); +let $container: JQueryNotifyWidget = $("").appendTo(document.body!).notify(); let notification: JQueryNotifyInstance = $container.notify( "create", diff --git a/types/jsdom/jsdom-tests.ts b/types/jsdom/jsdom-tests.ts index c672580a63..24b136e5ad 100644 --- a/types/jsdom/jsdom-tests.ts +++ b/types/jsdom/jsdom-tests.ts @@ -17,7 +17,7 @@ function test_executing_scripts1() { `); // The script will not be executed, by default: - dom.window.document.body.children.length === 1; + dom.window.document.body!.children.length === 1; } function test_executing_scripts2() { @@ -26,14 +26,14 @@ function test_executing_scripts2() { `, { runScripts: 'dangerously' }); // The script will be executed and modify the DOM: - dom.window.document.body.children.length === 2; + dom.window.document.body!.children.length === 2; } function test_executing_scripts3() { const window = (new JSDOM(``, { runScripts: 'outside-only' })).window; window.eval(`document.body.innerHTML = "

Hello, world!

";`); - window.document.body.children.length === 1; + window.document.body!.children.length === 1; } function test_virtualConsole() { @@ -74,7 +74,7 @@ function test_serialize() { dom.serialize() === 'hello'; // Contrast with: - dom.window.document.documentElement.outerHTML === 'hello'; + dom.window.document.documentElement!.outerHTML === 'hello'; } function test_nodeLocation() { @@ -86,7 +86,7 @@ function test_nodeLocation() { ); const document = dom.window.document; - const bodyEl = document.body; // implicitly created + const bodyEl = document.body!; // implicitly created const pEl = document.querySelector('p')!; const textNode = pEl.firstChild!; const imgEl = document.querySelector('img')!; diff --git a/types/json2csv/JSON2CSVBase.d.ts b/types/json2csv/JSON2CSVBase.d.ts index c5f328db1f..1faf2a5318 100644 --- a/types/json2csv/JSON2CSVBase.d.ts +++ b/types/json2csv/JSON2CSVBase.d.ts @@ -92,9 +92,10 @@ declare abstract class JSON2CSVBase { * Performs the flattening of a data row recursively * * @param {object} dataRow Original JSON object + * @param {string} separator Separator to be used as the flattened field name * @returns {object} Flattened object */ - protected flatten(dataRow: T): object; + protected flatten(dataRow: T, separator: string): object; /** * Performs the unwind recursively in specified sequence diff --git a/types/json2csv/JSON2CSVTransform.d.ts b/types/json2csv/JSON2CSVTransform.d.ts index 1785e09214..f453ece8b1 100644 --- a/types/json2csv/JSON2CSVTransform.d.ts +++ b/types/json2csv/JSON2CSVTransform.d.ts @@ -80,9 +80,10 @@ declare class JSON2CSVTransform extends Transform { // implements JSON2CSVBas * Performs the flattening of a data row recursively * * @param {object} dataRow Original JSON object + * @param {string} separator Separator to be used as the flattened field name * @returns {object} Flattened object */ - protected flatten(dataRow: T): object; + protected flatten(dataRow: T, separator: string): object; /** * Performs the unwind recursively in specified sequence diff --git a/types/json2csv/index.d.ts b/types/json2csv/index.d.ts index 55a1829625..55aca2687c 100644 --- a/types/json2csv/index.d.ts +++ b/types/json2csv/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for json2csv 4.1 +// Type definitions for json2csv 4.2 // Project: https://github.com/zemirco/json2csv // Definitions by: Juanjo Diaz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/json2csv/json2csv-tests.ts b/types/json2csv/json2csv-tests.ts index 67c46cd1c3..42f8a58b70 100644 --- a/types/json2csv/json2csv-tests.ts +++ b/types/json2csv/json2csv-tests.ts @@ -76,7 +76,7 @@ class ParserExt extends Parser { s = this.processValue(new Date(), true); s = this.processValue({}, true); s = this.processValue([], true); - const flattenedData: object = this.flatten({}); + const flattenedData: object = this.flatten({}, '.'); const unwindedData: object[] = this.unwindData([], []); } } @@ -110,7 +110,7 @@ class TransformExt extends Transform { s = this.processValue(new Date(), true); s = this.processValue({}, true); s = this.processValue([], true); - const flattenedData: object = this.flatten({}); + const flattenedData: object = this.flatten({}, '.'); const unwindedData: object[] = this.unwindData([], []); } } diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index f6be274a30..fe8d46658a 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -286,12 +286,6 @@ declare namespace Knex { (columnName: string): QueryBuilder; } - interface WhereIn { - (columnName: string, values: Value[]): QueryBuilder; - (columnName: string, callback: QueryCallback): QueryBuilder; - (columnName: string, query: QueryBuilder): QueryBuilder; - } - interface WhereBetween { (columnName: string, range: [Value, Value]): QueryBuilder; } @@ -306,7 +300,8 @@ declare namespace Knex { } interface WhereIn { - (columnName: string, values: Value[]): QueryBuilder; + (columnName: string, values: Value[] | QueryBuilder | QueryCallback): QueryBuilder; + (columnNames: string[], values: Value[][] | QueryBuilder | QueryCallback): QueryBuilder; } interface GroupBy extends RawQueryBuilder, ColumnNameQueryBuilder { diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 0c04dfc918..329ed9d414 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -1123,3 +1123,25 @@ knex({ table1Id: 'table1.id', table2Id: 'table2.id' }); + +knex('characters') + .select() + .whereIn(['name', 'class'], [['Bar', 'Fighter'], ['Foo', 'Druid']]); + +knex('characters') + .select() + .whereIn('name', knex('characters').select('name')); +knex('characters') + .select() + .whereIn(['name', 'class'], knex('characters').select('name', 'class')); + +knex('characters') + .select() + .whereIn('name', function() { + this.select('name').from('characters'); + }); +knex('characters') + .select() + .whereIn(['name', 'class'], function() { + this.select('name', 'class').from('characters'); + }); diff --git a/types/knuddels-userapps-api/index.d.ts b/types/knuddels-userapps-api/index.d.ts index 36c0c139de..baff7689f8 100644 --- a/types/knuddels-userapps-api/index.d.ts +++ b/types/knuddels-userapps-api/index.d.ts @@ -1,2741 +1,2933 @@ -// Type definitions for Knuddels UserApps API 1.0 +// Type definitions for Knuddels UserApps API 1.00108823 // Project: https://developer.knuddels.de // Definitions by: Knuddels GmbH & Co. KG // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // JSON definition -interface Json { +export interface Json { [x: string]: string | number | boolean | Date | Json | JsonArray; } -// tslint:disable-next-line no-empty-interface -interface JsonArray extends Array { } +export interface JsonArray extends Array { } + // serializable objects (for persistence) -type KnuddelsSerializable = string | number | boolean | User | BotUser; -interface KnuddelsJson { +export type KnuddelsSerializable = string | number | boolean | User | BotUser; +export interface KnuddelsJson { [x: string]: string | number | boolean | Date | KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable; } -// tslint:disable-next-line no-empty-interface -interface KnuddelsJsonArray extends Array { } +export interface KnuddelsJsonArray extends Array { } + // "data" that may be send between apps and between server and client -type KnuddelsEvent = string | Json | KnuddelsEventArray; -// tslint:disable-next-line no-empty-interface -interface KnuddelsEventArray extends Array { } +export type KnuddelsEvent = string | Json | KnuddelsEventArray; +export interface KnuddelsEventArray extends Array { } -/** - * App ist die abstrakte Klasse einer konkreten App, die ein Entwickler schreiben kann. - * Im eigenen Javascript-Code muss eine Variable mit dem Namen App vorhanden sein, damit eine App lauffähig ist. - */ -interface App { +declare global { /** - * Dieses Methode wird aufgerufen, sobald ein Nutzer versucht den Channel zu betreten. - * Die App kann nun entscheiden, ob der Nutzer den Channel betreten darf. - * - * Hinweis: Um ein responsives User Interface für den Nutzer, - * der den Channel betreten möchte zu garantieren, muss die App innerhalb von einer Sekunde auf diese Anfrage reagieren, - * damit ihre Antwort in das Ergebnis einfliesst. - * - * Mit bestimmten Smileyfeatures ist es derzeit trotzdem möglich, den Channel zu betreten. - * Diese Nutzer können nicht ausgesperrt werden: - *
    - *
  • Channelbesitzer
  • - *
  • Channelmoderatoren und HZAs
  • - *
  • Admins (sofern notwendig)
  • - *
  • Sysadmins
  • - *
  • User Apps Team (Mitarbeiter von Knuddels)
  • - *
- * - * Ist der Channel mit einem Passwort geschützt und der Nutzer, der versucht den Channel zu betreten kennt das Passwort, - * so kann er nicht aus dem Channel ausgeschlossen werden. + * @see https://developer.knuddels.de/docs/classes/App.html */ - mayJoinChannel?(user: User): ChannelJoinPermission; - /** - * Diese Methode wird jedes Mal aufgerufen, sobald ein Nutzer versucht eine öffentliche Nachricht zu senden. - * Die App kann nun entscheiden, ob die Nachricht veröffentlicht werden darf. - * - * Laufen mehrere Apps im selben Channel, so wird die Nachricht veröffentlicht, sofern alle Apps es erlauben. - * - * Dauert das Fragen aller Apps nach Erlaubnis länger als 10 Sekunden, so wird die Antwort genutzt, die bis dahin - * gegeben wurde. - */ - mayShowPublicMessage?(publicMessage: PublicMessage): boolean; - /** - * Diese Methode wird jedes Mal aufgerufen, sobald ein Nutzer versucht eine öffentliche Handlung auszuführen. - * Die App kann nun entscheiden, ob die Handlung ausgeführt werden darf. - * - * Laufen mehrere Apps im selben Channel, so wird die Handlung ausgeführt, sofern alle Apps es erlauben. - * - * Dauert das Fragen aller Apps nach Erlaubnis länger als 10 Sekunden, so wird die Antwort genutzt, die bis dahin - * gegeben wurde. - */ - mayShowPublicActionMessage?(publicActionMessage: PublicActionMessage): boolean; - /** - * Diese Methode wird aufgerufen, sobald die App startet. - * Dies ist der beste Zeipunkt um Werte zu initialisieren und aus der Persistenz zu lesen. - */ - onAppStart?(): void; - /** - * Diese Methode wird aufgerufen, wenn ein User Knuddel an den BotUser gesendet hat. - * Es ist die Aufgabe der App in dieser Methode zu entscheiden, ob sie die Knuddel annimmt oder ablehnt. - * Wird diese Methode von der App nicht implementiert, so werden Knuddel automatisch akzeptiert. - * Ist diese Methode implementiert und es treten Fehler (Exceptions, Timeout,...) auf oder der Entwickler entscheidet nicht, - * was mit den Knuddel geschehen soll, so werden diese vom App-System automatisch an den Absender zurück geschickt. - *
- * Wichtig: Zum Zeitpunkt des Aufrufs dieser Methode wurden die Knuddel noch nicht an den BotUser übertragen. - */ - onBeforeKnuddelReceived?(knuddelTransfer: KnuddelTransfer): void; - /** - * Diese Methode wird aufgerufen, sobald ein BotUser Knuddel von einem User erhalten hat. - */ - onKnuddelReceived?(sender: User, receiver: BotUser, knuddelAmount: KnuddelAmount, transferReason: string): void; - /** - * Diese Methode wird aufgerufen, wenn die App sich darauf vorbereiten soll heruntergefahren zu werden. - * Als Parameter wird die geschätzte Zeit übergeben, die die App noch hat, bis sie heruntergefahren wird - * und der Aufruf App/onShutdown:event folgt. - * - * App/onPrepareShutdown:event kann dazu benutzt werden das Nutzererlebnis zu verbessern, - * sofern eine App heruntergefahren werden muss (bsp. für Updates). - * Eine Spiele-App könnte z.B. entscheiden, dass sie keine weiteren Spiele eröffnet und den Spielern offener Spiele - * die Information anzeigt, wie lange das Spiel noch läuft, bevor es unentschieden endet. - * - *

Achtung: Die Methode kann im Lebenszyklus einer App mehrfach aufgerufen werden. - */ - onPrepareShutdown?(secondsTillShutdown: number): void; - /** - * Diese Methode wird aufgerufen, wenn ein BotUser privat angeschrieben wird. - */ - onPrivateMessage?(privateMessage: PrivateMessage): void; - /** - * Diese Methode wird aufgerufen, wenn im Channel der App - * eine öffentliche Nachricht geschrieben wird. - * Für Nachrichten von BotUsern wird diese Methode nicht aufgerufen. - */ - onPublicMessage?(publicMessage: PublicMessage): void; - /** - * Diese Methode wird aufgerufen, wenn im Channel der App - * eine Event-Nachricht veröffentlicht wird. - * Für Nachrichten von BotUsern wird diese Methode nicht aufgerufen. - */ - onPublicEventMessage?(publicEventMessage: PublicEventMessage): void; - /** - * Diese Methode wird aufgerufen, wenn im Channel der App - * eine öffentliche Handlung durchgeführt wird. - * Für Handlungen von BotUsern wird diese Methode nicht aufgerufen. - */ - onPublicActionMessage?(publicActionMessage: PublicActionMessage): void; - /** - * Diese Methode wird aufgerufen, wenn eine App beendet wird. - * Sobald diese Methode aufgerufen wird, steht nur noch ein begrenzter Teil der API zur Verfügung. - * Die App sollte den kompletten Zustand in der Persistenz speichern, sodass der Zustand - * beim nächsten App/onAppStart:event wiederhergestellt werden kann. - * - * Während des Shutdowns können asynchrone each-Methoden, wie UserPersistenceNumbers/each:method - * und UserAccess/eachAccessibleUser:method nicht zuverlässig genutzt werden. - */ - onShutdown?(): void; - /** - * Diese Methode wird aufgerufen, wenn ein User im Channel der App - * über die Systemfunktionen (/dice, /diceo) würfelt. - * Die App kann auf das Ergebnis zugreifen und die Daten für die Auswertung und Entscheidungen nutzen. - */ - onUserDiced?(diceEvent: DiceEvent): void; - /** - * Diese Methode wird aufgerufen, wenn ein User den Channel der App betritt. - */ - onUserJoined?(user: User): void; - /** - * Diese Methode wird aufgerufen, wenn ein User den Channel der App verlässt. - */ - onUserLeft?(user: User): void; - /** - * Diese Methode wird aufgerufen, wenn aus einer anderen App ein Event mit sendAppEvent versendet wurde. - */ - onAppEventReceived?(appInstance: AppInstance, type: string, data: KnuddelsEvent): void; - /** - * Diese Methode wird aufgerufen, wenn aus dem HTML User Interface ein Event mit - * sendEvent() gesendet wurde. - */ - onEventReceived?(user: User, type: string, data: KnuddelsEvent, appContentSession: AppContentSession): void; - /** - * Diese Methode wird aufgerufen, wenn ein User Knuddel in seinen KnuddelAccount - * eingezahlt hat. - */ - onAccountReceivedKnuddel?(sender: User, receiver: BotUser, knuddelAmount: KnuddelAmount, transferReason: string, knuddelAccount: KnuddelAccount): void; - /** - * Diese Methode wird aufgerufen, wenn sich die Anzahl der Knuddel auf einem KnuddelAccount eines User - * geändert hat. - */ - onAccountChangedKnuddelAmount?(user: User, knuddelAccount: KnuddelAccount, oldKnuddelAmount: KnuddelAmount, newKnuddelAmount: KnuddelAmount): void; - /** - * Ermöglicht das Registrieren eigener Chatbefehle. - * In einem Channel kann nur eine App laufen, die einen bestimmten Chatbefehl nutzt. - * Versucht eine zweite App einen Chatbefehl zu registrieren, den eine andere - * App bereits nutzt, so wird ein Fehler geloggt und die App startet nicht bzw. fährt herunter. - * - * Die Struktur eines registrierten Chatbefehls ist: - * commandName: function (user, params, command) {} - * - * - *
    - *
  • commandName ist der Name der Funktion, wie sie aufgerufen wird (beispielsweise /commandname)
  • - *
  • user ist der Nutzer, der die Funktion aufgerufen hat
  • - *
  • params sind die Parameter, die der Nutzer hinter dem Befehl eingegeben hat (beispielsweise /commandname params)
  • - *
  • command ist der Name des Befehl selbst (beispielsweise commandName)
  • - *
- */ - chatCommands?: { [commandName: string]: (user: User, params: string, command: string) => void }; -} + interface App { + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_mayJoinChannel + */ + mayJoinChannel?( + user: User + ): ChannelJoinPermission; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_mayShowPublicMessage + */ + mayShowPublicMessage?( + publicMessage: PublicMessage + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_mayShowPublicActionMessage + */ + mayShowPublicActionMessage?( + publicActionMessage: PublicActionMessage + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onAppStart + */ + onAppStart?(): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onBeforeKnuddelReceived + */ + onBeforeKnuddelReceived?( + knuddelTransfer: KnuddelTransfer + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onKnuddelReceived + */ + onKnuddelReceived?( + sender: User, + receiver: BotUser, + knuddelAmount: KnuddelAmount, + transferReason: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onPrepareShutdown + */ + onPrepareShutdown?( + secondsTillShutdown: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onPrivateMessage + */ + onPrivateMessage?( + privateMessage: PrivateMessage + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onPublicMessage + */ + onPublicMessage?( + publicMessage: PublicMessage + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onPublicEventMessage + */ + onPublicEventMessage?( + publicEventMessage: PublicEventMessage + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onPublicActionMessage + */ + onPublicActionMessage?( + publicActionMessage: PublicActionMessage + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onShutdown + */ + onShutdown?(): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onUserDiced + */ + onUserDiced?( + diceEvent: DiceEvent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onUserJoined + */ + onUserJoined?( + user: User + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onUserLeft + */ + onUserLeft?( + user: User + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onAppEventReceived + */ + onAppEventReceived?( + appInstance: AppInstance, + type: string, + data: KnuddelsEvent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onEventReceived + */ + onEventReceived?( + user: User, + type: string, + data: KnuddelsEvent, + appContentSession: AppContentSession + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onAccountReceivedKnuddel + */ + onAccountReceivedKnuddel?( + sender: User, + receiver: BotUser, + knuddelAmount: KnuddelAmount, + transferReason: string, + knuddelAccount: KnuddelAccount + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onAccountChangedKnuddelAmount + */ + onAccountChangedKnuddelAmount?( + user: User, + knuddelAccount: KnuddelAccount, + oldKnuddelAmount: KnuddelAmount, + newKnuddelAmount: KnuddelAmount + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onUserDeleted + */ + onUserDeleted?( + userId: number, + userPersistence: UserPersistence + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onDeveloperCommand + * @since AppServer 108662, ChatServer 108662 + */ + onDeveloperCommand?( + user: User, + params: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_mayUserDice + */ + mayUserDice?( + user: User, + diceConfig: DiceConfiguration + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#property_chatCommands + */ + chatCommands?: { [commandName: string]: (user: User, params: string, command: string) => void }; + } -/** - * Ermöglicht Zugriff auf Informationen zu Apps und Events zwischeneinander. - * - * Die Instanz von AppAccess erhält man über den KnuddelsServer - * mit KnuddelsServer.getAppAccess() - */ -declare class AppAccess { /** - * Liefert die Instanz der eigenen App. + * @see https://developer.knuddels.de/docs/classes/AppAccess.html */ - getOwnInstance(): AppInstance; - /** - * Liefert die Instanzen aller anderen Apps, die gerade in diesem Channel laufen. - * @since AppServer 82904 - */ - getAllRunningAppsInChannel(includeSelf?: boolean): AppInstance[]; - /** - * Liefert die Instanzen aller anderen Apps, die gerade in diesem Channel laufen. - * @since AppServer 82904 - */ - getRunningAppInChannel(appId: string): (AppInstance|null); -} + class AppAccess { + /** + * @see https://developer.knuddels.de/docs/classes/AppAccess.html#method_getOwnInstance + */ + getOwnInstance(): AppInstance; + /** + * @see https://developer.knuddels.de/docs/classes/AppAccess.html#method_getAllRunningAppsInChannel + * @since AppServer 82904 + */ + getAllRunningAppsInChannel( + includeSelf?: boolean + ): AppInstance[]; + /** + * @see https://developer.knuddels.de/docs/classes/AppAccess.html#method_getRunningAppInChannel + * @since AppServer 82904 + */ + getRunningAppInChannel( + appId: string + ): (AppInstance|null); + } -/** - * Repräsentiert den visuellen Inhalt einer Applikation, der Usern angezeigt werden soll. - */ -declare class AppContent { /** - * Liefert den AppViewMode. + * @see https://developer.knuddels.de/docs/classes/AppContent.html */ - getAppViewMode(): AppViewMode; - /** - * Liefert das HTMLFile, das beim Anlegen des AppContents - * genutzt wurde. - */ - getHTMLFile(): HTMLFile; - /** - * Liefert die Breite des AppContent. - */ - getWidth(): number; - /** - * Liefert die Höhe des AppContent. - */ - getHeight(): number; - /** - * Liefert die LoadConfiguration, mit der die Optik beim Laden des HTML User Interface beeinflusst werden kann. - */ - getLoadConfiguration(): LoadConfiguration; - /** - * Liefert einen AppContent, der das HTMLFile als Overlay oben rechts im Channel anzeigt. - */ - static overlayContent(htmlFile: HTMLFile, width: number, height: number): AppContent; - /** - * Liefert einen AppContent, der das HTMLFile als Overlay (200x350) oben rechts im Channel anzeigt. - */ - static overlayContent(htmlFile: HTMLFile): AppContent; - /** - * Liefert einen AppContent, der das HTMLFile im Applet/HTML-Chat - * als Popup (300x400) und auf Android als Fullscreen-View anzeigt. - */ - static popupContent(htmlFile: HTMLFile): AppContent; - /** - * Liefert einen AppContent, der das HTMLFile im Applet/HTML-Chat - * als Popup und auf Android als Fullscreen-View anzeigt. - */ - static popupContent(htmlFile: HTMLFile, width: number, height: number): AppContent; - /** - * Sendet Daten an alle Nutzer, die diesen AppContent geöffnet haben. - */ - sendEvent(type: string, data?: KnuddelsEvent): void; - /** - * Liefert eine Liste aller User, die diesen AppContent - * geöffnet haben. - */ - getUsers(): User[]; - /** - * Liefert eine Liste aller AppContentSessions, die dieses AppContent, - * die User gerade geöffnet haben. - */ - getSessions(): AppContentSession[]; - /** - * Ersetzt den AppContent, bei allen Usern, die diesen AppContent - * geöffnet haben durch den neuen AppContent. - * - *

Hinweis: Es können nur AppContent mit demselben AppViewMode - * zum Ersetzen genutzt werden. - */ - replaceWithAppContent(newAppContent: AppContent): void; - /** - * Entfernt diesen AppContent, bei allen Usern, die diesen AppContent - * geöffnet haben. - */ - remove(): void; - /** - * Fügt einen Listener hinzu, der aufgerufen wird, wenn jemand den AppContent schließt. - */ - addCloseListener(callback: { user: User; appContent: AppContent; }): void; -} + class AppContent { + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getAppViewMode + */ + getAppViewMode(): AppViewMode; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getHTMLFile + */ + getHTMLFile(): HTMLFile; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getWidth + */ + getWidth(): number; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getHeight + */ + getHeight(): number; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getLoadConfiguration + */ + getLoadConfiguration(): LoadConfiguration; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_overlayContent + */ + static overlayContent( + htmlFile: HTMLFile, + width: number, + height: number + ): AppContent; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_overlayContent + */ + static overlayContent( + htmlFile: HTMLFile + ): AppContent; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_popupContent + */ + static popupContent( + htmlFile: HTMLFile + ): AppContent; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_popupContent + */ + static popupContent( + htmlFile: HTMLFile, + width: number, + height: number + ): AppContent; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_sendEvent + */ + sendEvent( + type: string, + data?: KnuddelsEvent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getUsers + */ + getUsers(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getSessions + */ + getSessions(): AppContentSession[]; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_replaceWithAppContent + */ + replaceWithAppContent( + newAppContent: AppContent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_remove + */ + remove(): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_addCloseListener + */ + addCloseListener( + callback: { + user: User; + appContent: AppContent; + } + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_setAllowJFXBrowser + */ + setAllowJFXBrowser( + allowJFXBrowser: boolean + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_isAllowJFXBrowser + */ + isAllowJFXBrowser(): boolean; + } -/** - * Repräsentiert den visuellen Inhalt einer App, der einem User angezeigt wird. - */ -declare class AppContentSession { /** - * Sendet Daten an den verbundenen Client. + * @see https://developer.knuddels.de/docs/classes/AppContentSession.html */ - sendEvent(type: string, data?: KnuddelsEvent): void; - /** - * Liefert den AppViewMode. - */ - getAppViewMode(): AppViewMode; - /** - * Entfernt die AppContentSession beim verbundenen User. - */ - remove(): void; - /** - * Liefert den User. - */ - getUser(): User; - /** - * Liefert den verbundenen AppContent. - */ - getAppContent(): AppContent; -} + class AppContentSession { + /** + * @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_sendEvent + */ + sendEvent( + type: string, + data?: KnuddelsEvent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_getAppViewMode + */ + getAppViewMode(): AppViewMode; + /** + * @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_remove + */ + remove(): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_getUser + */ + getUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_getAppContent + */ + getAppContent(): AppContent; + } -/** - * Die Instanz von AppInfo zur laufenden App erhält man über die AppInstance - * mit appInstance.getAppInfo() - */ -declare class AppInfo { /** - * Liefert die AppUid. - * Diese ist für jede Sub-Channel Instanz der App unterschiedlich. - * Wenn RootAppUid == AppUid dann ist dies die Root-App-Instanz. + * @see https://developer.knuddels.de/docs/classes/AppInfo.html */ - getAppUid(): number; - /** - * Liefert die RootAppUid. - * Diese ist für jede Sub-Channel Instanz der App gleich. - * Wenn RootAppUid == AppUid dann ist dies die Root-App-Instanz. - * - * Sie wird für den Link für Auszahlungen aus einem Knuddel-Account benötigt: /knuddelaccount payout:<RootAppUid>:<BETRAG> - */ - getRootAppUid(): number; - /** - * Liefert den in der Konfiguration eingestellten Namen der App. - */ - getAppName(): string; - /** - * Liefert die Version der App, die in der Konfiguration eingestellt wurde. - */ - getAppVersion(): string; - /** - * Liefert die eindeutige Id der App. - * Die appId setzt sich zusammen aus - *
    - *
  • id des Entwicklungsservers
  • - *
  • FTP-Nutzername
  • - *
  • Ordnername der App -> appKey
  • - *
- */ - getAppId(): string; - /** - * Liefert den eindeutigen Key der App. - * Der appKey ist der Ordnername, in dem die App liegt. - */ - getAppKey(): string; - /** - * Liefert den Entwickler der App, falls die serverId knuddelsDE oder knuddelsDEV ist, ansonsten null. - */ - getAppDeveloper(): User; - /** - * Liefert die Liste der AppManager für diese App. Die Channelbesitzer zählen automatisch auch als AppManager. - */ - getAppManagers(): User[]; - /** - * Liefert den Steuersatz, der bei Auszahlung bereits genutzer Knuddel von einem - * KnuddelAccount an einen User - * anfällt. Die anfallenden Steuern werden bei Auszahlung vom BotUser - * abgezogen. - */ - getTaxRate(): number; - /** - * Liefert den KnuddelAmount, der an Steuern anfallen würde, - * wenn alle User jetzt all ihre Knuddel aus ihrem - * KnuddelAccount abheben würden. - */ - getTotalTaxKnuddelAmount(): KnuddelAmount; - /** - * Liefert den KnuddelAmount, der jetzt noch vom - * BotUser an KnuddelAccounts - * übertragen werden kann, so dass für alle Knuddel noch die Steuern bezahlt werden können. - */ - getMaxPayoutKnuddelAmount(): KnuddelAmount; -} + class AppInfo { + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppUid + */ + getAppUid(): number; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getRootAppUid + */ + getRootAppUid(): number; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppName + */ + getAppName(): string; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppVersion + */ + getAppVersion(): string; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppId + */ + getAppId(): string; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppKey + */ + getAppKey(): string; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppDeveloper + */ + getAppDeveloper(): User; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppManagers + */ + getAppManagers(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getTaxRate + */ + getTaxRate(): number; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getTotalTaxKnuddelAmount + */ + getTotalTaxKnuddelAmount(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getMaxPayoutKnuddelAmount + */ + getMaxPayoutKnuddelAmount(): KnuddelAmount; + } -/** - * Repräsentiert die Instanz einer App. - * - * Die eigene Instanz von AppInstance erhält man über das AppAccess-Objekt - * mit appAccess.getOwnInstance() - */ -declare class AppInstance { /** - * Liefert die AppInfo. + * @see https://developer.knuddels.de/docs/classes/AppInstance.html */ - getAppInfo(): AppInfo; - /** - * Sendet ein App-Event an diese App-Instanz. - */ - sendAppEvent(type: string, data: KnuddelsEvent): void; - /** - * Informiert, ob die aktuelle AppInstanz eine Root-Instanz ist. - */ - isRootInstance(): boolean; - /** - * Liefert die Root-Instanz der aktuellen App-Instanz. - */ - getRootInstance(): RootAppInstance; - /** - * Liefert alle App-Instanzen dieser App in diesem Channel und Subchannels. - * Mit includeSelf = false kann man die eigene Instanz ausschließen. - */ - getAllInstances(includeSelf?: boolean): AppInstance[]; - /** - * Liefert den Startzeitpunkt dieser AppInstance. - */ - getStartDate(): Date; - /** - * Liefert die Namen der ChatCommands, die diese AppInstnce derzeit registriert hat. - */ - getRegisteredChatCommandNames(): (string[]|null); - /** - * Liefert den Namen des Channels in dem diese AppInstance läuft. - */ - getChannelName(): string; -} + class AppInstance { + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getAppInfo + */ + getAppInfo(): AppInfo; + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_sendAppEvent + */ + sendAppEvent( + type: string, + data: KnuddelsEvent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_isRootInstance + */ + isRootInstance(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getRootInstance + */ + getRootInstance(): RootAppInstance; + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getAllInstances + */ + getAllInstances( + includeSelf?: boolean + ): AppInstance[]; + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getStartDate + */ + getStartDate(): Date; + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getRegisteredChatCommandNames + */ + getRegisteredChatCommandNames(): (string[]|null); + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getChannelName + */ + getChannelName(): string; + } -/** - * Jede App besitzt eine AppPersistence in der global für diese App - * Informationen gespeichert werden können. An die Instanz der AppPersistence gelangt man durch den Aufruf - * KnuddelsServer.getPersistence();. - */ -declare class AppPersistence extends Persistence { -} + /** + * @see https://developer.knuddels.de/docs/classes/AppPersistence.html + */ + class AppPersistence extends Persistence { + } -/** - * Eine Instanz eines AppProfileEntry repräsentiert einen von einer App erzeugen Profileintrag in Profilen von Usern. - */ -declare class AppProfileEntry { /** - * Liefert den key für den die Topliste, die den Profileintrag erzeugt angelegt wurde. + * @see https://developer.knuddels.de/docs/classes/AppProfileEntry.html */ - getKey(): string; - /** - * Liefert den getDisplayType - */ - getDisplayType(): ToplistDisplayType; - /** - * Liefert das Toplist-Objekt. - */ - getToplist(): Toplist; -} + class AppProfileEntry { + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntry.html#method_getKey + */ + getKey(): string; + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntry.html#method_getDisplayType + */ + getDisplayType(): ToplistDisplayType; + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntry.html#method_getToplist + */ + getToplist(): Toplist; + } -/** - * Mit einer Instanz von AppProfileEntryAccess kann eine App - * AppProfileEntry-Objekte (Profileinträge) erzeugen und verwalten. - * - * Die Instanz für die AppProfileEntryAccess erhält man über das KnuddelsServer-Objekt - * mit KnuddelsServer.getAppProfileEntryAccess() - * - *

Achtung: Derzeit darf eine App bis zu fünf AppProfileEntries haben. - *

Achtung: Profileinträge werden nur dann angezeigt, wenn der Channel sichtbar ist. - */ -declare class AppProfileEntryAccess { /** - * Liefert die Liste aller AppProfileEntry-Objekte, die diese App erzeugt hat. + * @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html */ - getAllProfileEntries(): AppProfileEntry[]; - /** - * Liefert den AppProfileEntry für den übergebenen userPersistenceNumberKey. - */ - getAppProfileEntry(userPersistenceNumberKey: string): AppProfileEntry; - /** - * Erzeugt oder aktualisiert ein AppProfileEntry anhand der übergebenen Toplist - * und dem ToplistDisplayType und liefert den AppProfileEntry im Anschluss zurück. - * - * Profileinträge, die erzeugt werden, sind nur sichtbar, solange die App läuft und werden im Profil ausgeblendet, sofern die App aus ist. - */ - createOrUpdateEntry(toplist: Toplist, toplistDisplayType: ToplistDisplayType): AppProfileEntry; - /** - * Löscht den übergebenen AppProfileEntry. - */ - removeEntry(appProfileEntry: AppProfileEntry): void; -} + class AppProfileEntryAccess { + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html#method_getAllProfileEntries + */ + getAllProfileEntries(): AppProfileEntry[]; + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html#method_getAppProfileEntry + */ + getAppProfileEntry( + userPersistenceNumberKey: string + ): AppProfileEntry; + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html#method_createOrUpdateEntry + */ + createOrUpdateEntry( + toplist: Toplist, + toplistDisplayType: ToplistDisplayType + ): AppProfileEntry; + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html#method_removeEntry + */ + removeEntry( + appProfileEntry: AppProfileEntry + ): void; + } -/** - * Liefert Informationen über einen AppServer. - * - * Die Instanz von AppServerInfo erhält man über den KnuddelsServer - * mit KnuddelsServer.getAppServerInfo() - */ -declare class AppServerInfo extends ServerInfo { -} + /** + * @see https://developer.knuddels.de/docs/classes/AppServerInfo.html + */ + class AppServerInfo extends ServerInfo { + } -/** - * null - */ -declare class AppViewMode { /** - * + * @see https://developer.knuddels.de/docs/classes/AppViewMode.html */ - static readonly Overlay: AppViewMode; - /** - * Zum Öffnen eines Popups durch das HTML User Interface - */ - static readonly Popup: AppViewMode; -} + class AppViewMode { + /** + * @see https://developer.knuddels.de/docs/classes/AppViewMode.html#property_Overlay + */ + static readonly Overlay: AppViewMode; + /** + * @see https://developer.knuddels.de/docs/classes/AppViewMode.html#property_Popup + */ + static readonly Popup: AppViewMode; + } -/** - * Ein BotUser repräsentiert einen Nutzer, der für die App als Nutzer im Channel interagieren kann. - * - * Die Instanz für den Standard-BotUser erhält man über das KnuddelsServer-Objekt - * mit KnuddelsServer.getDefaultBotUser() - */ -declare class BotUser extends User { /** - * Sendet eine öffentliche Nachricht in den Channel. + * @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html */ - sendPublicMessage(message: string): void; - /** - * Sendet eine öffentliche Handlung in den Channel. - * Dies funktioniert so, als ob der BotUser /me TEXT im Chat eingeben würde. - */ - sendPublicActionMessage(actionMessage: string): void; - /** - * Sendet eine private Nachricht an bestimmte Nutzer. - */ - sendPrivateMessage(message: string, users?: User[]): void; - /** - * Sendet eine persistente Nachricht an einen bestimmten Nutzer. - */ - sendPostMessage(topic: string, text: string, receivingUser?: User): void; - /** - * Transferiert eine bestimmte Anzahl Knuddel an einen Zielnutzer oder KnuddelAccount.

- * Wichtiger Hinweis: Sollte die App versuchen mehr Knuddel zu transferieren, - * als sie besitzt, so wird der onError-Callback aufgerufen und die App transferiert so viele Knuddel, wie möglich. - * Zudem werden die Schulden für den Channelbesitzer gemerkt. Sobald sich der Channelbesitzer einloggt, erhält er einen Hinweis über offene Schulden - * und sollte diese direkt begleichen. - * Hat ein Channelbesitzer eine gewisse Menge Schulden angesammelt, so schalten wir alle Apps in diesem Channel ab. - *
Es können nur Knuddel transferiert werden zu Nutzern mit UserType.Human. - */ - transferKnuddel( - receivingUserOrAccount: User | KnuddelAccount, - knuddelAmount: KnuddelAmount, - displayReasonText: string): void; - transferKnuddel( - receivingUserOrAccount: User | KnuddelAccount, - knuddelAmount: KnuddelAmount, - parameters?: { - displayReasonText?: string; - transferDisplayType?: KnuddelTransferDisplayType; - onSuccess?(): void; - onError?(message: string): void; - }): void; -} + class AuthenticityClassification { + /** + * @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#method_getDisplayText + * @since AppServer 94663, ChatServer 94663 + */ + getDisplayText(): string; + /** + * @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#property_ServiceNotAvailable + */ + static readonly ServiceNotAvailable: AuthenticityClassification; + /** + * @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#property_Unknown + */ + static readonly Unknown: AuthenticityClassification; + /** + * @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#property_Trusted + */ + static readonly Trusted: AuthenticityClassification; + /** + * @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#property_VeryTrusted + */ + static readonly VeryTrusted: AuthenticityClassification; + } -/** - * Ein Channel ist ein Raum in dem die App läuft. - * - * Die Instanz für den Channel erhält man über das KnuddelsServer-Objekt - * mit KnuddelsServer.getChannel() - */ -declare class Channel { /** - * Gibt Zugriff auf das ChannelConfiguration-Objekt des Channels. + * @see https://developer.knuddels.de/docs/classes/BotUser.html */ - getChannelConfiguration(): ChannelConfiguration; + class BotUser extends User { + /** + * @see https://developer.knuddels.de/docs/classes/BotUser.html#method_sendPublicMessage + */ + sendPublicMessage( + message: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/BotUser.html#method_sendPublicActionMessage + */ + sendPublicActionMessage( + actionMessage: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/BotUser.html#method_sendPrivateMessage + */ + sendPrivateMessage( + message: string, + users?: User[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/BotUser.html#method_sendPostMessage + */ + sendPostMessage( + topic: string, + text: string, + receivingUser?: User + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/BotUser.html#method_transferKnuddel + */ + transferKnuddel( + receivingUserOrAccount: (User|KnuddelAccount), + knuddelAmount: KnuddelAmount, + parameters?: { + displayReasonText?: string; + transferDisplayType?: KnuddelTransferDisplayType; + onSuccess?: () => void; + onError?: (message: string) => void; + } + ): void; + } + /** - * Gibt Zugriff auf das ChannelRestrictions-Objekt des Channels. + * @see https://developer.knuddels.de/docs/classes/Channel.html */ - getChannelRestrictions(): ChannelRestrictions; + class Channel { + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getChannelConfiguration + */ + getChannelConfiguration(): ChannelConfiguration; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getChannelRestrictions + */ + getChannelRestrictions(): ChannelRestrictions; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getChannelDesign + * @since AppServer 87470, ChatServer 87470 + */ + getChannelDesign(): ChannelDesign; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getOnlineUsers + */ + getOnlineUsers( + ...userType: UserType[] + ): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_isVideoChannel + */ + isVideoChannel(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getVideoChannelData + */ + getVideoChannelData(): VideoChannelData; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getChannelName + */ + getChannelName(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getRootChannelName + */ + getRootChannelName(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getTalkMode + */ + getTalkMode(): ChannelTalkMode; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getAllUsersWithTalkPermission + */ + getAllUsersWithTalkPermission( + ...channelTalkPermission: ChannelTalkPermission[] + ): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_isVisible + * @since AppServer 82202 + */ + isVisible(): boolean; + } + /** - * Gibt Zugriff auf das ChannelDesign-Objekt des Channels. + * @see https://developer.knuddels.de/docs/classes/ChannelConfiguration.html + */ + class ChannelConfiguration { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelConfiguration.html#method_getChannelRights + */ + getChannelRights(): ChannelRights; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelConfiguration.html#method_getChannelInformation + */ + getChannelInformation(): ChannelInformation; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ChannelDesign.html * @since AppServer 87470, ChatServer 87470 */ - getChannelDesign(): ChannelDesign; - /** - * Gibt Zugriff auf Nutzer, die gerade im Channel online sind. - */ - getOnlineUsers(...userType: UserType[]): User[]; - /** - * Liefert die Information, ob in diesem Channel Videos gestreamt werden können. - */ - isVideoChannel(): boolean; - /** - * Liefert die VideoChannelData des Channels. - */ - getVideoChannelData(): VideoChannelData; - /** - * Liefert den Namen des Channels. - */ - getChannelName(): string; - /** - * Liefert den Namen des Root-Channels (nur relevant, falls die App Tochterchannel haben kann). - */ - getRootChannelName(): string; - /** - * Liefert den ChannelTalkMode, in dem sich der Channel gerade befindet. - */ - getTalkMode(): ChannelTalkMode; - /** - * Liefert alle User, die bestimmte ChannelTalkPermissions haben. - */ - getAllUsersWithTalkPermission(...channelTalkPermission: ChannelTalkPermission[]): User[]; - /** - * Liefert die Information, ob der Channel sichtbar (true) oder unsichtbar (false) ist. - * @since AppServer 82202 - */ - isVisible(): boolean; -} + class ChannelDesign { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelDesign.html#method_getDefaultFontSize + * @since AppServer 87470, ChatServer 87470 + */ + getDefaultFontSize(): number; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelDesign.html#method_getDefaultFontColor + * @since AppServer 87470, ChatServer 87470 + */ + getDefaultFontColor(): Color; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelDesign.html#method_getBackgroundColor + * @since AppServer 87470, ChatServer 87470 + */ + getBackgroundColor(): Color; + } -/** - * Eine ChannelConfiguration erlaubt Zugriff auf verschiedene Details - * der Konfiguration des Channels, in dem die App läuft. - * - * Die Instanz für die ChannelConfiguration erhält man über das Channel-Objekt - * mit channel.getChannelConfiguration() - */ -declare class ChannelConfiguration { /** - * Liefert das ChannelRights-Objekt des Channels. + * @see https://developer.knuddels.de/docs/classes/ChannelInformation.html */ - getChannelRights(): ChannelRights; - /** - * Liefert das ChannelInformation-Objekt des Channels. - */ - getChannelInformation(): ChannelInformation; -} + class ChannelInformation { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelInformation.html#method_getTopic + */ + getTopic(): string; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelInformation.html#method_setTopic + */ + setTopic( + topic: string, + showMessage: boolean + ): void; + } -/** - * Ermöglicht Zugriff auf Designeinstellungen des Channels. - * @since AppServer 87470, ChatServer 87470 - */ -declare class ChannelDesign { /** - * Liefert die eingestellte Standard-Schriftgröße des Channels. - * @since AppServer 87470, ChatServer 87470 + * @see https://developer.knuddels.de/docs/classes/ChannelJoinPermission.html */ - getDefaultFontSize(): number; - /** - * Liefert die eingestellte Standard-Schriftfarbe des Channels. - * @since AppServer 87470, ChatServer 87470 - */ - getDefaultFontColor(): Color; - /** - * Liefert die eingestellte Hintergrundfarbe des Channels. - * @since AppServer 87470, ChatServer 87470 - */ - getBackgroundColor(): Color; -} + class ChannelJoinPermission { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelJoinPermission.html#method_accepted + */ + static accepted(): ChannelJoinPermission; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelJoinPermission.html#method_denied + */ + static denied( + denyReason: string + ): ChannelJoinPermission; + } -/** - * Ermöglicht Zugriff auf textuelle Channelinformationen und persistente Änderungen. - */ -declare class ChannelInformation { /** - * Liefert das eingestellte Thema des Channels. + * @see https://developer.knuddels.de/docs/classes/ChannelRestrictions.html */ - getTopic(): string; - /** - * Aktualisiert das Thema das Channels. - */ - setTopic(topic: string, showMessage: boolean): void; -} + class ChannelRestrictions { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelRestrictions.html#method_getMutedUsers + */ + getMutedUsers(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelRestrictions.html#method_getColorMutedUsers + */ + getColorMutedUsers(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelRestrictions.html#method_getLockedUsers + */ + getLockedUsers(): User[]; + } -/** - * Eine Instanz der Klasse ChannelJoinPermission wird als Rückgabewert - * der Methode App.mayJoinChannel(user) benötigt. - * - * Hiermit wird bestimmt, ob der anfragende Nutzer den Channel betreten darf. - * - * Erlauben mit ChannelJoinPermission.accepted() - * Verbieten mit ChannelJoinPermission.denied(denyReason) - */ -declare class ChannelJoinPermission { /** - * Erzeugt ein ChannelJoinPermission-Objekt, das den Zugriff in den Channel erlaubt. + * @see https://developer.knuddels.de/docs/classes/ChannelRights.html */ - static accepted(): ChannelJoinPermission; - /** - * Erzeugt ein ChannelJoinPermission-Objekt, das den Zugriff in den Channel verbietet. - */ - static denied(denyReason: string): ChannelJoinPermission; -} + class ChannelRights { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelRights.html#method_getChannelOwners + */ + getChannelOwners(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelRights.html#method_getChannelModerators + */ + getChannelModerators(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelRights.html#method_getEventModerators + */ + getEventModerators(): User[]; + } -/** - * Eine Instanz von ChannelRestrictions ermöglicht es, aktuelle Informationen über Nutzungsbeschränkungen im Channel zu erhalten. - * - * Die Instanz für die ChannelRestrictions erhält man über das Channel-Objekt - * mit channel.getChannelRestrictions() - */ -declare class ChannelRestrictions { /** - * Liefert alle User die im Channel derzeit für das Schreiben öffentlicher Nachrichten gesperrt sind. + * @see https://developer.knuddels.de/docs/classes/ChannelTalkMode.html */ - getMutedUsers(): User[]; - /** - * Liefert alle User die im Channel derzeit für das Nutzen - * von Farben, Textformatierung und Smileys in öffentlichen Nachrichten gesperrt sind. - */ - getColorMutedUsers(): User[]; - /** - * Liefert alle User die für das Betreten des Channel derzeit gesperrt sind. - */ - getLockedUsers(): User[]; -} + class ChannelTalkMode { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkMode.html#property_Everyone + */ + static readonly Everyone: ChannelTalkMode; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkMode.html#property_OnlyWithTalkPermission + */ + static readonly OnlyWithTalkPermission: ChannelTalkMode; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkMode.html#property_FilteredByModerators + */ + static readonly FilteredByModerators: ChannelTalkMode; + } -/** - * Die Instanz für die ChannelRights erhält man über das ChannelConfiguration-Objekt - * mit channelConfiguration.getChannelRights() - */ -declare class ChannelRights { /** - * Liefert die Liste aller Channelbesitzer. In öffentlichen Channels sind dies alle hauptzuständigen betreuenden Mitglieder. (HZA/HZE) + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html */ - getChannelOwners(): User[]; - /** - * Liefert die Liste aller Channel-Moderatoren. - */ - getChannelModerators(): User[]; - /** - * Liefert die Liste aller Event-Moderatoren. - */ - getEventModerators(): User[]; -} + class ChannelTalkPermission { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_NotInChannel + */ + static readonly NotInChannel: ChannelTalkPermission; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_Default + */ + static readonly Default: ChannelTalkPermission; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_TalkOnce + */ + static readonly TalkOnce: ChannelTalkPermission; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_TalkPermanent + */ + static readonly TalkPermanent: ChannelTalkPermission; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_VIP + */ + static readonly VIP: ChannelTalkPermission; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_Moderator + */ + static readonly Moderator: ChannelTalkPermission; + } -/** - * ChannelTalkMode repräsentiert das den Gesprächsmodus im Channel. - * - * Die Instanz für die ChannelTalkMode erhält man über das Channel-Objekt - * mit channel.getTalkMode() - */ -declare class ChannelTalkMode { /** - * Jeder darf gerade im Channel schreiben. + * @see https://developer.knuddels.de/docs/classes/ChatServerInfo.html */ - static readonly Everyone: ChannelTalkMode; - /** - * Nur Personen, die besondere Rederechte haben dürfen gerade im Channel schreiben. - */ - static readonly OnlyWithTalkPermission: ChannelTalkMode; - /** - * Nur Personen, die besondere Rederechte haben dürfen gerade im Channel schreiben. - * Die Nachrichten aller anderen Nutzer werden gefiltert und ggf. von den Moderatoren zugelassen. - */ - static readonly FilteredByModerators: ChannelTalkMode; -} + class ChatServerInfo extends ServerInfo { + /** + * @see https://developer.knuddels.de/docs/classes/ChatServerInfo.html#method_isTestSystem + */ + isTestSystem(): boolean; + } -/** - * ChannelTalkPermission repräsentiert das Rederecht eines User - * im Channel. - */ -declare class ChannelTalkPermission { /** - * Der User ist gerade nicht im Channel, - * daher ist die ChannelTalkPermission nicht bekannnt. + * @see https://developer.knuddels.de/docs/classes/Client.html */ - static readonly NotInChannel: ChannelTalkPermission; - /** - * Der User hat keine speziellen Rederechte. - * Beim ChannelTalkMode Default können diese User - * Nachrichten verfassen: - */ - static readonly Default: ChannelTalkPermission; - /** - * Der User kann eine öffentliche Nachricht verfassen. Danach wechselt die - * ChannelTalkPermission automatisch auf Default. - */ - static readonly TalkOnce: ChannelTalkPermission; - /** - * Der User kann permanent öffentliche Nachrichten verfassen. - */ - static readonly TalkPermanent: ChannelTalkPermission; - /** - * Der User ist VIP und kann öffentliche Nachrichten verfassen, - * die farbig und groß dargestellt werden. - */ - static readonly VIP: ChannelTalkPermission; - /** - * Der User ist VIP und kann öffentliche Nachrichten verfassen, - * die farbig und groß dargestellt werden. Moderatoren haben zudem weitere Möglichkeiten, die in der - * Anleitung zum Moderationssystem - * nachgelesen werden können. - */ - static readonly Moderator: ChannelTalkPermission; -} + class Client { + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_close + */ + static close(): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_sendEvent + */ + static sendEvent( + type: string, + data: KnuddelsEvent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_executeSlashCommand + */ + static executeSlashCommand( + command: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_includeJS + */ + static includeJS( + ...files: string[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_addEventListener + */ + static addEventListener( + type: string, + callback: (event: {type: string, data: KnuddelsEvent}) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_dispatchEvent + */ + static dispatchEvent( + event: Client.Event + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_removeEventListener + */ + static removeEventListener( + type: string, + callback?: (event: {type: string, data: KnuddelsEvent}) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_includeCSS + */ + static includeCSS( + ...files: string[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_playSound + */ + static playSound( + fileName: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_prefetchSound + */ + static prefetchSound( + fileName: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_freeSound + */ + static freeSound( + fileName: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_getHostFrame + */ + static getHostFrame(): Client.HostFrame; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_getNick + */ + static getNick(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_getClientType + */ + static getClientType(): ClientType; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_getCacheInvalidationId + */ + static getCacheInvalidationId(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_getDirectConnection + */ + static getDirectConnection(): Promise; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_addConnectionTypeChangeListener + */ + static addConnectionTypeChangeListener( + callback: (type: string) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_removeConnectionTypeChangeListener + */ + static removeConnectionTypeChangeListener( + callback: (type: string) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#property_pageData + */ + static pageData: Json; + } -/** - * Liefert Informationen über einen ChatServer. - * - * Die Instanz von ChatServerInfo erhält man über den KnuddelsServer - * mit KnuddelsServer.getChatServerInfo() - */ -declare class ChatServerInfo extends ServerInfo { /** - * Liefert die Information, ob dieser Chat-Server ein Test-System ist. + * @see https://developer.knuddels.de/docs/classes/Client.Color.html */ - isTestSystem(): boolean; -} + namespace Client { + class Color { + /** + * @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_fromRGB + */ + static fromRGB( + red: number, + green: number, + blue: number + ): Color; + /** + * @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_fromHexString + */ + static fromHexString( + colorString: string + ): Color; + /** + * @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_getRed + */ + getRed(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_getGreen + */ + getGreen(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_getBlue + */ + getBlue(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_asHexString + */ + asHexString(): string; + } + } -/** - * Klasse, die es ermöglicht den Client innerhalb des HTML User Interface zu steuern und Daten an den Server zu senden. - */ -declare class Client { /** - * Schließt das HTML User Interface. + * @see https://developer.knuddels.de/docs/classes/Client.Event.html */ - static close(): void; - /** - * Sendet ein Event zum Server, das mit dem AppHook onEventReceived in der App - * abgefangen werden kann. - */ - static sendEvent(type: string, data: KnuddelsEvent): void; - /** - * Sagt dem Chatserver, dass dieser Befehl für den Nutzer, der das HTML User Interface sieht, ausgeführt werden soll. - * Ist der Befehl auf einer Whitelist vom Server, so wird er sofort ausgeführt. Im anderen Falle sieht der Nutzer einen - * Link zum Bestätigen, mit dem er die Aktion starten kann. - * - * Derzeit sind diese Befehle auf der Whitelist: w, info, wc, top, h, dice, d, diceo, w2, serverpp, knuddelaccount, - * /tf-insert, /tf-inserts, /tf-insertb, /tf-insertsb, /tf-override, /tf-overrides, /tf-overrideb, /tf-overridesb, /autotype - */ - static executeSlashCommand(command: string): void; - /** - * Bindet eine Javascript-Datei ein und sorgt dafür, dass immer die aktuellste Version vom Server geladen wird. - */ - static includeJS(...files: string[]): void; - /** - * Registriert sich für ein bestimmtes Event, das vom Server mittels User/sendEvent:method oder vom Client via Client/dispatchEvent:method verschickt wurde. - */ - static addEventListener(type: string, callback: (event: {type: string, data: KnuddelsEvent}) => void): void; - /** - * Sendet ein bestimmtes Event, so dass alle mit Client/addEventListener:method registrierten Listener aufgerufen werden. - */ - static dispatchEvent(event: Client.Event): void; - /** - * Entfernt alle Event-Listener für einen bestimmten Event-Typ. - */ - static removeEventListener(type: string): void; - /** - * Bindet eine CSS-Datei ein und sorgt dafür, dass immer die aktuellste Version vom Server geladen wird. - */ - static includeCSS(...files: string[]): void; - /** - * Spielt einen Sound ab. Der angegebene Dateiname kann hierbei entweder absolut oder relativ zur angezeigten HTML-Datei sein. - * Bisher können nur Dateien mit Wave-Format zuverlässig abgespielt werden. - */ - static playSound(fileName: string): void; - /** - * Lädt einen Sound herunter, damit die Datei später ohne Wartezeit abgespielt werden kann. - * (Android only) - * Der angegebene Dateiname kann hierbei entweder absolut oder relativ zur angezeigten HTML-Datei sein. - */ - static prefetchSound(fileName: string): void; - /** - * Gibt einen Sound wieder frei, der in nächster Zeit vom Client nicht mehr gebraucht wird. - * (Android only) - * Der angegebene Dateiname kann hierbei entweder absolut oder relativ zur angezeigten HTML-Datei sein. - */ - static freeSound(fileName: string): void; - /** - * Liefert den HostFrame des aktuellen Inhalts. - */ - static getHostFrame(): Client.HostFrame; - /** - * Liefert den Nicknamen des Users, der gerade dieses HTML User Interface angezeigt bekommt. - */ - static getNick(): string; - /** - * Liefert den aktuellen ClientType des Nutzers, der gerade dieses HTML User Interface angezeigt bekommt. - */ - static getClientType(): ClientType; - /** - * Liefert die Id, die beim Laden von Skripten und Stylesheets an die URL angehängt wird, um sicherzustellen, dass eine neue Version - * der Datei vom Server geholt wird, statt die Datei aus dem Cache zu laden. - * - * Diese Id kann beim Einbinden eigener Ressourcen zum selben Zweck genutzt werden. - */ - static getCacheInvalidationId(): string; - /** - * Beinhaltet die JSON-Daten, die beim Erstellen des HTMLFile übergeben wurden. - */ - static pageData: Json; -} + namespace Client { + class Event { + /** + * @see https://developer.knuddels.de/docs/classes/Client.Event.html#method_Event + */ + constructor( + type: string, + data: KnuddelsEvent + ); + } + } -/** - * Klasse, mit der clientseitige Farbobjekte erstellt werden können. - */ -declare namespace Client { + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html + */ + namespace Client { + class HostFrame { + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setTitle + */ + setTitle( + newTitle: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setBackgroundColor + */ + setBackgroundColor( + newColor: Color, + durationMillis?: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setIcons + * @since Applet: 9.0bwj, AppServer: 84904 + */ + setIcons( + ...path: string[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setResizable + */ + setResizable( + resizable: boolean + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_focus + * @since Applet: 9.0bwj, AppServer: 84904 + */ + focus(): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setSize + * @since Applet: 9.0bwj, AppServer: 84516 + */ + setSize( + width: number, + height: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_getAppViewMode + * @since Applet: 9.0byl + */ + getAppViewMode(): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_getBrowserType + * @since Applet: 9.0bzp + */ + getBrowserType(): void; + } + } + + /** + * @see https://developer.knuddels.de/docs/classes/ClientType.html + */ + class ClientType { + /** + * @see https://developer.knuddels.de/docs/classes/ClientType.html#property_Applet + */ + static readonly Applet: ClientType; + /** + * @see https://developer.knuddels.de/docs/classes/ClientType.html#property_Browser + */ + static readonly Browser: ClientType; + /** + * @see https://developer.knuddels.de/docs/classes/ClientType.html#property_Android + */ + static readonly Android: ClientType; + /** + * @see https://developer.knuddels.de/docs/classes/ClientType.html#property_IOS + */ + static readonly IOS: ClientType; + /** + * @see https://developer.knuddels.de/docs/classes/ClientType.html#property_Offline + */ + static readonly Offline: ClientType; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Color.html + */ class Color { /** - * Erzeugt ein Color-Objekt mit RGB-Werten. + * @see https://developer.knuddels.de/docs/classes/Color.html#method_fromRGB */ - static fromRGB(red: number, green: number, blue: number): Color; + static fromRGB( + red: number, + green: number, + blue: number + ): Color; /** - * Erzeugt ein Color-Objekt aus einem HexString. + * @see https://developer.knuddels.de/docs/classes/Color.html#method_fromRGBA */ - static fromHexString(colorString: string): Color; + static fromRGBA( + red: number, + green: number, + blue: number, + alpha: number + ): Color; /** - * Liefert den Rot-Anteil der Farbe als Zahl zwischen 0 und 255. + * @see https://developer.knuddels.de/docs/classes/Color.html#method_getAlpha */ - getRed(): number; + getAlpha(): number; /** - * Liefert den Grün-Anteil der Farbe als Zahl zwischen 0 und 255. - */ - getGreen(): number; - /** - * Liefert den Blau-Anteil der Farbe als Zahl zwischen 0 und 255. + * @see https://developer.knuddels.de/docs/classes/Color.html#method_getBlue */ getBlue(): number; /** - * Liefert die Farbe als in CSS nutzbaren HexString. + * @see https://developer.knuddels.de/docs/classes/Color.html#method_getGreen */ - asHexString(): string; + getGreen(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Color.html#method_getRed + */ + getRed(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Color.html#method_toKCode + */ + toKCode(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Color.html#method_asNumber + */ + asNumber(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Color.html#method_fromNumber + */ + static fromNumber( + value: number + ): Color; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Dice.html + */ + class Dice { + /** + * @see https://developer.knuddels.de/docs/classes/Dice.html#method_Dice + */ + constructor( + count: number /* optional */, + value: number + ); + /** + * @see https://developer.knuddels.de/docs/classes/Dice.html#method_getAmount + */ + getAmount(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Dice.html#method_getNumberOfSides + */ + getNumberOfSides(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html + */ + class DiceConfiguration { + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_isUsingOpenThrow + */ + isUsingOpenThrow(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_isUsingPrivateThrow + */ + isUsingPrivateThrow(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_getDices + */ + getDices(): Dice[]; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_equals + */ + equals( + diceConfiguration: DiceConfiguration + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_getChatCommand + * @since AppServer 82248 + */ + getChatCommand(): string; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_toString + * @since AppServer 108781 + */ + toString(): string; + } + + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html + */ + class DiceConfigurationFactory { + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_addDice + */ + addDice( + dice: Dice + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_computeCurrentDiceCount + */ + computeCurrentDiceCount(): number; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_setUseOpenThrow + */ + setUseOpenThrow( + shouldUseOpenThrow: boolean + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_setShouldUsePrivateThrow + */ + setShouldUsePrivateThrow( + shouldUsePrivateThrow: boolean + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_getDiceConfiguration + */ + getDiceConfiguration(): DiceConfiguration; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_fromString + */ + static fromString( + diceConfigurationString: string + ): DiceConfiguration; + } + + /** + * @see https://developer.knuddels.de/docs/classes/DiceEvent.html + */ + class DiceEvent { + /** + * @see https://developer.knuddels.de/docs/classes/DiceEvent.html#method_getUser + */ + getUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/DiceEvent.html#method_getDiceResult + */ + getDiceResult(): DiceResult; + } + + /** + * @see https://developer.knuddels.de/docs/classes/DiceResult.html + */ + class DiceResult { + /** + * @see https://developer.knuddels.de/docs/classes/DiceResult.html#method_getDiceConfiguration + */ + getDiceConfiguration(): DiceConfiguration; + /** + * @see https://developer.knuddels.de/docs/classes/DiceResult.html#method_getSingleDiceResults + */ + getSingleDiceResults(): SingleDiceResult[]; + /** + * @see https://developer.knuddels.de/docs/classes/DiceResult.html#method_totalSum + */ + totalSum(): number; + /** + * @see https://developer.knuddels.de/docs/classes/DiceResult.html#method_toString + * @since AppServer 108781 + */ + toString(): string; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Domain.html + */ + class Domain { + /** + * @see https://developer.knuddels.de/docs/classes/Domain.html#method_getDomainName + */ + getDomainName(): string; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html + */ + class ExternalServerAccess { + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_getAllAccessibleDomains + */ + getAllAccessibleDomains(): Domain[]; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_canAccessURL + */ + canAccessURL( + urlString: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_getURL + */ + getURL( + urlString: string, + parameters?: { + onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + } + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_postURL + */ + postURL( + urlString: string, + parameters?: { + onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + data?: Json; + } + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_touchURL + */ + touchURL( + urlString: string, + parameters?: { + onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + } + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_callURL + */ + callURL( + urlString: string, + parameters?: { + onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + method?: ("GET" | "POST"); + data?: Json; + } + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html + */ + class ExternalServerResponse { + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getURLString + */ + getURLString(): string; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getResponseCode + */ + getResponseCode(): number; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getHeaderFieldNames + * @since AppServer 108668 + */ + getHeaderFieldNames(): string[]; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getHeaderFields + */ + getHeaderFields(): { [key: string]: string[] }; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getHeaderFieldValues + * @since AppServer 108668 + */ + getHeaderFieldValues( + headerFieldName: string + ): string[]; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Gender.html + */ + class Gender { + /** + * @see https://developer.knuddels.de/docs/classes/Gender.html#property_Male + */ + static readonly Male: Gender; + /** + * @see https://developer.knuddels.de/docs/classes/Gender.html#property_Female + */ + static readonly Female: Gender; + /** + * @see https://developer.knuddels.de/docs/classes/Gender.html#property_Unknown + */ + static readonly Unknown: Gender; + } + + /** + * @see https://developer.knuddels.de/docs/classes/HTMLFile.html + */ + class HTMLFile { + /** + * @see https://developer.knuddels.de/docs/classes/HTMLFile.html#method_HTMLFile + */ + constructor( + assetPath: string, + pageData?: Json + ); + /** + * @see https://developer.knuddels.de/docs/classes/HTMLFile.html#method_getAssetPath + */ + getAssetPath(): string; + /** + * @see https://developer.knuddels.de/docs/classes/HTMLFile.html#method_getPageData + */ + getPageData(): Json; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html + */ + class KnuddelAccount { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getKnuddelAmount + */ + getKnuddelAmount(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getKnuddelAmountUsed + */ + getKnuddelAmountUsed(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getKnuddelAmountUnused + */ + getKnuddelAmountUnused(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getTotalKnuddelAmountAppToUser + */ + getTotalKnuddelAmountAppToUser(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getTotalKnuddelAmountUserToApp + */ + getTotalKnuddelAmountUserToApp(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_hasEnough + */ + hasEnough( + knuddelAmount: KnuddelAmount + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getUser + */ + getUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_use + */ + use( + knuddelAmount: KnuddelAmount, + displayReasonText: string, + parameters?: { + transferReason?: string; + onError?: (message: string) => void; + onSuccess?: () => void; + } + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html + */ + class KnuddelAmount { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_KnuddelAmount + */ + constructor( + knuddel: number + ); + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_fromCents + */ + static fromCents( + knuddel: number + ): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_fromKnuddel + */ + static fromKnuddel( + knuddel: number + ): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_getKnuddelCents + */ + getKnuddelCents(): number; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_asNumber + */ + asNumber(): number; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_negate + */ + negate(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_isNegative + */ + isNegative(): boolean; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html + */ + class KnuddelPot { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getId + */ + getId(): number; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getState + */ + getState(): KnuddelPotState; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getKnuddelAmountPerParticipant + */ + getKnuddelAmountPerParticipant(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getKnuddelAmountTotal + */ + getKnuddelAmountTotal(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getParticipants + */ + getParticipants(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getMaxFeeMultiplier + */ + getMaxFeeMultiplier(): number; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_setFee + */ + setFee( + feeUser: BotUser, + feeMultiplier: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getFeeUser + */ + getFeeUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getFeeMultiplier + */ + getFeeMultiplier(): number; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_seal + */ + seal(): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_refund + */ + refund( + reason?: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_addWinner + */ + addWinner( + user: User, + weight?: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_payout + */ + payout( + text?: string + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPotState.html + */ + class KnuddelPotState { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPotState.html#property_Open + */ + static readonly Open: KnuddelPotState; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPotState.html#property_Sealed + */ + static readonly Sealed: KnuddelPotState; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPotState.html#property_Closed + */ + static readonly Closed: KnuddelPotState; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html + */ + class KnuddelTransfer { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_getSender + */ + getSender(): User; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_getReceiver + */ + getReceiver(): BotUser; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_getKnuddelAmount + */ + getKnuddelAmount(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_getTransferReason + */ + getTransferReason(): string; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_reject + */ + reject( + reason: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_accept + */ + accept(): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_canAddToPot + */ + canAddToPot( + pot: KnuddelPot + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_addToPot + */ + addToPot( + knuddelPot: KnuddelPot + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_isProcessed + */ + isProcessed(): boolean; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransferDisplayType.html + */ + class KnuddelTransferDisplayType { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransferDisplayType.html#property_Public + */ + static readonly Public: KnuddelTransferDisplayType; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransferDisplayType.html#property_Private + */ + static readonly Private: KnuddelTransferDisplayType; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransferDisplayType.html#property_Post + */ + static readonly Post: KnuddelTransferDisplayType; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html + */ + class KnuddelsServer { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getDefaultBotUser + */ + static getDefaultBotUser(): BotUser; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getPersistence + */ + static getPersistence(): AppPersistence; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getChannel + */ + static getChannel(): Channel; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getUserAccess + */ + static getUserAccess(): UserAccess; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getPaymentAccess + * @since AppServer 108571, ChatServer 108571 + */ + static getPaymentAccess(): PaymentAccess; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getExternalServerAccess + */ + static getExternalServerAccess(): ExternalServerAccess; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_refreshHooks + */ + static refreshHooks(): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getDefaultLogger + */ + static getDefaultLogger(): Logger; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getFullImagePath + */ + static getFullImagePath( + imageName: string + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getFullSystemImagePath + */ + static getFullSystemImagePath( + imageName: string + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getChatServerInfo + */ + static getChatServerInfo(): ChatServerInfo; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getAppServerInfo + */ + static getAppServerInfo(): AppServerInfo; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getAppAccess + */ + static getAppAccess(): AppAccess; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_createKnuddelPot + */ + static createKnuddelPot( + knuddelAmount: KnuddelAmount, + params?: { + payoutTimeoutMinutes?: number; + shouldSealPot?: (pot: KnuddelPot) => boolean; + onPotSealed?: (pot: KnuddelPot) => void; + } + ): KnuddelPot; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getKnuddelPot + */ + static getKnuddelPot( + id: number + ): (KnuddelPot|null); + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getAllKnuddelPots + */ + static getAllKnuddelPots(): KnuddelPot[]; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getToplistAccess + */ + static getToplistAccess(): ToplistAccess; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getAppProfileEntryAccess + */ + static getAppProfileEntryAccess(): AppProfileEntryAccess; + } + + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html + */ + class LoadConfiguration { + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setBackgroundColor + */ + setBackgroundColor( + color: Color + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setBackgroundImage + */ + setBackgroundImage( + imageUrl: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setText + */ + setText( + text: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setLoadingIndicatorImage + */ + setLoadingIndicatorImage( + imageUrl: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setForegroundColor + */ + setForegroundColor( + color: Color + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setEnabled + */ + setEnabled( + enabled: boolean + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Logger.html + */ + class Logger { + /** + * @see https://developer.knuddels.de/docs/classes/Logger.html#method_debug + */ + debug( + ...msg: any[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Logger.html#method_info + */ + info( + ...msg: any[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Logger.html#method_warn + */ + warn( + ...msg: any[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Logger.html#method_error + */ + error( + ...msg: any[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Logger.html#method_fatal + */ + fatal( + ...msg: any[] + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Message.html + */ + class Message { + /** + * @see https://developer.knuddels.de/docs/classes/Message.html#method_getAuthor + */ + getAuthor(): User; + /** + * @see https://developer.knuddels.de/docs/classes/Message.html#method_getText + */ + getText(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Message.html#method_getCreationDate + */ + getCreationDate(): Date; + } + + /** + * @see https://developer.knuddels.de/docs/classes/OwnAppInstance.html + */ + class OwnAppInstance { + /** + * @see https://developer.knuddels.de/docs/classes/OwnAppInstance.html#method_getOnlineUsers + * @since AppServer 82560 + */ + getOnlineUsers( + otherAppInstance: AppInstance, + ...userType: UserType[] + ): User[]; + } + + /** + * @see https://developer.knuddels.de/docs/classes/PaymentAccess.html + * @since AppServer 108571, ChatServer 108571 + */ + class PaymentAccess { + /** + * @see https://developer.knuddels.de/docs/classes/PaymentAccess.html#method_startKnuddelPurchase + * @since AppServer 108571, ChatServer 108571 + */ + startKnuddelPurchase( + user: User, + amount: KnuddelAmount, + parameters?: { + customMessage?: string; + transferReason?: string; + toAccount?: boolean; + } + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html + */ + class Persistence { + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_hasString + */ + hasString( + key: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_setString + */ + setString( + key: string, + value: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_getString + */ + getString( + key: string, + defaultValue?: string + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_deleteString + */ + deleteString( + key: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_hasNumber + */ + hasNumber( + key: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_setNumber + */ + setNumber( + key: string, + value: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_addNumber + */ + addNumber( + key: string, + value: number + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_getNumber + */ + getNumber( + key: string, + defaultValue?: number + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_deleteNumber + */ + deleteNumber( + key: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_hasObject + */ + hasObject( + key: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_setObject + */ + setObject( + key: string, + object: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable) + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_getObject + */ + getObject( + key: string, + defaultValue?: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable) + ): (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable); + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_deleteObject + */ + deleteObject( + key: string + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/PrivateMessage.html + */ + class PrivateMessage extends Message { + /** + * @see https://developer.knuddels.de/docs/classes/PrivateMessage.html#method_getReceivingUsers + */ + getReceivingUsers(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/PrivateMessage.html#method_sendReply + */ + sendReply( + text: string + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/PublicActionMessage.html + */ + class PublicActionMessage extends Message { + } + + /** + * @see https://developer.knuddels.de/docs/classes/PublicEventMessage.html + */ + class PublicEventMessage extends Message { + } + + /** + * @see https://developer.knuddels.de/docs/classes/PublicMessage.html + */ + class PublicMessage extends Message { + } + + /** + * @see https://developer.knuddels.de/docs/classes/Quest.html + */ + class Quest { + /** + * @see https://developer.knuddels.de/docs/classes/Quest.html#method_setSolved + * @since AppServer 82290, ChatServer 82290 + */ + setSolved( + count?: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Quest.html#method_getQuestKey + * @since AppServer 82290, ChatServer 82290 + */ + getQuestKey(): string; + } + + /** + * @see https://developer.knuddels.de/docs/classes/QuestAccess.html + */ + class QuestAccess { + /** + * @see https://developer.knuddels.de/docs/classes/QuestAccess.html#method_getQuests + * @since AppServer 82290, ChatServer 82290 + */ + getQuests(): Quest[]; + /** + * @see https://developer.knuddels.de/docs/classes/QuestAccess.html#method_hasQuest + * @since AppServer 82290, ChatServer 82290 + */ + hasQuest( + questKey: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/QuestAccess.html#method_getQuest + * @since AppServer 82290, ChatServer 82290 + */ + getQuest( + questKey: string + ): (Quest|null); + /** + * @see https://developer.knuddels.de/docs/classes/QuestAccess.html#method_getUser + * @since AppServer 82290, ChatServer 82290 + */ + getUser(): User; + } + + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html + */ + class RandomOperations { + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_nextInt + */ + static nextInt( + minValue: number /* optional */, + maxValue: number + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_nextInts + */ + static nextInts( + minValue: number /* optional */, + maxValue: number, + count: number, + onlyDifferentNumbers: boolean + ): number[]; + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_flipTrue + */ + static flipTrue( + truePropability: number + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_getRandomObject + */ + static getRandomObject( + objects: T[] + ): T; + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_shuffleObjects + */ + static shuffleObjects( + objects: T[] + ): T[]; + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_getRandomString + * @since AppServer 92699 + */ + static getRandomString( + length: number, + allowedCharacters?: string + ): string; + } + + /** + * @see https://developer.knuddels.de/docs/classes/RootAppInstance.html + */ + class RootAppInstance extends AppInstance { + /** + * @see https://developer.knuddels.de/docs/classes/RootAppInstance.html#method_updateApp + */ + updateApp( + message: string /* optional */, + logMessage?: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/RootAppInstance.html#method_cancelUpdateApp + * @since AppServer 98117 + */ + cancelUpdateApp(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/RootAppInstance.html#method_stopApp + */ + stopApp( + message: string /* optional */, + logMessage?: string + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ServerInfo.html + */ + class ServerInfo { + /** + * @see https://developer.knuddels.de/docs/classes/ServerInfo.html#method_getServerId + */ + getServerId(): string; + /** + * @see https://developer.knuddels.de/docs/classes/ServerInfo.html#method_getRevision + */ + getRevision(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/SingleDiceResult.html + */ + class SingleDiceResult { + /** + * @see https://developer.knuddels.de/docs/classes/SingleDiceResult.html#method_getDice + */ + getDice(): Dice; + /** + * @see https://developer.knuddels.de/docs/classes/SingleDiceResult.html#method_valuesRolled + */ + valuesRolled(): number[]; + /** + * @see https://developer.knuddels.de/docs/classes/SingleDiceResult.html#method_sum + */ + sum(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/String.html + */ + interface String { + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_escapeKCode + */ + escapeKCode(): string; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_stripKCode + */ + stripKCode(): string; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_startsWith + */ + startsWith( + prefix: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_endsWith + */ + endsWith( + suffix: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_getPixelWidth + */ + getPixelWidth( + fontSize: number, + isBold: boolean + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_limitString + */ + limitString( + fontSize: number, + isBold: boolean, + maxPixelWidth: number, + abbreviationMarker?: string + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_contains + */ + contains( + needle: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_minimalConversionCost + * @since AppServer 82271 + */ + minimalConversionCost( + otherString: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_hasOnlyNicknameCharacters + * @since AppServer 82271 + */ + hasOnlyNicknameCharacters(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_hasOnlyDigits + * @since AppServer 82271 + */ + hasOnlyDigits(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_hasOnlyAlphanumericalAndWhitespaceCharacters + * @since AppServer 82271 + */ + hasOnlyAlphanumericalAndWhitespaceCharacters(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_isEmpty + * @since AppServer 92695 + */ + isEmpty(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_toCamelCase + * @since AppServer 92695 + */ + toCamelCase(): string; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_capitalize + * @since AppServer 92695 + */ + capitalize(): string; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_replaceAll + */ + replaceAll( + search: string|RegExp, + replacement: string + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_isOk + * @since ChatServer 82262, AppServer 82262 + */ + isOk(): boolean; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html + */ + class Toplist { + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_getUserPersistenceNumberKey + */ + getUserPersistenceNumberKey(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_getDisplayName + */ + getDisplayName(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_getChatCommand + */ + getChatCommand( + user_or_userId?: (User|number) + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_getLabel + */ + getLabel( + user_or_userId: (User|number) + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_addLabelChangeListener + */ + addLabelChangeListener( + listener: (labelChangeEvent: ToplistLabelChangeEvent) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_removeLabelChangeListener + */ + removeLabelChangeListener( + listener: (labelChangeEvent: ToplistLabelChangeEvent) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_addRankChangeListener + */ + addRankChangeListener( + listener: (rankChangeEvent: ToplistRankChangeEvent) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_removeRankChangeListener + */ + removeRankChangeListener( + listener: (rankChangeEvent: ToplistRankChangeEvent) => void + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ToplistAccess.html + */ + class ToplistAccess { + /** + * @see https://developer.knuddels.de/docs/classes/ToplistAccess.html#method_getAllToplists + */ + getAllToplists(): Toplist[]; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistAccess.html#method_getToplist + */ + getToplist( + userPersistenceNumberKey: string + ): Toplist; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistAccess.html#method_removeToplist + */ + removeToplist( + toplist: Toplist + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistAccess.html#method_createOrUpdateToplist + */ + createOrUpdateToplist( + userPersistenceNumberKey: string, + displayName: string, + parameters?: { + labelMapping?: { [minValue: string]: string }; + ascending?: boolean; + } + ): Toplist; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html + */ + class ToplistDisplayType { + /** + * @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html#property_Label + */ + static readonly Label: ToplistDisplayType; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html#property_Value + */ + static readonly Value: ToplistDisplayType; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html#property_LabelAndRank + */ + static readonly LabelAndRank: ToplistDisplayType; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html#property_ValueAndRank + */ + static readonly ValueAndRank: ToplistDisplayType; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html + */ + class ToplistLabelChangeEvent { + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getToplist + */ + getToplist(): Toplist; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getOldLabel + */ + getOldLabel(): string; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getNewLabel + */ + getNewLabel(): string; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getUser + */ + getUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getOldValue + */ + getOldValue(): number; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getNewValue + */ + getNewValue(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html + */ + class ToplistRankChangeEvent { + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getToplist + */ + getToplist(): Toplist; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getOldRank + */ + getOldRank(): number; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getNewRank + */ + getNewRank(): number; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getUser + */ + getUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getUsersOvertook + */ + getUsersOvertook(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getOldValue + */ + getOldValue(): number; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getNewValue + */ + getNewValue(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/User.html + */ + class User { + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getUserId + */ + getUserId(): number; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getNick + */ + getNick(): string; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getAge + */ + getAge(): number; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getGender + */ + getGender(): Gender; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getRegDate + */ + getRegDate(): Date; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getUserStatus + */ + getUserStatus(): UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getUserType + */ + getUserType(): UserType; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getClientType + */ + getClientType(): ClientType; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_canShowAppViewMode + */ + canShowAppViewMode( + mode: AppViewMode + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_canSendAppContent + */ + canSendAppContent( + appContent: AppContent + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isInTeam + */ + isInTeam( + teamName: string, + subTeamName?: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getPersistence + */ + getPersistence(): UserPersistence; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_sendPrivateMessage + */ + sendPrivateMessage( + message: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_sendPostMessage + */ + sendPostMessage( + topic: string, + text: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isChannelOwner + */ + isChannelOwner(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isLikingChannel + */ + isLikingChannel(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isChannelCoreUser + * @since AppServer 92701, ChatServer 92701 + */ + isChannelCoreUser(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isAppManager + */ + isAppManager(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isMuted + */ + isMuted(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isColorMuted + */ + isColorMuted(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isLocked + */ + isLocked(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isChannelModerator + */ + isChannelModerator(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isEventModerator + */ + isEventModerator(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isAppDeveloper + */ + isAppDeveloper(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getProfileLink + */ + getProfileLink( + displayText?: string + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isOnlineInChannel + */ + isOnlineInChannel(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getKnuddelAmount + */ + getKnuddelAmount(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isOnline + */ + isOnline(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getReadme + */ + getReadme(): string; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getOnlineMinutes + */ + getOnlineMinutes(): number; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isAway + */ + isAway(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_hasProfilePhoto + */ + hasProfilePhoto(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_sendAppContent + */ + sendAppContent( + appContent: AppContent + ): AppContentSession; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getAppContentSessions + */ + getAppContentSessions(): AppContentSession[]; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getAppContentSession + */ + getAppContentSession( + appViewMode: AppViewMode + ): AppContentSession; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_equals + */ + equals( + user: User + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getProfilePhoto + */ + getProfilePhoto( + width: number, + height: number + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getQuestAccess + * @since AppServer 82290, ChatServer 82290 + */ + getQuestAccess(): QuestAccess; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isStreamingVideo + */ + isStreamingVideo(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getKnuddelAccount + */ + getKnuddelAccount(): KnuddelAccount; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getChannelTalkPermission + */ + getChannelTalkPermission(): ChannelTalkPermission; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isProfilePhotoVerified + */ + isProfilePhotoVerified(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isAgeVerified + */ + isAgeVerified(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_addNicklistIcon + */ + addNicklistIcon( + imagePath: string, + imageWidth: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_removeNicklistIcon + */ + removeNicklistIcon( + imagePath: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_triggerDice + * @since AppServer 89159, ChatServer 89159 + */ + triggerDice( + diceConfiguration: DiceConfiguration + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getAuthenticityClassification + * @since AppServer 94663, ChatServer 94663 + */ + getAuthenticityClassification(): AuthenticityClassification; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html + */ + class UserAccess { + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_getUserId + */ + getUserId( + nick: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_exists + */ + exists( + nick: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_isUserDeleted + */ + isUserDeleted( + userId: number + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_mayAccess + */ + mayAccess( + userId: number + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_getUserById + */ + getUserById( + userId: number + ): User; + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_getNick + */ + getNick( + userId: number + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_eachAccessibleUser + */ + eachAccessibleUser( + callback: (user: User, index: number, accessibleUserCount: number, key?: string) => boolean, + parameters?: { + onStart?: (accessibleUserCount: number, key?: string) => void; + onEnd?: (accessibleUserCount: number, key?: string) => void; + } + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistence.html + */ + class UserPersistence extends Persistence { + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistence.html#method_deleteAllNumbers + * @since AppServer 88569 + */ + deleteAllNumbers(): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistence.html#method_deleteAllObjects + * @since AppServer 88569 + */ + deleteAllObjects(): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistence.html#method_deleteAllStrings + * @since AppServer 88569 + */ + deleteAllStrings(): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistence.html#method_deleteAll + * @since AppServer 88569 + */ + deleteAll(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html + */ + class UserPersistenceNumberEntry { + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html#method_getUser + */ + getUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html#method_getValue + */ + getValue(): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html#method_getRank + */ + getRank(): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html#method_getPosition + */ + getPosition(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html + */ + class UserPersistenceNumbers { + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getSum + */ + static getSum( + key: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_deleteAll + */ + static deleteAll( + key: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getCount + */ + static getCount( + key: string, + parameters?: { + minimumValue?: number; + maximumValue?: number; + } + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_updateKey + */ + static updateKey( + oldKeyName: string, + newKeyName: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_updateValue + */ + static updateValue( + key: string, + oldValue: number, + newValue: number + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_addNumber + */ + static addNumber( + key: string, + value: number, + parameters?: { + minimumValue?: number; + maximumValue?: number; + targetUsers?: User[]; + } + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getSortedEntries + */ + static getSortedEntries( + key: string, + parameters?: { + ascending?: boolean; + count?: number; + page?: number; + minimumValue?: number; + maximumValue?: number; + } + ): UserPersistenceNumberEntry[]; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getSortedEntriesAdjacent + */ + static getSortedEntriesAdjacent( + key: string, + user_or_userId: (User|number), + parameters?: { + ascending?: boolean; + count?: number; + } + ): UserPersistenceNumberEntry[]; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getPosition + */ + static getPosition( + key: string, + user_or_userId: (User|number), + parameters?: { + ascending?: boolean; + minimumValue?: number; + } + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getRank + */ + static getRank( + key: string, + user_or_userId: (User|number), + parameters?: { + ascending?: boolean; + minimumValue?: number; + } + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_each + */ + static each( + key: string, + callback: (user: User, value: number, index: number, totalCount: number, key: string) => boolean, + parameters?: { + ascending?: boolean; + minimumValue?: number; + maximumValue?: number; + maximumCount?: number; + onStart?: (totalCount: number, key: string) => void; + onEnd?: (totalCount: number, key: string) => void; + } + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getAllKeys + * @since AppServer 82483 + */ + static getAllKeys( + filterKey?: string + ): string[]; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceObjects.html + */ + class UserPersistenceObjects { + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceObjects.html#method_deleteAll + * @since AppServer 82478 + */ + static deleteAll( + key: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceObjects.html#method_getAllKeys + * @since AppServer 82483 + */ + static getAllKeys( + filterKey?: string + ): string[]; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceStrings.html + */ + class UserPersistenceStrings { + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceStrings.html#method_exists + * @since AppServer 88571 + */ + static exists( + key: string, + value: string, + ignoreCase?: boolean + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceStrings.html#method_deleteAll + * @since AppServer 82478 + */ + static deleteAll( + key: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceStrings.html#method_getAllKeys + * @since AppServer 82483 + */ + static getAllKeys( + filterKey?: string + ): string[]; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html + */ + class UserStatus { + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#method_getNumericStatus + */ + getNumericStatus(): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#method_isAtLeast + */ + isAtLeast( + otherUserStatus: UserStatus + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Newbie + */ + static readonly Newbie: UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Family + */ + static readonly Family: UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Stammi + */ + static readonly Stammi: UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_HonoryMember + */ + static readonly HonoryMember: UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Admin + */ + static readonly Admin: UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_SystemBot + */ + static readonly SystemBot: UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Sysadmin + */ + static readonly Sysadmin: UserStatus; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserType.html + */ + class UserType { + /** + * @see https://developer.knuddels.de/docs/classes/UserType.html#property_AppBot + */ + static readonly AppBot: UserType; + /** + * @see https://developer.knuddels.de/docs/classes/UserType.html#property_SystemBot + */ + static readonly SystemBot: UserType; + /** + * @see https://developer.knuddels.de/docs/classes/UserType.html#property_Human + */ + static readonly Human: UserType; + } + + /** + * @see https://developer.knuddels.de/docs/classes/VideoChannelData.html + */ + class VideoChannelData { + /** + * @see https://developer.knuddels.de/docs/classes/VideoChannelData.html#method_getStreamingVideoUsers + */ + getStreamingVideoUsers(): User[]; } } - -/** - * Klasse, die es ermöglicht ein Event via Client/dispatchEvent:method zu versenden. - */ -declare namespace Client { - class Event { - /** - * Erzeugt ein Event. - */ - constructor(type: string, data: KnuddelsEvent); - } -} - -/** - * Klasse, die es ermöglicht den Inhalte zu steuern, die im Bereich liegen, der das HTML User Interface hostet. - */ -declare namespace Client { - class HostFrame { - /** - * Setzt den Titel der Seite im gezoomten Modus (nur Android). - */ - setTitle(newTitle: string): void; - /** - * Ändert die sichtbare Hintergrundfarbe des Hostframes animiert. (Android-only) - */ - setBackgroundColor(newColor: Color, durationMillis?: number): void; - /** - * Setzt die Icons, die als Fenster-Icon angezeigt werden sollen. (Applet-only, nur mit AppViewMode.Popup) - * Die Bilder müssen von groß nach klein sortiert sein. Die größeren Bilder werden (je nach System) automatisch dann eingesetzt, - * wenn größere Bilder benötigt werden (z.B. in der Task-Leiste, oder beim Alt+Tab Fenster-Wechsel). - * @since Applet: 9.0bwj, AppServer: 84904 - */ - setIcons(...path: string[]): void; - /** - * Setzt, ob das Fenster resizable ist. (Applet-only, nur mit AppViewMode.Popup) - */ - setResizable(resizable: boolean): void; - /** - * Bringt das Fenster der App (App-Popup bzw. Chat-Fenster) in den Vordergrund. (Applet-only) - * @since Applet: 9.0bwj, AppServer: 84904 - */ - focus(): void; - /** - * Ändert die Größe des App-Fensters (AppViewMode.Popup) bzw. App-Overlays (AppViewMode.Overlay). - * @since Applet: 9.0bwj, AppServer: 84516 - */ - setSize(width: number, height: number): void; - } -} - -/** - * ClientType repräsentiert die Art der Chat-Verbindung des Users. - * - * Eine Instanz von ClientType erhält man über das User-Objekt - * mit user.getClientType() - */ -declare class ClientType { - /** - * Der User ist mit dem Java Applet im Chat. - */ - static readonly Applet: ClientType; - /** - * Der User ist mit dem Browser im Chat (Mini-Chat, HTML-Chat). - */ - static readonly Browser: ClientType; - /** - * Der User ist mit der Android-App im Chat. - */ - static readonly Android: ClientType; - /** - * Der User ist mit der iOS-App im Chat. - */ - static readonly IOS: ClientType; - /** - * Der User ist nicht im Chat. - */ - static readonly Offline: ClientType; -} - -/** - * Klasse, mit der serverseitige Farbobjekte erstellt werden können. - */ -declare class Color { - /** - * Erzeugt ein serverseitiges Color-Objekt mit RGB-Werten. - * Als Alpha-Wert wird automatisch 255 genutzt. - */ - static fromRGB(red: number, green: number, blue: number): Color; - /** - * Erzeugt ein serverseitiges Color-Objekt mit RGBA-Werten. - */ - static fromRGBA(red: number, green: number, blue: number, alpha: number): Color; - /** - * Liefert den Alpha-Wert der Farbe als Zahl zwischen 0 und 255. - */ - getAlpha(): number; - /** - * Liefert den Blau-Anteil der Farbe als Zahl zwischen 0 und 255. - */ - getBlue(): number; - /** - * Liefert den Grün-Anteil der Farbe als Zahl zwischen 0 und 255. - */ - getGreen(): number; - /** - * Liefert den Rot-Anteil der Farbe als Zahl zwischen 0 und 255. - */ - getRed(): number; - /** - * Liefert die Farbe als KCode zurück. - */ - toKCode(): string; - /** - * Liefert die numerische Repräsentation der Farbe zurück. - */ - asNumber(): number; - /** - * Erzeugt ein serverseitiges Color-Objekt aus der numerischen Repräsentation einer Farbe. - */ - static fromNumber(value: number): Color; -} - -/** - * Eine Instanz von Dice repräsentiert die Anzahl an Würfeln von einerm bestimmten Typ. - */ -declare class Dice { - /** - * Erzeugt ein Dice-Objekt mit der übergebenen Anzahl Würfel und Augenzahl. - */ - constructor(count: number /* optional */, value: number); - /** - * Liefert die Anzahl der Würfel. - */ - getAmount(): number; - /** - * Liefert die Anzahl der Seiten der Würfel. - */ - getNumberOfSides(): number; -} - -/** - * Eine Instanz von DiceConfiguration repräsentiert eindeutig eine Konfiguration zum würfeln. - * Wurde gewürfelt, so können die Konfigurationen verglichen werden, um zu prüfen, ob exakt die Würfel - * gewürfelt wurden, die gewürfelt werden sollten. - */ -declare class DiceConfiguration { - /** - * Informiert, ob es sich um einen offenen Würfelwurf handelt. - * Offene Würfelwürfe sind speziell. Falls die Augenzahl des Würfels die Maximalsumme zeigt, - * so wird noch einmal gewürfelt und die neue Zahl dazu addiert, solange bis der Würfel - * nicht mehr die Maximalsumme zeigt. - * - * Beispiel: /diceo 1w4 -> 4 -> 4 -> 3 = 11 - */ - isUsingOpenThrow(): boolean; - /** - * Informiert darüber, ob die Würfel privat geworfen worden sind. - * Würfelwürfe zählen als privat, wenn am Ende des Würfelbefehls ein Ausrufezeichen steht. - * Beispiel: /dice 10w2! - */ - isUsingPrivateThrow(): boolean; - /** - * Liefert ein Array mit Würfeln, mit denen gewürfelt wurde. - */ - getDices(): Dice[]; - /** - * Vergleicht, ob zwei Konfigurationen inhaltlich identisch sind - */ - equals(diceConfiguration: DiceConfiguration): boolean; - /** - * Liefert den Befehl, der im Chat eingegeben werden kann, um einen Wurf auszuführen, - * der zur DiceConfiguration passt. - * @since AppServer 82248 - */ - getChatCommand(): string; -} - -/** - * Eine Instanz einer DiceConfigurationFactory kann zur Unterstützung genutzt werden, um eine - * DiceConfiguration zu erzeugen. - */ -declare class DiceConfigurationFactory { - /** - * Fügt der Konfiguration einen Würfel hinzu. - */ - addDice(dice: Dice): void; - /** - * Liefert die Anzahl der Würfel, die zur Konfiguration gehören. - */ - computeCurrentDiceCount(): number; - /** - * Setzt die Information, ob ein offener Wurf oder ein normaler Wurf stattfinden soll. - * Offene Würfelwürfe sind speziell. Falls die Augenzahl des Würfels die Maximalsumme zeigt, - * so wird noch einmal gewürfelt und die neue Zahl dazu addiert, solange bis der Würfel - * nicht mehr die Maximalsumme zeigt. - * - * Beispiel: /diceo 1w4 -> 4 -> 4 -> 3 = 11 - */ - setUseOpenThrow(shouldUseOpenThrow: boolean): void; - /** - * Setzt die Information, ob der Würfelwurf privat stattfinden soll. - */ - setShouldUsePrivateThrow(shouldUsePrivateThrow: boolean): void; - /** - * Liefert die erzeugte Würfelkonfiguration. - */ - getDiceConfiguration(): DiceConfiguration; - /** - * Erzeugt eine Würfelkonfiguration. - */ - static fromString(diceConfigurationString: string): DiceConfiguration; -} - -/** - * Wird in der App die Methode onUserDiced überschrieben, so erhält diese bei jedem Würfelwurf ein DiceEvent. - * Ein DiceEvent ermöglicht einem detaillierte Informationen rund um diesen Würfelwurf in Erfahrung zu bringen. - */ -declare class DiceEvent { - /** - * Liefert den Nutzer, der gewürfelt hat. - */ - getUser(): User; - /** - * Liefert das DiceResult des Würfelwurfs. - */ - getDiceResult(): DiceResult; -} - -/** - * Ein DiceResult beinhaltet konkrete Informationen über einen Würfelwurf. - */ -declare class DiceResult { - /** - * Liefert die Konfiguration mit der gewürfelt wurde. - */ - getDiceConfiguration(): DiceConfiguration; - /** - * Liefert ein Array mit Details zu den einzelnen Ergebnissen pro Würfeltyp. - */ - getSingleDiceResults(): SingleDiceResult[]; - /** - * Liefert die Summe der Augenzahlen aller Würfel - */ - totalSum(): number; -} - -/** - * Die Instanz einer Domain beinhaltet alle relevanten Informationen zur Domain. - */ -declare class Domain { - /** - * Liefert ein den Domain-Namen der aktuellen Domain. - */ - getDomainName(): string; -} - -/** - * Die Instanz von ExternalServerAccess erhält man über die KnuddelsServer.getExternalServerAccess(). - * Damit der Zugriff auf einen externern Server funktioniert, muss auf dem Server eine Datei knuddelsAccess.txt abgelegt werden, die die FTP-User-ID des Entwicklers enthält. - */ -declare class ExternalServerAccess { - /** - * Liefert eine Liste aller zugreifbaren Domains - */ - getAllAccessibleDomains(): Domain[]; - /** - * Prüft den Zugriff auf eine bestimmte URL. Wird je Kombination von "Protokoll + Host + Port" geprüft.
- * Beispiel: http://www.example.de:8080 - */ - canAccessURL(urlString: string): boolean; - /** - * Macht einen GET-Request auf die übergebene URL und liefert den Inhalt zurück. - * Diese Methode ist eine Convenience-Methode für externalServerAccess.callURL(). - */ - getURL( - urlString: string, - parameters?: { - onSuccess?(responseData: string, externalServerResponse: ExternalServerResponse): void; - onFailure?(responseData: string, externalServerResponse: ExternalServerResponse): void; - }): void; - /** - * Macht einen POST-Request auf die übergebene URL und liefert den Inhalt zurück. - * Diese Methode ist eine Convenience-Methode für externalServerAccess.callURL(). - */ - postURL( - urlString: string, - parameters?: { - onSuccess?(responseData: string, externalServerResponse: ExternalServerResponse): void; - onFailure?(responseData: string, externalServerResponse: ExternalServerResponse): void; - data?: Json; - }): void; - /** - * Macht einen GET-Request auf die übergebene URL. Im Gegensatz zum GET-Request wird der Inhalt der Webseite wird nicht ausgelesen. - * Aus diesem Grund ist diese Methode schneller. - * Diese Methode ist eine Convenience-Methode für externalServerAccess.callURL(). - */ - touchURL( - urlString: string, - parameters?: { - onSuccess?(responseData: string, externalServerResponse: ExternalServerResponse): void; - onFailure?(responseData: string, externalServerResponse: ExternalServerResponse): void; - }): void; - /** - * Macht einen Request auf die übergebene URL. - */ - callURL( - urlString: string, - parameters?: { - onSuccess?(responseData: string, externalServerResponse: ExternalServerResponse): void; - onFailure?(responseData: string, externalServerResponse: ExternalServerResponse): void; - method?: ("GET" | "POST"); - data?: Json; - }): void; -} - -/** - * Die Instanz von ExternalServerResponse erhält in den onSuccess- und onFailure-Callbacks der Methoden von - * ExternalServerAccess. Es enthält alle notwendigen Daten zum Verarbeiten. - */ -declare class ExternalServerResponse { - /** - * Liefert die abgefragte URL. - */ - getURLString(): string; - /** - * Liefert den HTTP-Statuscode der Seite. - */ - getResponseCode(): number; - /** - * Liefert ein Objekt, das die Headerdaten der Antwort enthält. - */ - getHeaderFields(): { [key: string]: string[] }; -} - -/** - * Gender repräsentiert das Geschlecht eines User. - */ -declare class Gender { - /** - * Das Geschlecht ist männlich. - */ - static readonly Male: Gender; - /** - * Das Geschlecht ist weiblich. - */ - static readonly Female: Gender; - /** - * Das Geschlecht ist nicht bekannt. - */ - static readonly Unknown: Gender; -} - -/** - * Repräsentiert eine HTML-Datei, die auf dem Server im Ordner /www liegt. - */ -declare class HTMLFile { - /** - * - */ - constructor(assetPath: string, pageData?: Json); - /** - * Liefert den Pfad, der beim Anlegen der HTMLFile-Instanz genutzt wurde. - */ - getAssetPath(): string; - /** - * Liefert die pageData, die beim Anlegen der HTMLFile-Instanz genutzt wurden. - */ - getPageData(): Json; -} - -/** - * Eine Instanz von KnuddelAccount ermöglicht den Zugriff auf die freigegebenen Knuddel - * eines bestimmten User. Knuddel können abgezogen und addiert werden. - */ -declare class KnuddelAccount { - /** - * Liefert den KnuddelAmount eines Users, - * über den die App gerade frei verfügen kann. - */ - getKnuddelAmount(): KnuddelAmount; - /** - * Liefert den KnuddelAmount aus dem KnuddelAccount, - * der bereits von der App genutzt wurde. - * Beim Auszahlen dieser Knuddel aus dem KnuddelAccount an den - * User fallen Steuern an. - */ - getKnuddelAmountUsed(): KnuddelAmount; - /** - * Liefert den KnuddelAmount aus dem KnuddelAccount, - * der noch nicht von der App genutzt wurde. - * Beim Auszahlen dieser Knuddel aus dem KnuddelAccount an den - * User fallen keine Steuern an. - */ - getKnuddelAmountUnused(): KnuddelAmount; - /** - * Liefert die Summe aller Transfers, die die App an diesen KnuddelAccount bzw. User überwiesen hat. - */ - getTotalKnuddelAmountAppToUser(): KnuddelAmount; - /** - * Liefert die Summe aller Transfers, die die App von diesem KnuddelAccount bzw. User abgebucht/erhalten hat. - */ - getTotalKnuddelAmountUserToApp(): KnuddelAmount; - /** - * Liefert die Information, ob in diesem Moment genug Knuddel verfügbar sind. - */ - hasEnough(knuddelAmount: KnuddelAmount): boolean; - /** - * Liefert den Nutzer, dem der KnuddelAccount gehört. - */ - getUser(): User; - /** - * Versucht eine bestimmte Menge Knuddel zu verwenden. Dies ist nur möglich, wenn der User auf seinem KnuddelAccount - * genug Knuddel besitzt und online im Channel ist. - * Vom KnuddelAccount des Besitzer des Channel können Knuddel auch abgebucht werden, wenn dieser nicht im Channel online ist. - * - * Ist das Event App.onBeforeKnuddelReceived implementiert, so wird diese direkt nach dem use aufgerufen, - * um zu entscheiden, ob die Knuddel angenommen werden sollen. - * - *

Hinweis: Knuddel an einen Nutzer senden kannst du mit der Methode BotUser/transferKnuddel:method. - */ - use(knuddelAmount: KnuddelAmount, displayReasonText: string, parameters?: { transferReason?: string; onError?(message: string): void; onSuccess?(): void; }): void; -} - -/** - * Eine Instanz von KnuddelAmount repräsentiert eine bestimmte Anzahl von Knuddel. - */ -declare class KnuddelAmount { - /** - * Erzeugt eine Instanz von KnuddelAmount mit der Anzahl Knuddel. - */ - constructor(knuddel: number); - /** - * Erzeugt eine Instanz von KnuddelAmount mit einer bestimmten Cent-Anzahl. - */ - static fromCents(knuddel: number): KnuddelAmount; - /** - * Erzeugt eine Instanz von KnuddelAmount mit einer bestimmten Knuddel-Anzahl. - */ - static fromKnuddel(knuddel: number): KnuddelAmount; - /** - * Liefert die Anzahl der Knuddel in KnuddelCent zurück. - */ - getKnuddelCents(): number; - /** - * Gibt den Wert der Knuddel als Zahl zurück. - */ - asNumber(): number; - /** - * Liefert eine negierte Kopie des KnuddelAmount zurück. - */ - negate(): KnuddelAmount; - /** - * Liefert die Information, ob der Knuddelwert unter 0 ist. - */ - isNegative(): boolean; -} - -/** - * Repräsentiert einen KnuddelPot. - * Ein KnuddelPot kann nur durch Factory-Methoden des KnuddelsServer erzeugt werden: - * KnuddelsServer/createKnuddelPot:method. - * - * Wird die App heruntergefahren, so werden alle KnuddelPots, die nicht gesealt sind automatisch refunded. - */ -declare class KnuddelPot { - /** - * Liefert die id des KnuddelPot. - */ - getId(): number; - /** - * Liefert den Status des KnuddelPot. - */ - getState(): KnuddelPotState; - /** - * Liefert den beim Kreieren des KnuddelPots festgelegten KnuddelAmount, den jeder Teilnehmer zahlen muss. - */ - getKnuddelAmountPerParticipant(): KnuddelAmount; - /** - * Liefert den KnuddelAmount, der bisher insgesamt in den KnuddelPot eingezahlt wurde. - */ - getKnuddelAmountTotal(): KnuddelAmount; - /** - * Liefert die Liste der Teilnehmer, die bisher in den KnuddelPot eingezahlt haben. - */ - getParticipants(): User[]; - /** - * Liefert den höchsten Multiplikator, der gültig ist. - */ - getMaxFeeMultiplier(): number; - /** - * Setzt den BotUser, der den Anteil der Einzahlungen nach dem Spiel erhält - * und den Anteil, vom Gesamtpot, den er erhalten soll. - */ - setFee(feeUser: BotUser, feeMultiplier: number): void; - /** - * Liefert den mit KnuddelPot/setFee:method gesetzten BotUser an den die Gebühr ausbezahlt wird. - */ - getFeeUser(): User; - /** - * Liefert den mit KnuddelPot/setFee:method gesetzten Multiplikator der Gebühr. - */ - getFeeMultiplier(): number; - /** - * Versiegelt den KnuddelPot, sodass keine weiteren Einzahlungen vorgenommen - * werden können und Gewinne ausgeschüttet werden können. - */ - seal(): void; - /** - * Bezahlt alle Einsätze an die Teilnehmer zurück und informiert mit dem übergeben Text über den Grund. - */ - refund(reason?: string): void; - /** - * Fügt einen Gewinner in die Liste der Gewinner hinzu. - * Der zweite Parameter ist die Gewichtung mit der ausgezahlt werden soll. - * Wird der Parameter weggelassen, so ist er automatisch 1. - */ - addWinner(user: User, weight?: number): void; - /** - * Zahlt den KnuddelPot an die mit addWinner gesetzten Gewinner aus. - */ - payout(text?: string): void; -} - -/** - * Repräsentiert den Status eines KnuddelPot. - */ -declare class KnuddelPotState { - /** - * Der KnuddelPot ist geöffnet und kann neue Teilnehmer annehmen. - */ - static readonly Open: KnuddelPotState; - /** - * Der KnuddelPot ist versiegelt und kann keine neuen Teilnehmer annehmen. - */ - static readonly Sealed: KnuddelPotState; - /** - * Der KnuddelPot ist beendet und die Knuddel bereits ausgezahlt. - */ - static readonly Closed: KnuddelPotState; -} - -/** - * Ein KnuddelTransfer ist ein Container-Objekt für die Daten, die bei einer Knuddel-Transaktion von einem User - * an eine App anfallen. - * - * Implementiert man den App-Hook onBeforeKnuddelReceived, so kann man dort entscheiden, ob man den KnuddelTransfer - * annimmt oder ablehnt. - */ -declare class KnuddelTransfer { - /** - * Liefert den User, der den KnuddelTransfer ausgelöst hat. - */ - getSender(): User; - /** - * Liefert den BotUser, der die Knuddel des KnuddelTransfer erhält, - * wenn dieser mit accept() angenommen wurde. - */ - getReceiver(): BotUser; - /** - * Liefert die Anzahl der Knuddel, die mit diesem Transfer überwiesen werden. - */ - getKnuddelAmount(): KnuddelAmount; - /** - * Liefert den Grund für den Transfer, der bei der Überweisung angegeben wurde mit - * /appknuddel BOTNICK:KNUDDEL:GRUND. - */ - getTransferReason(): string; - /** - * Lehnt die Knuddel aus dem KnuddelTransfer ab und sendet sie zurück an den Absender. - * Als Grund sieht der Absender den übergebenen reason. - * - * Diese Methode wirft eine Exception, wenn sie auf einen bereits verarbeiteten Transfer aufgerufen wird. - * Sie kann nur erfolgreich aus dem AppHook onBeforeKnuddelReceived aufgerufen werden. - * - * In der Methode onBeforeKnuddelReceived kann genau ein Aufruf einer dieser drei Methoden gemacht werden: - * KnuddelTransfer/accept:method, - * KnuddelTransfer/addToPot:method, - * KnuddelTransfer/reject:method - */ - reject(reason: string): void; - /** - * Nimmt die Knuddel aus dem KnuddelTransfer an und übergibt sie an den BotUser, - * der mit getReceiver() abgefragt werden kann. - * - * Diese Methode wirft eine Exception, wenn sie auf einen bereits verarbeiteten Transfer aufgerufen wird. - * Sie kann nur erfolgreich aus dem AppHook onBeforeKnuddelReceived aufgerufen werden. - * In der Methode onBeforeKnuddelReceived kann genau ein Aufruf einer dieser drei Methoden gemacht werden: - * - * KnuddelTransfer/accept:method, - * KnuddelTransfer/addToPot:method, - * KnuddelTransfer/reject:method - */ - accept(): void; - /** - * Liefert die Information, ob ein bestimmter KnuddelTransfer zu einem KnuddelPot hinzugefügt werden kann. - */ - canAddToPot(pot: KnuddelPot): boolean; - /** - * Nimmt die Knuddel aus dem KnuddelTransfer an und übergibt sie an den übergebenen KnuddelPot. - * - * Diese Methode funktioniert analog zu KnuddelTransfer/accept:method, nur dass die Knuddel im KnuddelPot statt beim BotUser landen. - * - * Diese Methode wirft eine Exception, wenn sie auf einen bereits verarbeiteten Transfer aufgerufen wird. - * Sie kann nur erfolgreich aus dem AppHook onBeforeKnuddelReceived aufgerufen werden. - * - * In der Methode onBeforeKnuddelReceived kann genau ein Aufruf einer dieser drei Methoden gemacht werden: - * KnuddelTransfer/accept:method, - * KnuddelTransfer/addToPot:method, - * KnuddelTransfer/reject:method - */ - addToPot(knuddelPot: KnuddelPot): void; - /** - * Liefert die Information, ob der KnuddelTransfer bereits verarbeitet wurde. - * Falls die Methode false zurückliefert muss noch entschieden werden, ob der - * KnuddelTransfer angenommen oder abgelehnt wird. - */ - isProcessed(): boolean; -} - -/** - * KnuddelTransferDisplayType repräsentiert die Art der Darstellung einer Knuddel-Überweisung. - */ -declare class KnuddelTransferDisplayType { - /** - * Nachricht wird öffentlich angezeigt. - */ - static readonly Public: KnuddelTransferDisplayType; - /** - * Nachricht wird privat angezeigt. - */ - static readonly Private: KnuddelTransferDisplayType; - /** - * Nachricht wird als /m zugestellt. - */ - static readonly Post: KnuddelTransferDisplayType; -} - -/** - * KnuddelsServer ist die 'Einstiegsklasse'. Mit den statischen Methoden des KnuddelsServer erhält man Zugriff auf viele - * Objekte und Klassen, die im Verlauf der App-Entwicklung benötigt werden. - */ -declare class KnuddelsServer { - /** - * Liefert den BotUser, der standardmäßig zur App gehört. - */ - static getDefaultBotUser(): BotUser; - /** - * Liefert die AppPersistence, mit der sich Zahlen, Strings und Javascript-Objekte langfristig und über die Session einer App hinaus gespeichert werden können. - */ - static getPersistence(): AppPersistence; - /** - * Liefert den Channel in dem die App läuft. - */ - static getChannel(): Channel; - /** - * Liefert das UserAccess-Objekt, über das - * User zugreifbar werden. - */ - static getUserAccess(): UserAccess; - /** - * Liefert ein ExternalServerAccess-Objekt, mit dem - * andere Server angesteuert werden können. - */ - static getExternalServerAccess(): ExternalServerAccess; - /** - * Aktualisiert die Liste der genutzten Hooks. Werden zur Laufzeit chatCommands oder App-Hooks (wie mayJoinChannel) dynamisch erzeugt oder gelöscht, so muss danach refreshHooks() - * aufgerufen werden, damit diese Änderung wirksam wird. - */ - static refreshHooks(): void; - /** - * Liefert den Standard-Logger für diese App. Alles, was geloggt wird, wird vom Nutzer "App-Logs" als private Nachricht zugestellt. - */ - static getDefaultLogger(): Logger; - /** - * Liefert den Pfad eines Bildes zur Integration in der eigenen App. - * Alle Bilder, die im Ordner /www in der App abgelegt werden können hier referenziert werden. - */ - static getFullImagePath(imageName: string): string; - /** - * Liefert den Pfad eines Systembildes zur Integration in der eigenen App. - * Alle Bilder, die unter http://apps4.knuddels.biz/kimg/ - * erreichbar sind können hier referenziert werden. - */ - static getFullSystemImagePath(imageName: string): string; - /** - * Liefert die Informationen über den ChatServer auf dem die App läuft. - */ - static getChatServerInfo(): ChatServerInfo; - /** - * Liefert die Informationen über den AppServer auf dem die App läuft. - */ - static getAppServerInfo(): AppServerInfo; - /** - * Liefert das AppAccess-Object. - */ - static getAppAccess(): AppAccess; - /** - * Erzeugt einen KnuddelPot. - * - * Ist ein KnuddelPot 30 Minuten nach dem Erzeugen noch nicht gesealt, - * so wird vom Server automatisch ein KnuddelPot/refund:method ausgelöst. - */ - static createKnuddelPot( - knuddelAmount: KnuddelAmount, - params?: { - payoutTimeoutMinutes?: number; - shouldSealPot?(pot: KnuddelPot): boolean; - onPotSealed?(pot: KnuddelPot): void; - }): KnuddelPot; - /** - * Liefert den KnuddelPot mit der angegeben id. - */ - static getKnuddelPot(id: number): (KnuddelPot|null); - /** - * Liefert alle für die App noch verwaltbaren KnuddelPot-Objekte. - */ - static getAllKnuddelPots(): KnuddelPot[]; - /** - * Liefert das ToplistAccess-Objekt, über das - * Toplisten erzeugt und verwaltet werden können. - */ - static getToplistAccess(): ToplistAccess; - /** - * Liefert das AppProfileEntryAccess-Objekt, über das - * App-Profileinträge erzeugt und verwaltet werden können. - */ - static getAppProfileEntryAccess(): AppProfileEntryAccess; -} - -/** - * Mit einer Instanz einer LoadConfiguration kann gestaltet werden, wie der Inhalt des HTML User Interface aussieht, bevor es fertig geladen ist. - */ -declare class LoadConfiguration { - /** - * Setzt die Farbe des Hintergrundes vom Loading-View, der angezeigt wird, während das HTML User Interface lädt. (standardmäßig weiß) - */ - setBackgroundColor(color: Color): void; - /** - * Setzt das Hintergrundbild vom Loading-View, das angezeigt wird, während das HTML User Interface lädt. (standardmäßig nicht gesetzt) - */ - setBackgroundImage(imageUrl: string): void; - /** - * Setzt den Text des Ladehinweiseses im Loading-View, der angezeigt wird, während das HTML User Interface lädt. (standardmäßig "Lädt...") - * Hinweis: Wird mit setLoadingIndicatorImage ein Loaading-Indicator-Bild gesetzt, so wird der mit setText gesetzte Texte ignoriert. - */ - setText(text: string): void; - /** - * Setzt ein Loading-Indicator-Bild im Loading-View, das angezeigt wird, während das HTML User Interface lädt. (standardmäßig nicht gesetzt) - * Hinweis: Wird mit setLoadingIndicatorImage ein Loaading-Indicator-Bild gesetzt, so wird der mit setText gesetzte Texte ignoriert. - */ - setLoadingIndicatorImage(imageUrl: string): void; - /** - * Setzt die Farbe des Textes im Loading-View, der angezeigt wird, während das HTML User Interface lädt. (standardmäßig schwarz) - */ - setForegroundColor(color: Color): void; - /** - * Aktiviert/Deaktiviert die Nutzung vom Loading-View. (standardmäßig aktiviert) - * Es kann sinnvoll sein, den Loading-View zu deaktivieren, wenn man selbst einen komplett eigenen Loading-View in seine App einbauen möchte. - */ - setEnabled(enabled: boolean): void; -} - -/** - * Eine Instanz eines Logger ermöglicht das Loggen von Inhalten. - * - * Diese erhält man über das KnuddelsServer-Objekt - * mit KnuddelsServer.getDefaultLogger() - * - * Die Log-Einträge werden je nach Einstellungen im /apps-Fenster an den Besitzer des Channels, - * die App-Manager und den App-Entwickler zugestellt. - */ -declare class Logger { - /** - * Logge einen Text mit Level DEBUG. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt. Siehe: /apps, Tab: Logs. - * - * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. - */ - debug(...msg: any[]): void; - /** - * Logge einen Text mit Level INFO. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt. Siehe: /apps, Tab: Logs. - * - * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. - */ - info(...msg: any[]): void; - /** - * Logge einen Text mit Level WARN. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt, sowie im /apps Fenster im Log angezeigt. Siehe: /apps, Tab: Logs. - * - * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. - */ - warn(...msg: any[]): void; - /** - * Logge einen Text mit Level ERROR. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt, sowie im /apps Fenster im Log angezeigt. Siehe: /apps, Tab: Logs. - * - * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. - */ - error(...msg: any[]): void; - /** - * Logge einen Text mit Level FATAL. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt, sowie im /apps Fenster im Log angezeigt. Siehe: /apps, Tab: Logs. - * - * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. - */ - fatal(...msg: any[]): void; -} - -/** - * Message ist eine abstrakte Klasse und repräsentiert eine Nachricht im Chat. - */ -declare class Message { - /** - * Liefert den User, der die Nachricht verfasst hat. - */ - getAuthor(): User; - /** - * Liefert den Inhalt der Nachricht. - */ - getText(): string; - /** - * Liefert den genauen Zeitpunkt, zu dem die Nachricht erstellt wurde. - */ - getCreationDate(): Date; -} - -/** - * Repräsentiert die Instanz der konkreten App, auf die dieser Code Zugriff hat. - * - * Die Instanz von OwnAppInstance erhält man über das AppAccess-Objekt - * mit appAccess.getOwnInstance() - */ -declare class OwnAppInstance { - /** - * Gibt Zugriff auf Nutzer, die gerade im Channel dieser AppInstance online sind. - * @since AppServer 82560 - */ - getOnlineUsers(otherAppInstance: AppInstance, ...userType: UserType[]): User[]; -} - -/** - * Eine Instanz von Persistence ermöglicht die persistente Speicherung von Zahlen, Zeichenketten und JSON-Objekten. - * Es gibt die zwei Arten AppPersistence und UserPersistence - * - * Jeder eigene Datentyp hat seinen eigenen Namensraum. - * So kann derselbe key für eine Zahl, Zeichenkette und auch JSON-Objekt genutzt werden. - * - *

Hinweis: Mit der Persistence gespeicherte Informationen überleben - * sogar die Deinstallation und Neuinstallation der App. - */ -declare class Persistence { - /** - * Informiert darüber, ob unter dem key ein String abgespeichert ist. - */ - hasString(key: string): boolean; - /** - * Setzt die Zeichenkette value für den key. - * Falls bereits eine Zeichenkette für den key existiert, so wird diese überschrieben. - */ - setString(key: string, value: string): void; - /** - * Liefert die Zeichenkette, die für den key gespeichert ist. - * Falls für key keine Zeichenkette gespeichert ist, so gibt die Methode - * den defaultValue zurück. - */ - getString(key: string, defaultValue?: string): string; - /** - * Löscht die Zeichenkette, die unter key gespeichert ist. - */ - deleteString(key: string): void; - /** - * Informiert darüber, ob unter dem key eine Zahl abgespeichert ist. - */ - hasNumber(key: string): boolean; - /** - * Setzt die Zahl value für den key. - * Falls bereits eine Zahl für den key existiert, so wird diese überschrieben. - */ - setNumber(key: string, value: number): void; - /** - * Addiert den übergebenen value auf die unter dem Key key vorhandenen Wert drauf. - * Value kann auch negativ sein um eine Subtraktion durchzuführen. - * Falls keine Zahl für den key existiert, so wird der value für key gespeichert. - */ - addNumber(key: string, value: number): number; - /** - * Liefert die Zahl, die für den key gespeichert ist. - * Falls für key keine Zahl gespeichert ist, so gibt die Methode - * den defaultValue zurück. - */ - getNumber(key: string, defaultValue?: number): number; - /** - * Löscht die Zahl, die unter key gespeichert ist. - */ - deleteNumber(key: string): void; - /** - * Informiert darüber, ob unter dem key ein Objekt abgespeichert ist. - */ - hasObject(key: string): boolean; - /** - * Setzt das Objekt value für den key. - * Falls bereits ein Objekt für den key existiert, so wird dieses überschrieben. - * Das als JSON serialisierte Objekt darf maximal 100kb groß sein. - */ - setObject(key: string, object: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable)): void; - /** - * Liefert das Objekt, das für den key gespeichert ist. - * Falls für key kein Objekt gespeichert ist, so gibt die Methode - * den defaultValue zurück. - */ - getObject(key: string, defaultValue?: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable)): (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable); - /** - * Löscht das Objekt, das unter key gespeichert ist. - */ - deleteObject(key: string): void; -} - -/** - * Eine Instanz von PrivateMessage repräsentiert eine private Nachricht im Chat. - * Die App erhält sämtliche private Nachrichten, die an einen ihrer BotUser - * geschickt werden. - * - *

Hinweis: Eine App hat keinen Zugriff auf private Nachrichten, - * die Nutzer untereinander schreiben, ohne dass ein BotUser als Empfänger involviert ist. - */ -declare class PrivateMessage extends Message { - /** - * Liefert die Liste der Empfänger der Nachricht. - */ - getReceivingUsers(): User[]; - /** - * Sendet eine private Nachricht an alle Beteiligten des Gespräches. - */ - sendReply(text: string): void; -} - -/** - * Eine Instanz von PublicActionMessage repräsentiert eine öffentliche Handlung im Chat. - * Die App erhält die öffentlichen Handlungen. - */ -declare class PublicActionMessage extends Message { -} - -/** - * Eine Instanz von PublicEventMessage repräsentiert ein öffentliches Event im Chat. - * Die App erhält die öffentlichen Events. - */ -declare class PublicEventMessage extends Message { -} - -/** - * Eine Instanz von PublicMessage repräsentiert eine öffentliche Nachricht im Chat. - * Die App erhält die öffentlichen Nachrichten, die geschrieben werden. - */ -declare class PublicMessage extends Message { -} - -/** - * Eine Quest ist eine konkrete Aufgabe, die ein User in der App zu erledigen hat. - * - * Im Blog findest du Informationen darüber, wie man eine Quest für seine App erhält: - * https://blog.developer.knuddels.de/2015/10/29/how-to-get-a-quest/ - */ -declare class Quest { - /** - * Löst ein Quest-Event aus. - * @since AppServer 82290, ChatServer 82290 - */ - setSolved(count?: number): void; - /** - * Liefert den Key der Quest. - * @since AppServer 82290, ChatServer 82290 - */ - getQuestKey(): string; -} - -/** - * Ein QuestAccess-Objekt ermöglicht den Zugriff auf die Quests, die ein Nutzer des Chats, für die laufende App hat. - * - * Im Blog findest du Informationen darüber, wie man eine Quest für seine App erhält: - * https://blog.knuddels.de/2015/10/29/how-to-get-a-quest/ - */ -declare class QuestAccess { - /** - * Liefert die Quests - * für diesen Nutzer in dieser App. - * @since AppServer 82290, ChatServer 82290 - */ - getQuests(): Quest[]; - /** - * Liefert die Information, ob eine bestimmte Quest offen ist. - * @since AppServer 82290, ChatServer 82290 - */ - hasQuest(questKey: string): boolean; - /** - * Liefert eine bestimmte Quest, falls vorhanden. - * @since AppServer 82290, ChatServer 82290 - */ - getQuest(questKey: string): (Quest|null); - /** - * Liefert den User, der zu diesem QuestAccess-Objekt gehört. - * @since AppServer 82290, ChatServer 82290 - */ - getUser(): User; -} - -/** - * RandomOperations bietet eine Sammlung verschiedener Zufallsoperationen, die man für Glücksspiele und Ähnliches nutzen kann. - */ -declare class RandomOperations { - /** - * Liefert eine Zufallszahl zwischen minValue (inklusiv) und maxValue (exklusiv). - */ - static nextInt(minValue: number /* optional */, maxValue: number): number; - /** - * Liefert ein Array mit Zufallszahlen zwischen minValue (inklusiv) und n (exklusiv). - */ - static nextInts(minValue: number /* optional */, maxValue: number, count: number, onlyDifferentNumbers: boolean): number[]; - /** - * Liefert true in truePropability/1 Fällen - */ - static flipTrue(truePropability: number): boolean; - /** - * Liefert ein zufälliges Objekt aus einem Array. - * Falls das Array leer ist, wird null zurückgeliefert. - */ - static getRandomObject(objects: T[]): T; - /** - * Mischt das Array der übergebenen Objekte und liefert es zurück. - */ - static shuffleObjects(objects: T[]): T[]; - /** - * Liefert einen zufälligen String zurück. - * @since AppServer 92699 - */ - static getRandomString(length: number, allowedCharacters?: string): string; -} - -/** - * Repräsentiert die Root-Instanz einer App, die im Hauptchannel läuft. - * - * Die Instanz für die RootAppInstance erhält man über das AppInstance-Objekt - * mit appInstance.getRootInstance() - */ -declare class RootAppInstance extends AppInstance { - /** - * Aktualisiert diese App im Channel (und ggf. vorhandenen Tochterchanneln) auf die neueste Version. - */ - updateApp(message: string /* optional */, logMessage?: string): void; - /** - * Stoppt diese App. - */ - stopApp(message: string /* optional */, logMessage?: string): void; -} - -/** - * Liefert Informationen über einen Server. - */ -declare class ServerInfo { - /** - * Liefert die interne ServerId des Servers. - */ - getServerId(): string; - /** - * Liefert die Code-Revision des Servers. - */ - getRevision(): number; -} - -/** - * Ein SingleDiceResult enthält das Ergebnis aller Würfel desselben Typs. - * Würfelt man beispielsweise mit der Konfiguration "1w2 + 10w5" so gibt es im DiceResult - * zwei SingleDiceResult-Objekte. Eines für "1w2" und eines für "10w5". - */ -declare class SingleDiceResult { - /** - * Liefert den Würfel zurück, durch den dieses SingleDiceResult erzeugt wurde. - */ - getDice(): Dice; - /** - * Liefert die Ziffern, die gewürfelt wurden. - */ - valuesRolled(): number[]; - /** - * Liefert die Summe der Augenzahlen des SingleDiceResult. - */ - sum(): number; -} - -/** - * Diese Dokumentation beschreibt, welche Erweiterungen am serverseitigen String-Objekt vorgenommen wurden. - */ -interface String { - /** - * Die Methode liefert den String zurück, auf dem sie aufgerufen wurde mit KCode escaped. - */ - escapeKCode(): string; - /** - * Entfernt jeglichen KCode aus dem String und gibt ihn zurück. - */ - stripKCode(): string; - /** - * Diese Methode liefert die Information, ob der String auf dem die Methode aufgerufen wurde - * mit einem bestimmten Prefix beginnt. - */ - startsWith(prefix: string): boolean; - /** - * Diese Methode liefert die Information, ob der String auf dem die Methode aufgerufen wurde - * mit einem bestimmten Suffix endet. - */ - endsWith(suffix: string): boolean; - /** - * Liefert die Breite des Strings in der Schriftart Arial mit der gegeben Schriftgröße und Information, ob Text fett dargestellt werden soll. - */ - getPixelWidth(fontSize: number, isBold: boolean): number; - /** - * Liefert einen String, der in der Schriftart Arial mit der gegeben Schriftgröße und Information, ob Text fett dargestellt werden soll - * maximal maxPixelWidth breit ist. Wird der Text dafür gekürzt, so wird an das Ende abbreviationMarker angehangen. - * Falls abbreviationMarker nicht übergeben wurde, so ist es automatisch '...'. - */ - limitString(fontSize: number, isBold: boolean, maxPixelWidth: number, abbreviationMarker?: string): string; - /** - * Liefert die Information, ob ein bestimmter String in diesem String vorhanden ist. - */ - contains(needle: string): boolean; - /** - * Liefert die Levenshtein-Distanz zum übergebenen String. - * Levenshtein-Distanz: Minimale Anzahl von Einfüge-, Lösch- und Ersetz-Operationen, um die erste Zeichenkette in die zweite umzuwandeln. - * @since AppServer 82271 - */ - minimalConversionCost(otherString: string): number; - /** - * Liefert die Information, ob der String nur aus Zeichen besteht, die in einem Nicknamen - * vorkommen dürfen. - * @since AppServer 82271 - */ - hasOnlyNicknameCharacters(): boolean; - /** - * Liefert die Information, ob der String nur aus Zeichen besteht, die Nummern sind. - * @since AppServer 82271 - */ - hasOnlyDigits(): boolean; - /** - * Liefert die Information, ob der String nur aus Zeichen besteht, die alphanumerisch + Whitespaces sind. - * @since AppServer 82271 - */ - hasOnlyAlphanumericalAndWhitespaceCharacters(): boolean; - /** - * Liefert die Information, ob der String leer oder null ist. - * @since AppServer 92695 - */ - isEmpty(): boolean; - /** - * Liefert den String in CamelCase. - * @since AppServer 92695 - */ - toCamelCase(): string; - /** - * Liefert den String mit dem ersten Buchstaben als Großbuchstaben. - * @since AppServer 92695 - */ - capitalize(): string; - /** - * Erstellt eine Kopie des String, in dem alle Vorkommnisse des String search in replacement - * ersetzt werden und liefert diesen zurück. - */ - replaceAll(search: string | RegExp, replacement: string): string; - /** - * Prüft primitiv, ob der String laut Knuddels-Filterregeln ok ist. - * @since ChatServer 82262, AppServer 82262 - */ - isOk(): boolean; -} - -/** - * Eine Instanz einer Toplist repräsentiert eine eigene Topliste für einen bestimmten userPersistenceNumberKey. - */ -declare class Toplist { - /** - * Liefert den userPersistenceNumberKey mit dem die Topliste erzeugt wurde. - */ - getUserPersistenceNumberKey(): string; - /** - * Liefert den Anzeigenamen der Topliste. - */ - getDisplayName(): string; - /** - * Liefert den Befehl, der im Chat eingegeben werden kann, um diese Topliste zu öffnen. - * Wird ein User oder eine userId übergeben, so öffnet sich die Topliste mit diesem Nutzer im Fokus. - */ - getChatCommand(user_or_userId?: (User|number)): string; - /** - * Liefert den Anzeigenamen für den übergebenen User oder eine userId. - */ - getLabel(user_or_userId: (User|number)): string; - /** - * Legt einen Change-Listener an, der jedes mal aufgerufen wird, wenn ein User - * einen neuen Anzeigenamen erhält. - */ - addLabelChangeListener(listener: (labelChangeEvent: ToplistLabelChangeEvent) => void): void; - /** - * Löscht einen LabelChangeListener, der mit Toplist/addLabelChangeListener:method erzeugt wurde. - */ - removeLabelChangeListener(listener: (labelChangeEvent: ToplistLabelChangeEvent) => void): void; - /** - * Legt einen Change-Listener an, der jedes mal aufgerufen wird, wenn ein sich der Rang User eines Nutzers ändert. - */ - addRankChangeListener(listener: (rankChangeEvent: ToplistRankChangeEvent) => void): void; - /** - * Löscht einen RankChangeListener, der mit Toplist/addRankChangeListener:method erzeugt wurde. - */ - removeRankChangeListener(listener: (rankChangeEvent: ToplistRankChangeEvent) => void): void; -} - -/** - * Mit einer Instanz von ToplistAccess kann eine App - * Toplist erzeugen und verwalten. - * - * Die Instanz für die ToplistAccess erhält man über das KnuddelsServer-Objekt - * mit KnuddelsServer.getToplistAccess() - */ -declare class ToplistAccess { - /** - * Liefert die Liste aller Toplisten, die diese App erzeugt hat. - */ - getAllToplists(): Toplist[]; - /** - * Liefert die Toplist mit dem Persistenz-Key zurück. - */ - getToplist(userPersistenceNumberKey: string): Toplist; - /** - * Löscht die übergebene Toplist oder die Toplist mit dem Persistenz-Key. - */ - removeToplist(toplist: Toplist): void; - /** - * Erzeugt oder aktualisiert die Toplist für den übergebenen userPersistenceNumberKey. - */ - createOrUpdateToplist(userPersistenceNumberKey: string, displayName: string, parameters?: { labelMapping?: { [minValue: string]: string }; ascending?: boolean; }): Toplist; -} - -/** - * ToplistDisplayType repräsentiert den Anzeigetyp eines Toplisteneintrags im Profil vonUsern. - */ -declare class ToplistDisplayType { - /** - * Nur Anzeigename anzeigen. - */ - static readonly Label: ToplistDisplayType; - /** - * Gespeicherten Wert anzeigen. - */ - static readonly Value: ToplistDisplayType; - /** - * Anzeigename und Rang anzeigen. - */ - static readonly LabelAndRank: ToplistDisplayType; - /** - * Wert und Rang anzeigen. - */ - static readonly ValueAndRank: ToplistDisplayType; -} - -/** - * ToplistLabelChangeEvents erhalten EventListener die bei einer - * Toplist mit der Methode Toplist/addLabelChangeListener:method - * erzeugt wurden, nachdem sich der Anzeigename für einen User geändert hat. - * - * Das ToplistLabelChangeEvent enthält alle wichtigen Daten, um auf die Änderung zu reagieren - * und dem User beispielsweise für den Aufstieg zu gratulieren. - */ -declare class ToplistLabelChangeEvent { - /** - * Liefert die zugehörige Toplist. - */ - getToplist(): Toplist; - /** - * Liefert den vorherigen Anzeigenamen. Hatte der User vorher keinen - * Anzeigenamen, so ist dieser Wert null. - */ - getOldLabel(): string; - /** - * Liefert den neuen Anzeigenamen. Hatte der User nun keinen - * Anzeigenamen mehr, so ist dieser Wert null. - */ - getNewLabel(): string; - /** - * Liefert den User für den das Event ausgelöst wurde. - */ - getUser(): User; - /** - * Liefert den Wert, der vor der Änderung gespeichert war. - */ - getOldValue(): number; - /** - * Liefert den neuen Wert. - */ - getNewValue(): number; -} - -/** - * ToplistRankChangeEvents erhalten EventListener die bei einer - * Toplist mit der Methode Toplist/addRankChangeListener:method - * erzeugt wurden, nachdem sich der Rang für einen User geändert hat. - * - * Das ToplistRankChangeEvent enthält alle wichtigen Daten, um auf die Änderung zu reagieren - * und den überholten Usern eine Nachricht zu senden. - */ -declare class ToplistRankChangeEvent { - /** - * Liefert die zugehörige Toplist. - */ - getToplist(): Toplist; - /** - * Liefert den Toplisten-Rang, den der User vor der Änderung hatte. - */ - getOldRank(): number; - /** - * Liefert den neuen Toplisten-Rang, des Users. - */ - getNewRank(): number; - /** - * Liefert den User für den das Event ausgelöst wurde. - */ - getUser(): User; - /** - * Liefert die User, die bei dieser Änderung überholt worden sind. - *

Achtung: Wenn mehr als 10 User - * überholt wurden, so liefert die Methode die besten 10 überholten User. - */ - getUsersOvertook(): User[]; - /** - * Liefert den Wert, der vor der Änderung gespeichert war. - */ - getOldValue(): number; - /** - * Liefert den neuen Wert. - */ - getNewValue(): number; -} - -/** - * Ein User ist ein Nutzer des Chats, in dem die App läuft. - */ -declare class User { - /** - * Liefert die eindeutige Nutzerkennung des Nutzers. - */ - getUserId(): number; - /** - * Liefert den Nicknamen des Nutzers. - */ - getNick(): string; - /** - * Liefert das Alter des Nutzers. Bei Nutzern, die bereits sehr lange in der Plattform sind kann es vorkommen, dass kein Alter angegeben wurde. In diesem Fall ist das Alter 0. - */ - getAge(): number; - /** - * Liefert das Geschlecht des Nutzers. - */ - getGender(): Gender; - /** - * Liefert den Zeitpunkt der Registrierung des Nutzers. - */ - getRegDate(): Date; - /** - * Liefert den UserStatus des Nutzers. - */ - getUserStatus(): UserStatus; - /** - * Liefert den UserType des Nutzers. - */ - getUserType(): UserType; - /** - * Liefert den aktuellen ClientType des Nutzers oder Offline wenn er nicht im Chat online ist. - */ - getClientType(): ClientType; - /** - * Prüft ob der Client des Users den übergebenen AppViewMode (für User/sendAppContent:method) anzeigen kann. - */ - canShowAppViewMode(mode: AppViewMode): boolean; - /** - * Prüft ob der Client des User's den übergebenen AppContent anzeigen kann. - */ - canSendAppContent(appContent: AppContent): boolean; - /** - * Prüft, ob der User in dem angegebenen Team ist. - * Dies funktioniert derzeit nur für Teams, die eine eigene /fa haben. - * - * Achtung: Bei Nutzern, die neu in ein Team kommen, funktioniert die Abfrage erst dann korrekt, - * wenn er sich neu in den Channel eingeloggt hat. - */ - isInTeam(teamName: string, subTeamName?: string): boolean; - /** - * Liefert ein UserPersistence-Objekt für diesen Nutzer. Mit diesem Objekt kann eine App sich Dinge über diesen speziellen Nutzer merken. - */ - getPersistence(): UserPersistence; - /** - * Shortcut-Funktion um mit dem DefaultBotUser eine private Nachricht zu versenden. - */ - sendPrivateMessage(message: string): void; - /** - * Shortcut-Funktion um mit dem DefaultBotUser eine /m zu versenden. - */ - sendPostMessage(topic: string, text: string): void; - /** - * Liefert die Information, ob dieser Nutzer Channelbesitzer im Channel der App ist. - */ - isChannelOwner(): boolean; - /** - * Liefert die Information, ob der Channel der App - * ein Lieblingschannel des Nutzers ist. - */ - isLikingChannel(): boolean; - /** - * Liefert die Information, ob der Nutzer im harten Kern des Channels der App ist. - * @since AppServer 92701, ChatServer 92701 - */ - isChannelCoreUser(): boolean; - /** - * Liefert die Information, ob dieser Nutzer ein AppManager für diese App ist. Die Channelbesitzer zählen automatisch auch als AppManager. - */ - isAppManager(): boolean; - /** - * Liefert Information, ob dieser Nutzer derzeit für das Schreiben öffentlicher Nachrichten im Channel gesperrt ist. - */ - isMuted(): boolean; - /** - * Liefert Information, ob dieser Nutzer beim Schreiben öffentlicher Nachrichten im Channel - * derzeit für die Verwendung von Textformatierungen, Farben und Smileys gesperrt ist. - */ - isColorMuted(): boolean; - /** - * Liefert Information, ob dieser Nutzer derzeit für das Betreten des Channel gesperrt ist. - */ - isLocked(): boolean; - /** - * Liefert Information, ob dieser Nutzer Channelmoderator im Channel der App ist. - */ - isChannelModerator(): boolean; - /** - * Liefert Information, ob dieser Nutzer Eventmoderator im Channel der App ist. - */ - isEventModerator(): boolean; - /** - * Liefert Information, ob dieser Nutzers der Entwickler der App ist. - */ - isAppDeveloper(): boolean; - /** - * Liefert einen Link zum Profil des Nutzers, den man im Chat anzeigen kann. - */ - getProfileLink(displayText?: string): string; - /** - * Liefert die Information, ob der Nutzer online im Channel der App ist. - */ - isOnlineInChannel(): boolean; - /** - * Liefert die Anzahl der Knuddel, die der Nutzer besitzt. - */ - getKnuddelAmount(): KnuddelAmount; - /** - * Liefert die Information, ob der Nutzer irgendwo im Chat online ist. - */ - isOnline(): boolean; - /** - * Liefert die Readme des Nutzers, die er mit /readme TEXT in sein Profil gesetzt hat. - */ - getReadme(): string; - /** - * Liefert die vom Nutzer verbrachte Zeit im gesamten Chatsystem In Minuten. - * Hinweis: Die Minutenzahl wird derzeit immer nur zu dem Zeitpunkt aktualisiert, - * wenn der Nutzer offline geht. - */ - getOnlineMinutes(): number; - /** - * Liefert die Information, ob der Nutzer sich mittels /away-Funktion kurz abgemeldet hat. - */ - isAway(): boolean; - /** - * Liefert die Information, ob der Nutzer ein Profilfoto hat. - */ - hasProfilePhoto(): boolean; - /** - * (Er)setzt den übergebenen AppContent beim Nutzer. - */ - sendAppContent(appContent: AppContent): AppContentSession; - /** - * Liefert alle AppContentSession, die der User - * aktuell geöffnet hat. - */ - getAppContentSessions(): AppContentSession[]; - /** - * Liefert die AppContentSession, die der User - * mit einem bestimmten AppViewMode aktuell geöffnet hat. - */ - getAppContentSession(appViewMode: AppViewMode): AppContentSession; - /** - * Vergleicht den übergebenen Nutzer und liefert true, falls der übergebene Nutzer - * identisch ist mit dem aktuellen Nutzer. - */ - equals(user: User): boolean; - /** - * Liefert die URL zum Profilfoto des Nutzers. Die übergebene Breite und Höhe - * liefern dem Server einen Anhaltswert, um das bestmögliche Foto zu finden, - * sind aber keine Garantie, dass das Foto diese Ausmaße haben wird. - */ - getProfilePhoto(width: number, height: number): string; - /** - * Liefert das QuestAccess-Objekt - * für diesen Nutzer in dieser App. - * @since AppServer 82290, ChatServer 82290 - */ - getQuestAccess(): QuestAccess; - /** - * Liefert die Information, ob der Nutzer gerade sein Video streamt. - */ - isStreamingVideo(): boolean; - /** - * Liefert den KnuddelAccount des Nutzers. - */ - getKnuddelAccount(): KnuddelAccount; - /** - * Liefert die ChannelTalkPermission für diesen Nutzer in diesem - * Channel. - */ - getChannelTalkPermission(): ChannelTalkPermission; - /** - * Liefert die Information, ob der User ein verifiziertes Profilbild hat. - */ - isProfilePhotoVerified(): boolean; - /** - * Liefert die Information, ob das Alter des Users verifiziert ist. - */ - isAgeVerified(): boolean; - /** - * Setzt dem Nutzer ein Icon in die Nickliste, das auf der rechten Seite seines Nicks angezeigt wird. - * Der Eintrag wird automatisch entfernt, sobald der Nutzer den Channel verlässt, - * kann aber auch mit User/removeNicklistIcon:method - * entfernt werden. - */ - addNicklistIcon(imagePath: string, imageWidth: number): void; - /** - * Entfernt dem Nutzer ein über die API gesetztes Icon in die Nickliste. - */ - removeNicklistIcon(imagePath: string): void; - /** - * Startet einen Würfelwurf für den Nutzer, falls er online im Channel ist und er nicht gemuted ist. - * @since AppServer 89159, ChatServer 89159 - */ - triggerDice(diceConfiguration: DiceConfiguration): void; -} - -/** - * Mit einer Instanz von UserAccess kann eine App - * auf User zugreifen, die bereits einmal im Channel waren, - * als die App lief. Für alle nicht zugreifbaren User kann man via UserAccess den korrekt geschriebenen Nicknamen erhalten. - * - * Die Instanz für die UserAccess erhält man über das KnuddelsServer-Objekt - * mit KnuddelsServer.getUserAccess() - */ -declare class UserAccess { - /** - * Liefert die userId des Nutzers mit dem übergebenen Nicknamen. - */ - getUserId(nick: string): number; - /** - * Informiert darüber, ob ein Nutzer mit dem übergebenen Nicknamen existiert. - */ - exists(nick: string): boolean; - /** - * Informiert darüber, ob der Nutzer mit der übergebenen userId geladen werden darf. Neben dem AppDeveloper können nur Nutzer geladen werden, die sich einmal im Channel befanden, als die App - * lief. - */ - mayAccess(userId: number): boolean; - /** - * Liefert den Nutzer mit der übergebenen userId. Neben dem AppDeveloper können nur Nutzer geladen werden, die sich einmal im Channel befanden, als die App lief. Es wird empfohlen vor der - * Abfrage von getUserById(userId) mit UserAccess/mayAccess:method abzufragen, ob dies funktionieren wird. - */ - getUserById(userId: number): User; - /** - * Liefert den Nicknamen des Nutzers mit der übergebenen userId in der korrekten Schreibweise. - */ - getNick(userId: number): string; - /** - * Loopt über alle zugreifbaren User sortiert nach Registrierzeitpunkt und - * führt für jeden User das übergebene Callback aus. - */ - eachAccessibleUser( - callback: (user: User, index: number, accessibleUserCount: number, key?: string) => boolean, - parameters?: { - onStart?(accessibleUserCount: number, key?: string): void; - onEnd?(accessibleUserCount: number, key?: string): void; - }): void; -} - -/** - * Für jeden User kann eine UserPersistence angefordert werden, um sich - * für einen bestimmten Nutzer Dinge persistent zu merken. - */ -declare class UserPersistence extends Persistence { - /** - * Löscht alle Zahlenwerte, die in dieser UserPersistence gespeichert sind. - * @since AppServer 88569 - */ - deleteAllNumbers(): number; - /** - * Löscht alle Objekte, die in dieser UserPersistence gespeichert sind. - * @since AppServer 88569 - */ - deleteAllObjects(): number; - /** - * Löscht alle Zeichenketten, die in dieser UserPersistence gespeichert sind. - * @since AppServer 88569 - */ - deleteAllStrings(): number; - /** - * Löscht alle Daten, die in dieser UserPersistence gespeichert sind. - * @since AppServer 88569 - */ - deleteAll(): number; -} - -/** - * Diese Klasse repräsentiert einen Eintrag der Persistenz. - */ -declare class UserPersistenceNumberEntry { - /** - * Liefert den Nutzer. - */ - getUser(): User; - /** - * Liefert den Wert. - */ - getValue(): number; - /** - * Liefert den Rang des Elements in der Persistenz. - */ - getRank(): number; - /** - * Liefert die Position des Elements in der Persistenz. - */ - getPosition(): number; -} - -/** - * Mit dieser Klasse ist es möglich nicht User-spezifische Abfragen auf die UserPersistence auszuführen. - */ -declare class UserPersistenceNumbers { - /** - * Liefert die Summe aller via UserPersistence gespeicherten Zahlen für den übergebenen key. - */ - static getSum(key: string): number; - /** - * Löscht alle gespeicherten Zahlen-Werte für den übergebenen key. - */ - static deleteAll(key: string): number; - /** - * Liefert die Anzahl aller unterschiedlichen Nutzer, die Werte für einen bestimmten key gespeichert haben. - * Hierbei kann optional der Wertebereich über die parameters eingegrenzt werden. - */ - static getCount(key: string, parameters?: { minimumValue?: number; maximumValue?: number; }): number; - /** - * Ändert einen bestimmten key bei allen UserPersistence. - */ - static updateKey(oldKeyName: string, newKeyName: string): number; - /** - * Ändert alle Werte für einen bestimmten key, die vorher einen bestimmten anderen Wert hatten in der UserPersistence. - *
Hinweis: Da diese Methode ein Batch-Update ist werden keine Change-Listener (ToplistRankChangeEvent, ToplistLabelChangeEvent) ausgelöst. - */ - static updateValue(key: string, oldValue: number, newValue: number): number; - /** - * Addiert einen Wert für Einträge mit einem bestimmten key in der UserPersistence. - *
Hinweis: Da diese Methode ein Batch-Update ist werden keine Change-Listener (ToplistRankChangeEvent, ToplistLabelChangeEvent) ausgelöst. - */ - static addNumber(key: string, value: number, parameters?: { minimumValue?: number; maximumValue?: number; targetUsers?: User[]; }): number; - /** - * Liefert ein Array mit UserPersistenceNumberEntry-Objekten für einen bestimmten key. - * Hierdurch kann beispielsweise eine blätterbare Topliste abgebildet werden. - */ - static getSortedEntries(key: string, parameters?: { ascending?: boolean; count?: number; page?: number; minimumValue?: number; maximumValue?: number; }): UserPersistenceNumberEntry[]; - /** - * Liefert ein Array mit UserPersistenceNumberEntry-Objekten für einen bestimmten key. Hierbei werden die nähesten Elemente gewählt, - * die am übergebenen User/UserId liegen. - * - * Beispiel: Der Nutzer ist in der Liste auf Position 20, dann werden die Resultate von 14-24 bei einem Count von 10 ausgegeben. - * Beispiel: Der Nutzer ist in der Liste auf Position 3, dann werden die Resultate von 1-10 bei einem Count von 10 ausgegeben. - */ - static getSortedEntriesAdjacent(key: string, user_or_userId: (User|number), parameters?: { ascending?: boolean; count?: number; }): UserPersistenceNumberEntry[]; - /** - * Liefert die absolute Position des Nutzers in der Liste. Die Position ist im Gegensatz zum Rang immer eindeutig. - * - * Bei gleichem Wert hat der Nutzer die höhere Position, der zuerst einen Eintrag in der Persistenz hatte. - * - * Mit der Methode UserPersistenceNumbers/getRank:method kann man den Rang des Nutzers herausfinden. Dieser ist identisch, wenn - * unterschiedliche Nutzer denselben Wert haben. - */ - static getPosition(key: string, user_or_userId: (User|number), parameters?: { ascending?: boolean; minimumValue?: number; }): number; - /** - * Liefert den Rang des Nutzers. Der Rang ist nicht eindeutig. Bei gleicher Punktzahl haben Nutzer denselben Rang. - * Mit der Methode UserPersistenceNumbers/getPosition:method kann man die Position eindeutige Position, statt des Ranges herausfinden. - */ - static getRank(key: string, user_or_userId: (User|number), parameters?: { ascending?: boolean; minimumValue?: number; }): number; - /** - * Ruft eine Funktion für alle Nutzer auf, die einen bestimmten key in der UserPersistence gesetzt haben. - * Hierbei greifen die übergebenen Filter. - */ - static each( - key: string, - callback: { user: User; value: number; index: number; totalCount: number; key: string; }, - parameters?: { - ascending?: boolean; - minimumValue?: number; - maximumValue?: number; - maximumCount?: number; - onStart?(totalCount: number, key: string): void; - onEnd?(totalCount: number, key: string): void; - }): void; - /** - * Liefert alle keys, die für User in der Persistence - * gespeichert wurden. - * @since AppServer 82483 - */ - static getAllKeys(filterKey?: string): string[]; -} - -/** - * Mit dieser Klasse ist es möglich nicht User-spezifische Abfragen auf die UserPersistence auszuführen. - */ -declare class UserPersistenceObjects { - /** - * Löscht alle gespeicherten Objekte für den übergebenen key. - * @since AppServer 82478 - */ - static deleteAll(key: string): number; - /** - * Liefert alle keys, die für User in der Persistence - * gespeichert wurden. - * @since AppServer 82483 - */ - static getAllKeys(filterKey?: string): string[]; -} - -/** - * Mit dieser Klasse ist es möglich nicht User-spezifische Abfragen auf die UserPersistence auszuführen. - */ -declare class UserPersistenceStrings { - /** - * Liefert die Information, ob für einen bestimmten key und value bei einem beliebigen Nutzer eine Paarung existiert. - * @since AppServer 88571 - */ - static exists(key: string, value: string, ignoreCase?: boolean): boolean; - /** - * Löscht alle gespeicherten Strings für den übergebenen key. - * @since AppServer 82478 - */ - static deleteAll(key: string): number; - /** - * Liefert alle keys, die für User in der Persistence - * gespeichert wurden. - * @since AppServer 82483 - */ - static getAllKeys(filterKey?: string): string[]; -} - -/** - * Repräsentiert den Status eines User. - */ -declare class UserStatus { - /** - * Liefert den numerischen Wert das UserStatus. - */ - getNumericStatus(): number; - /** - * Liefert die Information ob der aktuelle UserStatus mindestens so hoch ist, wie der übergebene UserStatus. - */ - isAtLeast(otherUserStatus: UserStatus): boolean; - /** - * - */ - static readonly Newbie: UserStatus; - /** - * - */ - static readonly Family: UserStatus; - /** - * - */ - static readonly Stammi: UserStatus; - /** - * - */ - static readonly HonoryMember: UserStatus; - /** - * - */ - static readonly Admin: UserStatus; - /** - * - */ - static readonly SystemBot: UserStatus; - /** - * - */ - static readonly Sysadmin: UserStatus; -} - -/** - * Repräsentiert den Typ eines User. - */ -declare class UserType { - /** - * Bot der App. - */ - static readonly AppBot: UserType; - /** - * Bot des Knuddels-Chatsystems. - */ - static readonly SystemBot: UserType; - /** - * Menschlicher User. - */ - static readonly Human: UserType; -} - -/** - * VideoChannelData hält Informationen zu laufenden Video-Streams im Channel bereit. - */ -declare class VideoChannelData { - /** - * Liefert alle User die im Channel derzeit ihr Video streamen. - */ - getStreamingVideoUsers(): User[]; -} diff --git a/types/knuddels-userapps-api/knuddels-userapps-api-tests.ts b/types/knuddels-userapps-api/knuddels-userapps-api-tests.ts index 4ee25c84ec..25319722c0 100644 --- a/types/knuddels-userapps-api/knuddels-userapps-api-tests.ts +++ b/types/knuddels-userapps-api/knuddels-userapps-api-tests.ts @@ -8,7 +8,7 @@ class Server implements App { onAppStart() { KnuddelsServer.getChannel() .getOnlineUsers(UserType.Human) - .forEach((user) => { + .forEach((user: User) => { this.onUserJoined(user); }); } @@ -23,7 +23,9 @@ class Server implements App { onUserLeft(user: User) { if (this.usersPlaying.get(user.getNick()) === 1) { KnuddelsServer.getDefaultBotUser() - .transferKnuddel(user, new KnuddelAmount(1), 'Du hast den Channel verlassen.'); + .transferKnuddel(user, new KnuddelAmount(1), { + displayReasonText: 'Du hast den Channel verlassen.' + }); this.usersPlaying.delete(user.getNick()); } @@ -39,8 +41,10 @@ class Server implements App { const user = KnuddelsServer.getUserAccess() .getUserById(userId); - KnuddelsServer.getDefaultBotUser() - .transferKnuddel(user, new KnuddelAmount(1), 'Die App fährt gleich herunter.'); + KnuddelsServer.getDefaultBotUser() + .transferKnuddel(user, new KnuddelAmount(1), { + displayReasonText: 'Die App fährt gleich herunter.' + }); user.getAppContentSessions() .forEach((session: AppContentSession) => { session.remove(); @@ -104,7 +108,9 @@ class Server implements App { if (hasWon) { KnuddelsServer.getDefaultBotUser() - .transferKnuddel(user, new KnuddelAmount(2), 'Richtig getippt...'); + .transferKnuddel(user, new KnuddelAmount(2), { + displayReasonText: 'Richtig getippt...' + }); } setTimeout(() => { diff --git a/types/koa-html-minifier/index.d.ts b/types/koa-html-minifier/index.d.ts new file mode 100644 index 0000000000..5343257116 --- /dev/null +++ b/types/koa-html-minifier/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for koa-html-minifier 1.0 +// Project: https://github.com/koajs/html-minifier +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Middleware } from 'koa'; +import { Options } from 'html-minifier'; + +declare function minifier(options?: Options): Middleware; + +declare namespace minifier {} + +export = minifier; diff --git a/types/koa-html-minifier/koa-html-minifier-tests.ts b/types/koa-html-minifier/koa-html-minifier-tests.ts new file mode 100644 index 0000000000..c068d303af --- /dev/null +++ b/types/koa-html-minifier/koa-html-minifier-tests.ts @@ -0,0 +1,8 @@ +import * as Koa from 'koa'; +import * as KoaHtmlMinifier from 'koa-html-minifier'; + +const app = new Koa() + .use(KoaHtmlMinifier()) + .use(KoaHtmlMinifier({ + collapseWhitespace: true + })); diff --git a/types/koa-html-minifier/tsconfig.json b/types/koa-html-minifier/tsconfig.json new file mode 100644 index 0000000000..9a46770f6f --- /dev/null +++ b/types/koa-html-minifier/tsconfig.json @@ -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", + "koa-html-minifier-tests.ts" + ] +} diff --git a/types/koa-html-minifier/tslint.json b/types/koa-html-minifier/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-html-minifier/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-joi-router/index.d.ts b/types/koa-joi-router/index.d.ts index bf3f387d31..e9e8670726 100644 --- a/types/koa-joi-router/index.d.ts +++ b/types/koa-joi-router/index.d.ts @@ -1,30 +1,36 @@ // Type definitions for koa-joi-router 5.0 // Project: https://github.com/koajs/joi-router // Definitions by: Matthew Bull +// Dave Welsh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 import * as Koa from 'koa'; import * as Joi from 'joi'; -interface Spec { - method: string; - path: string|RegExp; - handler: (ctx: createRouter.Context) => void; - validate?: { - type: string; - body?: Joi.AnySchema; - params?: Joi.AnySchema; - output?: {[status: number]: Joi.AnySchema}; - }; -} - interface createRouter { (): createRouter.Router; Joi: typeof Joi; } declare namespace createRouter { + interface Spec { + method: string; + path: string|RegExp; + handler: (ctx: Context) => void; + validate?: { + header?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + query?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + params?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + body?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + maxBody?: number; + failure?: number; + type?: 'form'|'json'|'multipart'; + output?: {[status: number]: Joi.AnySchema}; + continueOnError?: boolean; + }; + } + interface Request extends Koa.Request { body: any; params: {[key: string]: string}; diff --git a/types/koa-joi-router/koa-joi-router-tests.ts b/types/koa-joi-router/koa-joi-router-tests.ts index 76a392bdec..90dac8d752 100644 --- a/types/koa-joi-router/koa-joi-router-tests.ts +++ b/types/koa-joi-router/koa-joi-router-tests.ts @@ -2,7 +2,7 @@ import router = require('koa-joi-router'); const { Joi } = router; -const spec1 = { +const spec1: router.Spec = { path: '/user', method: 'POST', handler: (ctx: router.Context) => ctx.body = '', @@ -10,7 +10,7 @@ const spec1 = { router().route(spec1); -const spec2 = { +const spec2: router.Spec = { method: 'PATCH', path: '/user', validate: { @@ -21,7 +21,7 @@ const spec2 = { router().route(spec2); -const spec3 = { +const spec3: router.Spec = { method: 'PATCH', path: '/user', validate: { @@ -33,7 +33,7 @@ const spec3 = { router().route(spec3); -const spec4 = { +const spec4: router.Spec = { method: 'PATCH', path: '/user', validate: { @@ -50,7 +50,7 @@ const spec4 = { router().route(spec4); -const spec5 = { +const spec5: router.Spec = { method: 'PUT', path: '/user', handler: (ctx: router.Context) => { @@ -61,7 +61,7 @@ const spec5 = { router().route(spec5); -const spec6 = { +const spec6: router.Spec = { method: 'GET', path: '/user', handler: (ctx: router.Context) => { @@ -72,6 +72,39 @@ const spec6 = { router().route(spec6); +const spec7: router.Spec = { + method: 'GET', + path: '/user', + validate: { + query: { + id: Joi.number(), + name: Joi.string(), + } + }, + handler: (ctx: router.Context) => { + ctx.status = 201; + ctx.body = ctx.request.params; + }, +}; + +router().route(spec7); + +const spec8: router.Spec = { + method: 'POST', + path: '/user', + validate: { + header: { + authentication: Joi.string(), + } + }, + handler: (ctx: router.Context) => { + ctx.status = 201; + ctx.body = ctx.request.params; + }, +}; + +router().route(spec8); + router().route([spec1, spec2, spec3]); router().routes.map(({ path }) => path); diff --git a/types/koa__cors/index.d.ts b/types/koa__cors/index.d.ts index 25d337716e..da58136652 100644 --- a/types/koa__cors/index.d.ts +++ b/types/koa__cors/index.d.ts @@ -1,10 +1,13 @@ // Type definitions for @koa/cors 2.2 // Project: https://github.com/koajs/cors -// Definitions by: Xavier Stouder , Izayoi Ko , Steve Hipwell +// Definitions by: Xavier Stouder +// Izayoi Ko +// Steve Hipwell +// Steven McDowall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as Koa from "koa"; +import * as Koa from 'koa'; export = cors; @@ -12,7 +15,7 @@ declare function cors(options?: cors.Options): Koa.Middleware; declare namespace cors { interface Options { - origin?: ((req: Koa.Request) => string) | string; + origin?: ((ctx: Koa.Context) => string) | string; allowMethods?: string[] | string; exposeHeaders?: string[] | string; allowHeaders?: string[] | string; diff --git a/types/koa__cors/koa__cors-tests.ts b/types/koa__cors/koa__cors-tests.ts index 135845f205..25f068eb13 100644 --- a/types/koa__cors/koa__cors-tests.ts +++ b/types/koa__cors/koa__cors-tests.ts @@ -3,3 +3,11 @@ import cors = require('@koa/cors'); const app = new Koa(); app.use(cors()); + +// Trying using cors() passing in a function .. +function testCorsFunction(ctx: Koa.Context) { + const requestOrigin = ctx.request.origin; + return requestOrigin; +} + +app.use(cors({ origin: testCorsFunction })); diff --git a/types/lazy.js/index.d.ts b/types/lazy.js/index.d.ts index 3a44d2ce40..cea9ef0dea 100644 --- a/types/lazy.js/index.d.ts +++ b/types/lazy.js/index.d.ts @@ -4,259 +4,283 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace LazyJS { - interface LazyStatic { - - (value: string): StringLikeSequence; - (value: T[]): ArrayLikeSequence; - (value: any[]): ArrayLikeSequence; - (value: Object): ObjectLikeSequence; - (value: Object): ObjectLikeSequence; - - strict(): LazyStatic; - - generate(generatorFn: GeneratorCallback, length?: number): GeneratedSequence; - - range(to: number): GeneratedSequence; - range(from: number, to: number, step?: number): GeneratedSequence; - - repeat(value: T, count?: number): GeneratedSequence; - - on(eventType: string): Sequence; - - readFile(path: string): StringLikeSequence; - makeHttpRequest(path: string): StringLikeSequence; + (value: string): StringLikeSequence; + (value: T[]): ArrayLikeSequence; + (value: any[]): ArrayLikeSequence; + (value: Object): ObjectLikeSequence; + (value: Object): ObjectLikeSequence; + + strict(): LazyStatic; + + generate( + generatorFn: GeneratorCallback, + length?: number + ): GeneratedSequence; + + range(to: number): GeneratedSequence; + range(from: number, to: number, step?: number): GeneratedSequence; + + repeat(value: T, count?: number): GeneratedSequence; + + on(eventType: string): Sequence; + + readFile(path: string): StringLikeSequence; + makeHttpRequest(path: string): StringLikeSequence; } - + interface ArrayLike { - length: number; - [index: number]: T; + length: number; + [index: number]: T; } - + interface Callback { - (): void; + (): void; } - + interface ErrorCallback { - (error: any): void; + (error: any): void; } - + interface ValueCallback { - (value: T): void; + (value: T): void; } - + interface GetKeyCallback { - (value: T): string; + (value: T): string; } - - interface TestCallback { - (value: T): boolean; + + interface TestCallback { + (value: T, index: U): boolean; } - + interface MapCallback { - (value: T): U; + (value: T): U; } - + interface MapStringCallback { - (value: string): string; + (value: string): string; } - + interface NumberCallback { - (value: T): number; + (value: T): number; } - + interface MemoCallback { - (memo: U, value: T): U; + (memo: U, value: T): U; } - + interface GeneratorCallback { - (index: number): T; + (index: number): T; } - + interface CompareCallback { - (x: any, y: any): number; + (x: any, y: any): number; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + interface Iterator { - new (sequence: Sequence): Iterator; - current(): T; - moveNext(): boolean; + new (sequence: Sequence): Iterator; + current(): T; + moveNext(): boolean; } - + interface GeneratedSequence extends Sequence { - new(generatorFn: GeneratorCallback, length: number): GeneratedSequence; - length(): number; + new (generatorFn: GeneratorCallback, length: number): GeneratedSequence< + T + >; + length(): number; } - + interface AsyncSequence extends SequenceBase { - each(callback: ValueCallback): AsyncHandle; + each(callback: ValueCallback): AsyncHandle; } - + interface AsyncHandle { - cancel(): void; - onComplete(callback: Callback): void; - onError(callback: ErrorCallback): void; + cancel(): void; + onComplete(callback: Callback): void; + onError(callback: ErrorCallback): void; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + namespace Sequence { - function define(methodName: string[], overrides: Object): Function; + function define(methodName: string[], overrides: Object): Function; } - + interface Sequence extends SequenceBase { - each(eachFn: ValueCallback): Sequence; + each(eachFn: ValueCallback): Sequence; } - + interface SequenceBase extends SequenceBaser { - first(): any; - first(count: number): Sequence; - indexOf(value: any, startIndex?: number): Sequence; - - last(): any; - last(count: number): Sequence; - lastIndexOf(value: any): Sequence; - - reverse(): Sequence; + first(): any; + first(count: number): Sequence; + indexOf(value: any, startIndex?: number): Sequence; + + last(): any; + last(count: number): Sequence; + lastIndexOf(value: any): Sequence; + + reverse(): Sequence; } - + interface SequenceBaser { - // TODO improve define() (needs ugly overload) - async(interval: number): AsyncSequence; - chunk(size: number): Sequence; - compact(): Sequence; - concat(var_args: T[]): Sequence; - consecutive(length: number): Sequence; - contains(value: T): boolean; - countBy(keyFn: GetKeyCallback): ObjectLikeSequence; - countBy(propertyName: string): ObjectLikeSequence; - dropWhile(predicateFn: TestCallback): Sequence; - every(predicateFn: TestCallback): boolean; - filter(predicateFn: TestCallback): Sequence; - find(predicateFn: TestCallback): T; - findWhere(properties: Object): T; - - flatten(): Sequence; - groupBy(keyFn: GetKeyCallback): ObjectLikeSequence; - initial(count?: number): Sequence; - intersection(var_args: T[]): Sequence; - invoke(methodName: string): Sequence; - isEmpty(): boolean; - join(delimiter?: string): string; - map(mapFn: MapCallback): Sequence; - - max(valueFn?: NumberCallback): T; - min(valueFn?: NumberCallback): T; - none(valueFn?: TestCallback): boolean; - pluck(propertyName: string): Sequence; - reduce(aggregatorFn: MemoCallback, memo?: U): U; - reduceRight(aggregatorFn: MemoCallback, memo: U): U; - reject(predicateFn: TestCallback): Sequence; - rest(count?: number): Sequence; - shuffle(): Sequence; - some(predicateFn?: TestCallback): boolean; - sort(sortFn?: CompareCallback, descending?: boolean): Sequence; - sortBy(sortFn: string, descending?: boolean): Sequence; - sortBy(sortFn: NumberCallback, descending?: boolean): Sequence; - sortedIndex(value: T): Sequence; - size(): number; - sum(valueFn?: NumberCallback): T; - takeWhile(predicateFn: TestCallback): Sequence; - union(var_args: T[]): Sequence; - uniq(): Sequence; - where(properties: Object): Sequence; - without(...var_args: T[]): Sequence; - without(var_args: T[]): Sequence; - zip(var_args: T[]): Sequence; - - toArray(): T[]; - toObject(): Object; + // TODO improve define() (needs ugly overload) + async(interval: number): AsyncSequence; + chunk(size: number): Sequence; + compact(): Sequence; + concat(var_args: T[]): Sequence; + consecutive(length: number): Sequence; + contains(value: T): boolean; + countBy(keyFn: GetKeyCallback): ObjectLikeSequence; + countBy(propertyName: string): ObjectLikeSequence; + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): T; + findWhere(properties: Object): T; + flatten(): Sequence; + groupBy(keyFn: GetKeyCallback): ObjectLikeSequence; + initial(count?: number): Sequence; + intersection(var_args: T[]): Sequence; + invoke(methodName: string): Sequence; + isEmpty(): boolean; + join(delimiter?: string): string; + map(mapFn: MapCallback): Sequence; + max(valueFn?: NumberCallback): T; + min(valueFn?: NumberCallback): T; + none(valueFn?: TestCallback): boolean; + pluck(propertyName: string): Sequence; + reduce(aggregatorFn: MemoCallback, memo?: U): U; + reduceRight(aggregatorFn: MemoCallback, memo: U): U; + reject(predicateFn: TestCallback): Sequence; + rest(count?: number): Sequence; + shuffle(): Sequence; + size(): number; + some(predicateFn?: TestCallback): boolean; + sort(sortFn?: CompareCallback, descending?: boolean): Sequence; + sortBy(sortFn: NumberCallback, descending?: boolean): Sequence; + sortBy(sortFn: string, descending?: boolean): Sequence; + sortedIndex(value: T): Sequence; + sum(valueFn?: NumberCallback): T; + takeWhile(predicateFn: TestCallback): Sequence; + toArray(): T[]; + toObject(): Object; + union(var_args: T[]): Sequence; + uniq(): Sequence; + where(properties: Object): Sequence; + without(...var_args: T[]): Sequence; + without(var_args: T[]): Sequence; + zip(var_args: T[]): Sequence; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + namespace ArrayLikeSequence { - function define(methodName: string[], overrides: Object): Function; + function define(methodName: string[], overrides: Object): Function; } - + interface ArrayLikeSequence extends Sequence { - // define()X; - concat(var_args: T[]): ArrayLikeSequence; - first(count?: number): ArrayLikeSequence; - get(index: number): T; - length(): number; - map(mapFn: MapCallback): ArrayLikeSequence; - pop(): ArrayLikeSequence; - rest(count?: number): ArrayLikeSequence; - reverse(): ArrayLikeSequence; - shift(): ArrayLikeSequence; - slice(begin: number, end?: number): ArrayLikeSequence; + // define()X; + concat(var_args: T[]): ArrayLikeSequence; + first(count?: number): ArrayLikeSequence; + get(index: number): T; + length(): number; + map(mapFn: MapCallback): ArrayLikeSequence; + pop(): ArrayLikeSequence; + push(value: T): ArrayLikeSequence; + rest(count?: number): ArrayLikeSequence; + reverse(): ArrayLikeSequence; + shift(): ArrayLikeSequence; + slice(begin: number, end?: number): ArrayLikeSequence; + unshift(value: T): ArrayLikeSequence; + + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): T; + none(valueFn?: TestCallback): boolean; + reject(predicateFn: TestCallback): Sequence; + some(predicateFn?: TestCallback): boolean; + takeWhile(predicateFn: TestCallback): Sequence; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + namespace ObjectLikeSequence { - function define(methodName: string[], overrides: Object): Function; + function define(methodName: string[], overrides: Object): Function; } - + interface ObjectLikeSequence extends Sequence { - assign(other: Object): ObjectLikeSequence; - // throws error - //async(): X; - defaults(defaults: Object): ObjectLikeSequence; - functions(): Sequence; - get(property: string): ObjectLikeSequence; - invert(): ObjectLikeSequence; - keys(): Sequence; - merge(others: Object | ObjectLikeSequence, mergeFn?: Function): ObjectLikeSequence; - omit(properties: string[]): ObjectLikeSequence; - pairs(): Sequence; - pick(properties: string[]): ObjectLikeSequence; - toArray(): T[]; - toObject(): Object; - values(): Sequence; + assign(other: Object): ObjectLikeSequence; + // throws error + //async(): X; + defaults(defaults: Object): ObjectLikeSequence; + functions(): Sequence; + get(property: string): ObjectLikeSequence; + invert(): ObjectLikeSequence; + keys(): Sequence; + merge(others: Object | ObjectLikeSequence, mergeFn?: Function): ObjectLikeSequence; + omit(properties: string[]): ObjectLikeSequence; + pairs(): Sequence; + pick(properties: string[]): ObjectLikeSequence; + toArray(): T[]; + toObject(): Object; + values(): Sequence; + watch(propertyNames: string | string[]): Sequence<{property: string; value: any;}>; + + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): T; + none(valueFn?: TestCallback): boolean; + reject(predicateFn: TestCallback): Sequence; + some(predicateFn?: TestCallback): boolean; + takeWhile(predicateFn: TestCallback): Sequence; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + namespace StringLikeSequence { - function define(methodName: string[], overrides: Object): Function; + function define(methodName: string[], overrides: Object): Function; } - + interface StringLikeSequence extends SequenceBaser { - charAt(index: number): string; - charCodeAt(index: number): number; - contains(value: string): boolean; - endsWith(suffix: string): boolean; + charAt(index: number): string; + charCodeAt(index: number): number; + contains(value: string): boolean; + endsWith(suffix: string): boolean; + first(): string; + indexOf(substring: string, startIndex?: number): number; + last(): string; + last(count: number): StringLikeSequence; + lastIndexOf(substring: string, startIndex?: number): number; + mapString(mapFn: MapStringCallback): StringLikeSequence; + match(pattern: RegExp): StringLikeSequence; + reverse(): StringLikeSequence; + split(delimiter: RegExp): StringLikeSequence; + split(delimiter: string): StringLikeSequence; + startsWith(prefix: string): boolean; + substring(start: number, stop?: number): StringLikeSequence; + toLowerCase(): StringLikeSequence; + toUpperCase(): StringLikeSequence; - first(): string; - first(count: number): StringLikeSequence; - - indexOf(substring: string, startIndex?: number): number; - - last(): string; - last(count: number): StringLikeSequence; - - lastIndexOf(substring: string, startIndex?: number): number; - mapString(mapFn: MapStringCallback): StringLikeSequence; - match(pattern: RegExp): StringLikeSequence; - reverse(): StringLikeSequence; - - split(delimiter: string): StringLikeSequence; - split(delimiter: RegExp): StringLikeSequence; - - startsWith(prefix: string): boolean; - substring(start: number, stop?: number): StringLikeSequence; - toLowerCase(): StringLikeSequence; - toUpperCase(): StringLikeSequence; + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): string; + first(count: number): StringLikeSequence; + none(valueFn?: TestCallback): boolean; + reject(predicateFn: TestCallback): Sequence; + some(predicateFn?: TestCallback): boolean; + takeWhile(predicateFn: TestCallback): Sequence; } -} - -declare var Lazy: LazyJS.LazyStatic; - -declare module 'lazy.js' { -export = Lazy; -} - + } + + declare var Lazy: LazyJS.LazyStatic; + + declare module 'lazy.js' { + export = Lazy; + } + \ No newline at end of file diff --git a/types/less/index.d.ts b/types/less/index.d.ts index bca5c21c33..7d69273a52 100644 --- a/types/less/index.d.ts +++ b/types/less/index.d.ts @@ -52,6 +52,11 @@ declare namespace Less { interface StaticOptions { async: boolean; fileAsync: boolean; + modifyVars: { [variable: string]: string }; + } + + interface ImportManager { + contents: { [fileName: string]: string }; } interface Options { @@ -76,21 +81,33 @@ declare namespace Less { map: string; imports: string[]; } + + interface RefreshOutput { + endTime: Date; + startTime: Date; + sheets: number; + totalMilliseconds: number; + } } interface LessStatic { options: Less.StaticOptions; - - modifyVars(vars: { [name: string]: string }): void; - + + importManager?: Less.ImportManager; + sheets: HTMLLinkElement[]; + + modifyVars(vars: { [name: string]: string }): Promise; + refreshStyles(): void; - + render(input: string, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; render(input: string, options: Less.Options, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; render(input: string): Promise; render(input: string, options: Less.Options): Promise; + refresh(reload?: boolean, modifyVars?: { [variable: string]: string }, clearFileCache?: boolean): Promise; + version: number[]; watch(): void; diff --git a/types/less/less-tests.ts b/types/less/less-tests.ts index 5d0029475a..20a1f587a9 100644 --- a/types/less/less-tests.ts +++ b/types/less/less-tests.ts @@ -39,8 +39,22 @@ less.render("h1 { background: red; }", options); less.modifyVars({ '@buttonFace': '#5B83AD', '@buttonText': '#D9EEF2' +}).then((output) => { + console.log('Successfully modified vars.'); }); less.refreshStyles(); less.watch(); + +less.refresh(true, { + '@buttonFace': '#5B83AD' +}, true).then((output) => { + console.log('successfully refreshed less files'); +}); + +if (less.importManager) { + for (let fileName in less.importManager.contents) { + let fileContents = less.importManager.contents[fileName]; + } +} \ No newline at end of file diff --git a/types/lodash/common/common.d.ts b/types/lodash/common/common.d.ts index ccbd9d30f1..864450b1bd 100644 --- a/types/lodash/common/common.d.ts +++ b/types/lodash/common/common.d.ts @@ -212,6 +212,7 @@ declare module "../index" { type ValueIterateeCustom = ((value: T) => TResult) | IterateeShorthand; type ValueIteratorTypeGuard = (value: T) => value is S; type ValueKeyIteratee = ((value: T, key: string) => NotVoid) | IterateeShorthand; + type ValueKeyIterateeTypeGuard = (value: T, key: string) => value is S; type Comparator = (a: T, b: T) => boolean; type Comparator2 = (a: T1, b: T2) => boolean; diff --git a/types/lodash/common/object.d.ts b/types/lodash/common/object.d.ts index edb9e1736c..b136e9469b 100644 --- a/types/lodash/common/object.d.ts +++ b/types/lodash/common/object.d.ts @@ -3111,11 +3111,19 @@ declare module "../index" { * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ - pickBy( - object: T | null | undefined, - predicate: ObjectIteratorTypeGuard + pickBy( + object: Dictionary | null | undefined, + predicate: ValueKeyIterateeTypeGuard ): Dictionary; + /** + * @see _.pickBy + */ + pickBy( + object: NumericDictionary | null | undefined, + predicate: ValueKeyIterateeTypeGuard + ): NumericDictionary; + /** * @see _.pickBy */ @@ -3145,11 +3153,19 @@ declare module "../index" { /** * @see _.pickBy */ - pickBy( - this: LoDashImplicitWrapper, - predicate: ObjectIteratorTypeGuard + pickBy( + this: LoDashImplicitWrapper | null | undefined>, + predicate: ValueKeyIterateeTypeGuard ): LoDashImplicitWrapper>; + /** + * @see _.pickBy + */ + pickBy( + this: LoDashImplicitWrapper | null | undefined>, + predicate: ValueKeyIterateeTypeGuard + ): LoDashImplicitWrapper>; + /** * @see _.pickBy */ @@ -3179,11 +3195,19 @@ declare module "../index" { /** * @see _.pickBy */ - pickBy( - this: LoDashExplicitWrapper, - predicate: ObjectIteratorTypeGuard + pickBy( + this: LoDashExplicitWrapper | null | undefined>, + predicate: ValueKeyIterateeTypeGuard ): LoDashExplicitWrapper>; + /** + * @see _.pickBy + */ + pickBy( + this: LoDashExplicitWrapper | null | undefined>, + predicate: ValueKeyIterateeTypeGuard + ): LoDashExplicitWrapper>; + /** * @see _.pickBy */ diff --git a/types/lodash/fp.d.ts b/types/lodash/fp.d.ts index f373d81a27..cdc850d444 100644 --- a/types/lodash/fp.d.ts +++ b/types/lodash/fp.d.ts @@ -2887,28 +2887,35 @@ declare namespace _ { type LodashPick2x1 = (object: T | null | undefined) => lodash.PartialDeep; type LodashPick2x2 = (props: lodash.PropertyPath) => lodash.PartialDeep; interface LodashPickBy { - (predicate: lodash.ValueIteratorTypeGuard): LodashPickBy1x1; - (predicate: lodash.__, object: T | null | undefined): LodashPickBy1x2; - (predicate: lodash.ValueIteratorTypeGuard, object: T | null | undefined): lodash.Dictionary; - (predicate: lodash.ValueKeyIteratee): LodashPickBy2x1; - (predicate: lodash.__, object: lodash.Dictionary | null | undefined): LodashPickBy2x2; + (predicate: lodash.ValueKeyIterateeTypeGuard): LodashPickBy1x1; + (predicate: lodash.__, object: lodash.Dictionary | null | undefined): LodashPickBy1x2; + (predicate: lodash.ValueKeyIterateeTypeGuard, object: lodash.Dictionary | null | undefined): lodash.Dictionary; + (predicate: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPickBy2x2; + (predicate: lodash.ValueKeyIterateeTypeGuard, object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; + (predicate: lodash.ValueKeyIteratee): LodashPickBy3x1; (predicate: lodash.ValueKeyIteratee, object: lodash.Dictionary | null | undefined): lodash.Dictionary; - (predicate: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPickBy3x2; (predicate: lodash.ValueKeyIteratee, object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; + (predicate: lodash.__, object: T | null | undefined): LodashPickBy5x2; (predicate: lodash.ValueKeyIteratee, object: T | null | undefined): lodash.PartialObject; } - type LodashPickBy1x1 = (object: T | null | undefined) => lodash.Dictionary; - interface LodashPickBy1x2 { - (predicate: lodash.ValueIteratorTypeGuard): lodash.Dictionary; - (predicate: lodash.ValueKeyIteratee): lodash.PartialObject; + interface LodashPickBy1x1 { + (object: lodash.Dictionary | null | undefined): lodash.Dictionary; + (object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; } - interface LodashPickBy2x1 { + interface LodashPickBy1x2 { + (predicate: lodash.ValueKeyIterateeTypeGuard): lodash.Dictionary; + (predicate: lodash.ValueKeyIteratee): lodash.Dictionary; + } + interface LodashPickBy2x2 { + (predicate: lodash.ValueKeyIterateeTypeGuard): lodash.NumericDictionary; + (predicate: lodash.ValueKeyIteratee): lodash.NumericDictionary; + } + interface LodashPickBy3x1 { (object: lodash.Dictionary | null | undefined): lodash.Dictionary; (object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; (object: T1 | null | undefined): lodash.PartialObject; } - type LodashPickBy2x2 = (predicate: lodash.ValueKeyIteratee) => lodash.Dictionary; - type LodashPickBy3x2 = (predicate: lodash.ValueKeyIteratee) => lodash.NumericDictionary; + type LodashPickBy5x2 = (predicate: lodash.ValueKeyIteratee) => lodash.PartialObject; interface LodashProp { (path: TKey | [TKey]): LodashProp1x1; (path: lodash.__, object: TObject): LodashProp1x2; diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index e9eb4d98ae..0515136714 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -5631,9 +5631,19 @@ fp.now(); // $ExpectType number const mixedDictionary: _.Dictionary | null | undefined = anything; - _.pickBy(mixedDictionary, (item: string | number): item is number => typeof item === "number"); // $ExpectType Dictionary - _(mixedDictionary).pickBy((item: string | number): item is number => typeof item === "number"); // $ExpectType LoDashImplicitWrapper> - _.chain(mixedDictionary).pickBy((item: string | number): item is number => typeof item === "number"); // $ExpectType LoDashExplicitWrapper> + const userDefinedTypeGuard = (item: string | number): item is number => typeof item === "number"; + + _.pickBy(mixedDictionary, userDefinedTypeGuard); // $ExpectType Dictionary + _(mixedDictionary).pickBy(userDefinedTypeGuard); // $ExpectType LoDashImplicitWrapper> + _.chain(mixedDictionary).pickBy(userDefinedTypeGuard); // $ExpectType LoDashExplicitWrapper> + fp.pickBy(userDefinedTypeGuard)(mixedDictionary); // $ExpectType Dictionary + + const mixedNumericDictionary: _.NumericDictionary | null | undefined = anything; + + _.pickBy(mixedNumericDictionary, userDefinedTypeGuard); // $ExpectType NumericDictionary + _(mixedNumericDictionary).pickBy(userDefinedTypeGuard); // $ExpectType LoDashImplicitWrapper> + _.chain(mixedNumericDictionary).pickBy(userDefinedTypeGuard); // $ExpectType LoDashExplicitWrapper> + fp.pickBy(userDefinedTypeGuard)(mixedNumericDictionary); // $ExpectType NumericDictionary } // _.result diff --git a/types/lowdb/_lodash.d.ts b/types/lowdb/_lodash.d.ts index dc34d17db0..ca8aace259 100644 --- a/types/lowdb/_lodash.d.ts +++ b/types/lowdb/_lodash.d.ts @@ -1297,10 +1297,14 @@ declare module "./index" { this: LoDashExplicitSyncWrapper, ...props: _.PropertyPath[] ): LoDashExplicitSyncWrapper<_.PartialObject>; - pickBy( - this: LoDashExplicitSyncWrapper, - predicate: _.ObjectIteratorTypeGuard + pickBy( + this: LoDashExplicitSyncWrapper<_.Dictionary | null | undefined>, + predicate: _.ValueKeyIterateeTypeGuard ): LoDashExplicitSyncWrapper<_.Dictionary>; + pickBy( + this: LoDashExplicitSyncWrapper<_.NumericDictionary | null | undefined>, + predicate: _.ValueKeyIterateeTypeGuard + ): LoDashExplicitSyncWrapper<_.NumericDictionary>; pickBy( this: LoDashExplicitSyncWrapper<_.Dictionary | null | undefined>, predicate?: _.ValueKeyIteratee @@ -2889,10 +2893,14 @@ declare module "./index" { this: LoDashExplicitAsyncWrapper, ...props: _.PropertyPath[] ): LoDashExplicitAsyncWrapper<_.PartialObject>; - pickBy( - this: LoDashExplicitAsyncWrapper, - predicate: _.ObjectIteratorTypeGuard + pickBy( + this: LoDashExplicitAsyncWrapper<_.Dictionary | null | undefined>, + predicate: _.ValueKeyIterateeTypeGuard ): LoDashExplicitAsyncWrapper<_.Dictionary>; + pickBy( + this: LoDashExplicitAsyncWrapper<_.NumericDictionary | null | undefined>, + predicate: _.ValueKeyIterateeTypeGuard + ): LoDashExplicitAsyncWrapper<_.NumericDictionary>; pickBy( this: LoDashExplicitAsyncWrapper<_.Dictionary | null | undefined>, predicate?: _.ValueKeyIteratee diff --git a/types/lunr/index.d.ts b/types/lunr/index.d.ts index e16851b52b..da87ae95d8 100644 --- a/types/lunr/index.d.ts +++ b/types/lunr/index.d.ts @@ -238,7 +238,6 @@ declare namespace lunr { * A query builder callback provides a query object to be used to express * the query to perform on the index. * - * @callback lunr.Index~queryBuilder * @param query - The query object to build up. */ type QueryBuilder = (this: Query, query: Query) => void; @@ -658,7 +657,6 @@ declare namespace lunr { * A token update function is used when updating or optionally * when cloning a token. * - * @callback lunr.Token~updateFunction * @param str - The string representation of the token. * @param metadata - All metadata associated with this token. */ diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 17706a9002..e96e389894 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -319,8 +319,8 @@ declare module 'luxon' { } type IntervalObject = { - start: DateTime; - end: DateTime; + start?: DateTime; + end?: DateTime; }; class Interval { @@ -338,8 +338,8 @@ declare module 'luxon' { ): Interval; static fromISO(string: string, options?: DateTimeOptions): Interval; static invalid(reason?: string): Interval; - static merge(intervals: Interval[]): [Interval]; - static xor(intervals: Interval[]): [Interval]; + static merge(intervals: Interval[]): Interval[]; + static xor(intervals: Interval[]): Interval[]; end: DateTime; invalidReason: string; isValid: boolean; diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index de0aca9bfd..017f07b0c6 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -78,6 +78,7 @@ const i = Interval.fromDateTimes(now, later); i.length(); i.length('years'); i.contains(DateTime.local(2019)); +i.set({end: DateTime.local(2020)}); i.toISO(); i.toString(); diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 5f64b7470b..d85af4fd5a 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.45.0 +// Type definitions for Mapbox GL JS v0.47.0 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer , Patrick Reames // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -26,17 +26,15 @@ declare namespace mapboxgl { export class Map extends Evented { constructor(options?: MapboxOptions); - addControl(control: Control, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; + addControl(control: Control | IControl, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; - addControl(control: IControl, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; + removeControl(control: Control | IControl): this; - removeControl(control: Control): this; + resize(eventData?: EventData): this; - removeControl(control: IControl): this; + getBounds(): LngLatBounds; - resize(): this; - - getBounds(): mapboxgl.LngLatBounds; + getMaxBounds(): LngLatBounds; setMaxBounds(lnglatbounds?: LngLatBoundsLike): this; @@ -48,6 +46,10 @@ declare namespace mapboxgl { getMaxZoom(): number; + getRenderWorldCopies(): boolean; + + setRenderWorldCopies(renderWorldCopies?: boolean): this; + project(lnglat: LngLatLike): mapboxgl.Point; unproject(point: PointLike): mapboxgl.LngLat; @@ -62,13 +64,13 @@ declare namespace mapboxgl { querySourceFeatures(sourceID: string, parameters?: { sourceLayer?: string, filter?: any[] }): GeoJSON.Feature[]; - setStyle(style: mapboxgl.Style | string): this; + setStyle(style: mapboxgl.Style | string, options?: { diff?: boolean, localIdeographFontFamily?: string }): this; getStyle(): mapboxgl.Style; isStyleLoaded(): boolean; - addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; + addSource(id: string, source: VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; isSourceLoaded(id: string): boolean; @@ -76,9 +78,9 @@ declare namespace mapboxgl { removeSource(id: string): this; - getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; + getSource(id: string): VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource; - addImage(name: string, image: HTMLImageElement | ArrayBufferView, options?: { width?: number, height?: number, pixelRatio?: number }): this; + addImage(name: string, image: HTMLImageElement | ArrayBufferView | { width: number, height: number, data: Uint8Array | Uint8ClampedArray } | ImageData, options?: { pixelRatio?: number, sdf?: any }): this; hasImage(name: string): boolean; @@ -86,6 +88,8 @@ declare namespace mapboxgl { loadImage(url: string, callback: Function): this; + listImages(): string[]; + addLayer(layer: mapboxgl.Layer, before?: string): this; moveLayer(id: string, beforeId?: string): this; @@ -96,7 +100,7 @@ declare namespace mapboxgl { setFilter(layer: string, filter?: any[]): this; - setLayerZoomRange(layerId: string, minzoom?: number, maxzoom?: number): this; + setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this; getFilter(layer: string): any[]; @@ -108,10 +112,14 @@ declare namespace mapboxgl { getLayoutProperty(layer: string, name: string, klass?: string): any; - setLight(options: mapboxgl.Light, lightOptions: any): this; + setLight(options: mapboxgl.Light, lightOptions?: any): this; getLight(): mapboxgl.Light; + setFeatureState(feature: {source?: string, sourceLayer?: string, id?: string}, state: any): void; + + getFeatureState(feature: {source?: string, sourceLayer?: string, id?: string}): any; + getContainer(): HTMLElement; getCanvasContainer(): HTMLElement; @@ -134,7 +142,7 @@ declare namespace mapboxgl { setCenter(center: LngLatLike, eventData?: mapboxgl.EventData): this; - panBy(offset: number[], options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + panBy(offset: PointLike, options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; panTo(lnglat: LngLatLike, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; @@ -162,6 +170,8 @@ declare namespace mapboxgl { setPitch(pitch: number, eventData?: EventData): this; + cameraForBounds(bounds: LngLatBoundsLike, options?: {padding?: number | PaddingOptions, offset?: PointLike, maxZoom?: number}): CameraOptions; + fitBounds(bounds: LngLatBoundsLike, options?: mapboxgl.FitBoundsOptions, eventData?: mapboxgl.EventData): this; jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; @@ -204,6 +214,12 @@ declare namespace mapboxgl { /** initial map center */ center?: LngLatLike; + clickTolerance?: number; + + collectResourceTiming?: boolean; + + crossSourceCollisions?: boolean; + /** ID of the container element */ container?: string | Element; @@ -219,6 +235,8 @@ declare namespace mapboxgl { /** If true, the map will track and update the page URL according to map position */ hash?: boolean; + fadeDuration?: number; + /** If true, map creation will fail if the implementation determines that the performance of the created WebGL context would be dramatically lower than expected. */ failIfMajorPerformanceCaveat?: boolean; @@ -228,6 +246,8 @@ declare namespace mapboxgl { /** If true, enable keyboard shortcuts (see KeyboardHandler). */ keyboard?: boolean; + localIdeographFontFamily?: string; + logoPosition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; /** If set, the map is constrained to the given bounds. */ @@ -244,6 +264,8 @@ declare namespace mapboxgl { pitch?: number; + pitchWithRotate?: boolean; + refreshExpiredTiles?: boolean; renderWorldCopies?: boolean; @@ -257,6 +279,8 @@ declare namespace mapboxgl { /** If true, the map will automatically resize when the browser window resizes */ trackResize?: boolean; + transformRequest?: Function; + /** If true, enable the "pinch to rotate and zoom" interaction (see TouchZoomRotateHandler). */ touchZoomRotate?: boolean; @@ -500,7 +524,7 @@ declare namespace mapboxgl { } export interface Source { - type: 'vector' | 'raster' | 'geojson' | 'image' | 'video' | 'canvas'; + type: 'vector' | 'raster' | 'raster-dem' | 'geojson' | 'image' | 'video' | 'canvas'; } export type GeoJSONGeometry = GeoJSON.Point | GeoJSON.LineString | GeoJSON.MultiPoint | GeoJSON.Polygon | GeoJSON.MultiLineString | GeoJSON.MultiPolygon | GeoJSON.GeometryCollection; @@ -519,6 +543,12 @@ declare namespace mapboxgl { constructor(options?: mapboxgl.GeoJSONSourceOptions); setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; + + getClusterExpansionZoom(clusterId: number, callback: (error: any, zoom: number) => void): this; + + getClusterChildren(clusterId: number, callback: (error: any, features: GeoJSON.Feature[]) => void): this; + + getClusterLeaves(cluserId: number, limit: number, offset: number, callback: (error: any, features: GeoJSON.Feature[]) => void): this; } export interface GeoJSONSourceOptions { @@ -526,6 +556,8 @@ declare namespace mapboxgl { maxzoom?: number; + attribution?: string; + buffer?: number; tolerance?: number; @@ -591,6 +623,10 @@ declare namespace mapboxgl { canvas: string | HTMLCanvasElement; + play(): void; + + pause(): void; + getCanvas(): HTMLCanvasElement; setCoordinates(coordinates: number[][]): this; @@ -608,17 +644,35 @@ declare namespace mapboxgl { type: 'vector'; url?: string; tiles?: string[]; + bounds?: number[]; + scheme?: 'xyz' | 'tms'; minzoom?: number; maxzoom?: number; + attribution?: string; } interface RasterSource extends Source { type: 'raster'; url?: string; tiles?: string[]; + bounds?: number[]; minzoom?: number; maxzoom?: number; tileSize?: number; + scheme?: 'xyz' | 'tms'; + attribution?: string; + } + + interface RasterDemSource extends Source { + type: 'raster-dem'; + url?: string; + tiles?: string[]; + bounds?: number[]; + minzoom?: number; + maxzoom?: number; + tileSize?: number; + attribution?: string; + encoding?: 'terrarium' | 'mapbox'; } /** @@ -752,7 +806,7 @@ declare namespace mapboxgl { /** * Marker */ - export class Marker { + export class Marker extends Evented { constructor(options?: mapboxgl.MarkerOptions); constructor(element?: HTMLElement, options?: mapboxgl.MarkerOptions); @@ -765,15 +819,21 @@ declare namespace mapboxgl { setLngLat(lngLat: LngLatLike): this; + getElement(): HTMLElement; + setPopup(popup?: Popup): this; getPopup(): Popup; + togglePopup(): this; + getOffset(): PointLike; setOffset(offset: PointLike): this; - togglePopup(): this; + setDraggable(shouldBeDraggable: boolean): this; + + isDraggable(): boolean; } export interface MarkerOptions { @@ -784,6 +844,8 @@ declare namespace mapboxgl { anchor?: Anchor; color?: string + + draggable?: boolean; } /** @@ -831,6 +893,7 @@ declare namespace mapboxgl { export class MapTouchEvent { type: string; + target: Map; map: Map; originalEvent: TouchEvent; point: mapboxgl.Point; @@ -967,7 +1030,7 @@ declare namespace mapboxgl { metadata?: any; ref?: string; - source?: string | VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; + source?: string | VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; 'source-layer'?: string; @@ -1008,14 +1071,14 @@ declare namespace mapboxgl { } export interface FillPaint { - 'fill-antialias'?: boolean; + 'fill-antialias'?: boolean | Expression; 'fill-opacity'?: number | StyleFunction | Expression; 'fill-opacity-transition'?: Transition; 'fill-color'?: string | StyleFunction | Expression; 'fill-color-transition'?: Transition; 'fill-outline-color'?: string | StyleFunction | Expression; 'fill-outline-color-transition'?: Transition; - 'fill-translate'?: number[] | Expression; + 'fill-translate'?: number[]; 'fill-translate-transition'?: Transition; 'fill-translate-anchor'?: 'map' | 'viewport'; 'fill-pattern'?: string; @@ -1046,7 +1109,7 @@ declare namespace mapboxgl { visibility?: 'visible' | 'none'; 'line-cap'?: 'butt' | 'round' | 'square'; - 'line-join'?: 'bevel' | 'round' | 'miter'; + 'line-join'?: 'bevel' | 'round' | 'miter' | Expression; 'line-miter-limit'?: number | Expression; 'line-round-limit'?: number | Expression; } @@ -1077,7 +1140,7 @@ declare namespace mapboxgl { export interface SymbolLayout { visibility?: 'visible' | 'none'; - 'symbol-placement'?: 'point' | 'line'; + 'symbol-placement'?: 'point' | 'line' | 'line-center'; 'symbol-spacing'?: number | Expression; 'symbol-avoid-edges'?: boolean; 'icon-allow-overlap'?: boolean | StyleFunction; @@ -1092,7 +1155,7 @@ declare namespace mapboxgl { 'icon-padding'?: number | Expression; 'icon-keep-upright'?: boolean; 'icon-offset'?: number[] | StyleFunction | Expression; - 'icon-anchor'?: Anchor; + 'icon-anchor'?: Anchor | StyleFunction | Expression; 'icon-pitch-alignment'?: 'map' | 'viewport' | 'auto'; 'text-pitch-alignment'?: 'map' | 'viewport' | 'auto'; 'text-rotation-alignment'?: 'map' | 'viewport' | 'auto'; @@ -1103,7 +1166,7 @@ declare namespace mapboxgl { 'text-line-height'?: number | Expression; 'text-letter-spacing'?: number | Expression; 'text-justify'?: 'left' | 'center' | 'right'; - 'text-anchor'?: Anchor; + 'text-anchor'?: Anchor | StyleFunction | Expression; 'text-max-angle'?: number | Expression; 'text-rotate'?: number | StyleFunction | Expression; 'text-padding'?: number | Expression; @@ -1162,6 +1225,7 @@ declare namespace mapboxgl { 'raster-contrast'?: number | Expression; 'raster-contrast-transition'?: Transition; 'raster-fade-duration'?: number | Expression; + 'raster-resample'?: 'linear' | 'nearest'; } export interface CircleLayout { diff --git a/types/mark.js/mark.js-tests.ts b/types/mark.js/mark.js-tests.ts index a979990521..2f4bb62d9a 100644 --- a/types/mark.js/mark.js-tests.ts +++ b/types/mark.js/mark.js-tests.ts @@ -3,7 +3,7 @@ import * as Mark from 'mark.js'; /* test instance */ const mark = new Mark(document.querySelectorAll('div')); const markBySelector = new Mark('div'); -const markByElement = new Mark(document.body); +const markByElement = new Mark(document.body!); mark.mark('keyword'); mark.mark('keyword', { diff --git a/types/markdown-it/index.d.ts b/types/markdown-it/index.d.ts index 5f5129e8b0..24513c3e56 100644 --- a/types/markdown-it/index.d.ts +++ b/types/markdown-it/index.d.ts @@ -97,7 +97,7 @@ declare module MarkdownIt { type TokenRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => void; interface Rule { - (state: any): void; + (state: any, silent?: boolean): void; } interface Ruler { diff --git a/types/marko/marko-tests.ts b/types/marko/marko-tests.ts index 623ad12e5f..e43f61d8b5 100644 --- a/types/marko/marko-tests.ts +++ b/types/marko/marko-tests.ts @@ -18,7 +18,7 @@ const template: Template = require('template.marko'); // $ExpectType RenderResult template .renderSync({ name: 'Marko' }) - .appendTo(document.body); + .appendTo(document.body!); createServer((req, res) => { res.setHeader('content-type', 'text/html'); @@ -30,12 +30,12 @@ const template: Template = require('template.marko'); .render({ $global: { flags: ['mobile'] } }) .then((result) => { // $ExpectType RenderResult - result.appendTo(document.body); + result.appendTo(document.body!); }); template.render({}, (err: Error | null, result: RenderResult) => { // $ExpectType RenderResult - result.appendTo(document.body); + result.appendTo(document.body!); }); }; diff --git a/types/memjs/index.d.ts b/types/memjs/index.d.ts new file mode 100644 index 0000000000..8ab8290ae3 --- /dev/null +++ b/types/memjs/index.d.ts @@ -0,0 +1,410 @@ +// Type definitions for memjs 1.2 +// Project: http://github.com/memcachier/memjs +// Definitions by: Zongmin Lei +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +export interface ClientOptions { + /** + * `failoverTime` - how much to wait until retring a failed server. Default + * is 60 seconds. + */ + failoverTime?: number; + /** + * `retries` - the number of times to retry an operation in lieu of failures + * (default 2) + */ + retries?: number; + /** + * `retry_delay` - default is 0.2 + */ + retry_delay?: number; + /** + * `expires` - the default expiration in seconds to use (default 0 - never + * expire). If `expires` is greater than 30 days (60 x 60 x 24 x 30), it is + * treated as a UNIX time (number of seconds since January 1, 1970). + */ + expires?: number; + /** + * `logger` - a logger object that responds to `log(string)` method calls. + */ + logger?: { + log(...args: any[]): void; + }; +} +export class Client { + /** + * Creates a new client given an optional config string and optional hash of + * options. The config string should be of the form: + * + * "[user:pass@]server1[:11211],[user:pass@]server2[:11211],..." + * + * If the argument is not given, fallback on the `MEMCACHIER_SERVERS` environment + * variable, `MEMCACHE_SERVERS` environment variable or `"localhost:11211"`. + * + * The options hash may contain the options: + * + * * `retries` - the number of times to retry an operation in lieu of failures + * (default 2) + * * `expires` - the default expiration in seconds to use (default 0 - never + * expire). If `expires` is greater than 30 days (60 x 60 x 24 x 30), it is + * treated as a UNIX time (number of seconds since January 1, 1970). + * * `logger` - a logger object that responds to `log(string)` method calls. + * * `failover` - whether to failover to next server. Defaults to false. + * * `failoverTime` - how much to wait until retring a failed server. Default + * is 60 seconds. + * + * ~~~~ + * log(msg1[, msg2[, msg3[...]]]) + * ~~~~ + * + * Defaults to `console`. + * + * Or options for the servers including: + * * `username` and `password` for fallback SASL authentication credentials. + * * `timeout` in seconds to determine failure for operations. Default is 0.5 + * seconds. + * * 'conntimeout' in seconds to connection failure. Default is twice the value + * of `timeout`. + * * `keepAlive` whether to enable keep-alive functionality. Defaults to false. + * * `keepAliveDelay` in seconds to the initial delay before the first keepalive + * probe is sent on an idle socket. Defaults is 30 seconds. + */ + static create(serversStr?: string, options?: ClientOptions): Client; + + servers: string[]; + + /** + * Client initializer takes a list of Servers and an options dictionary. See Client.create for details. + * @param servers + * @param options + */ + constructor(servers: string, options?: ClientOptions); + + /** + * Chooses the server to talk to by hashing the given key. + * @param key + */ + server(key: string): string; + + /** + * GET + * + * Retrieves the value at the given key in memcache. + * + * The callback signature is: + * + * callback(err, value, flags) + * + * _value_ and _flags_ are both `Buffer`s. If the key is not found, the + * callback is invoked with null for both arguments and no error + * @param key + * @param callback + */ + get( + key: string, + callback: (err?: Error | null, value?: Buffer, flags?: Buffer) => void + ): void; + + /** + * SET + * + * Sets the given _key_ and _value_ in memcache. + * + * The options dictionary takes: + * * _expires_: overrides the default expiration (see `Client.create`) for this + * particular key-value pair. + * + * The callback signature is: + * + * callback(err, success) + * @param key + * @param value + * @param options + * @param callback + */ + set( + key: string, + value: string | Buffer, + options: { expires?: number }, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * ADD + * + * Adds the given _key_ and _value_ to memcache. The operation only succeeds + * if the key is not already set. + * + * The options dictionary takes: + * * _expires_: overrides the default expiration (see `Client.create`) for this + * particular key-value pair. + * + * The callback signature is: + * + * callback(err, success) + * @param key + * @param value + * @param options + * @param callback + */ + add( + key: string, + value: string | Buffer, + options: { expires?: number }, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * REPLACE + * + * Replaces the given _key_ and _value_ to memcache. The operation only succeeds + * if the key is already present. + * + * The options dictionary takes: + * * _expires_: overrides the default expiration (see `Client.create`) for this + * particular key-value pair. + * + * The callback signature is: + * + * callback(err, success) + * @param key + * @param value + * @param options + * @param callback + */ + replace( + key: string, + value: string | Buffer, + options: { expires?: number }, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * DELETE + * + * Deletes the given _key_ from memcache. The operation only succeeds + * if the key is already present. + * + * The callback signature is: + * + * callback(err, success) + * @param key + * @param callback + */ + delete( + key: string, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * INCREMENT + * + * Increments the given _key_ in memcache. + * + * The options dictionary takes: + * * _initial_: the value for the key if not already present, defaults to 0. + * * _expires_: overrides the default expiration (see `Client.create`) for this + * particular key-value pair. + * + * The callback signature is: + * + * callback(err, success, value) + * @param key + * @param amount + * @param options + * @param callback + */ + increment( + key: string, + amount: number, + options: { initial?: number; expires?: number }, + callback: ( + err?: Error | null, + success?: boolean, + value?: number + ) => void + ): void; + + /** + * DECREMENT + * + * Decrements the given _key_ in memcache. + * + * The options dictionary takes: + * * _initial_: the value for the key if not already present, defaults to 0. + * * _expires_: overrides the default expiration (see `Client.create`) for this + * particular key-value pair. + * + * The callback signature is: + * + * callback(err, success, value) + * @param key + * @param amount + * @param options + * @param callback + */ + decrement( + key: string, + amount: number, + options: { initial?: number; expires?: number }, + callback: ( + err?: Error | null, + success?: boolean, + value?: number + ) => void + ): void; + + /** + * APPEND + * + * Append the given _value_ to the value associated with the given _key_ in + * memcache. The operation only succeeds if the key is already present. The + * callback signature is: + * + * callback(err, success) + * @param key + * @param value + * @param callback + */ + append( + key: string, + value: string | Buffer, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * PREPEND + * + * Prepend the given _value_ to the value associated with the given _key_ in + * memcache. The operation only succeeds if the key is already present. The + * callback signature is: + * + * callback(err, success) + * @param key + * @param value + * @param callback + */ + prepend( + key: string, + value: string | Buffer, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * TOUCH + * + * Touch sets an expiration value, given by _expires_, on the given _key_ in + * memcache. The operation only succeeds if the key is already present. The + * callback signature is: + * + * callback(err, success) + * @param key + * @param expires + * @param callback + */ + touch( + key: string, + expires: number, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * FLUSH + * + * Flushes the cache on each connected server. The callback signature is: + * + * callback(lastErr, results) + * + * where _lastErr_ is the last error encountered (or null, in the common case + * of no errors). _results_ is a dictionary mapping `"hostname:port"` to either + * `true` (if the operation was successful), or an error. + * @param callback + */ + flush( + callback: ( + err?: Error | null, + results?: Record + ) => void + ): void; + + /** + * STATS_WITH_KEY + * + * Sends a memcache stats command with a key to each connected server. The + * callback is invoked **ONCE PER SERVER** and has the signature: + * + * callback(err, server, stats) + * + * _server_ is the `"hostname:port"` of the server, and _stats_ is a dictionary + * mapping the stat name to the value of the statistic as a string. + * @param key + * @param callback + */ + statsWithKey( + key: string, + callback: ( + err?: Error | null, + server?: string, + stats?: Record + ) => void + ): void; + + /** + * RESET_STATS + * + * Reset the statistics each server is keeping back to zero. This doesn't clear + * stats such as item count, but temporary stats such as total number of + * connections over time. + * + * The callback is invoked **ONCE PER SERVER** and has the signature: + * + * callback(err, server) + * + * _server_ is the `"hostname:port"` of the server. + * @param callback + */ + resetStats(callback: (err?: Error | null, server?: string) => void): void; + + /** + * QUIT + * + * Closes the connection to each server, notifying them of this intention. Note + * that quit can race against already outstanding requests when those requests + * fail and are retried, leading to the quit command winning and closing the + * connection before the retries complete. + */ + quit(): void; + + /** + * CLOSE + * + * Closes (abruptly) connections to all the servers. + */ + close(): void; + + /** + * Perform a generic single response operation (get, set etc) on a server + * serv: the server to perform the operation on + * request: a buffer containing the request + * seq: the sequence number of the operation. It is used to pin the callbacks + * to a specific operation and should never change during a `perform`. + * callback: a callback invoked when a response is received or the request + * fails + * retries: number of times to retry request on failure + * @param key + * @param request + * @param seq + * @param callback + * @param retries + */ + perform( + key: string, + request: Buffer, + seq: number, + callback: () => void, + retries: number + ): void; +} diff --git a/types/memjs/memjs-tests.ts b/types/memjs/memjs-tests.ts new file mode 100644 index 0000000000..2e3c34a3b5 --- /dev/null +++ b/types/memjs/memjs-tests.ts @@ -0,0 +1,10 @@ +import * as memjs from "memjs"; + +const client = memjs.Client.create(); + +client.set("hello", "world", { expires: 600 }, (err, val) => { + console.log(err, val); +}); +client.get("hello", (err, val) => { + console.log(err, val); +}); diff --git a/types/memjs/tsconfig.json b/types/memjs/tsconfig.json new file mode 100644 index 0000000000..8df1e4876a --- /dev/null +++ b/types/memjs/tsconfig.json @@ -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", + "memjs-tests.ts" + ] +} diff --git a/types/memjs/tslint.json b/types/memjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/memjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mithril/test/test-api.ts b/types/mithril/test/test-api.ts index 73e03edeae..66c026f47d 100644 --- a/types/mithril/test/test-api.ts +++ b/types/mithril/test/test-api.ts @@ -142,7 +142,7 @@ const FRAME_BUDGET = 100; }); }; - m.render(document.body, userInputs(users)); + m.render(document.body!, userInputs(users)); } //////////////////////////////////////////////////////////////////////////////// @@ -246,7 +246,7 @@ const FRAME_BUDGET = 100; }; // example 1 - m.route(document.body, "/", { + m.route(document.body!, "/", { "/": { view() { return m(Layout, m(Home)); @@ -260,7 +260,7 @@ const FRAME_BUDGET = 100; }); // example 2 - m.route(document.body, "/", { + m.route(document.body!, "/", { "/": { render() { return m(Layout, m(Home)); @@ -285,7 +285,7 @@ const FRAME_BUDGET = 100; }, }; - m.route(document.body, "/", { + m.route(document.body!, "/", { "/": { render() { return m(Anon1); @@ -313,7 +313,7 @@ const FRAME_BUDGET = 100; } }; - m.route(document.body, "/user/list", { + m.route(document.body!, "/user/list", { "/user/list": { onmatch: state.loadUsers, render() { @@ -330,7 +330,7 @@ const FRAME_BUDGET = 100; { let progress = 0; - m.mount(document.body, { + m.mount(document.body!, { view() { return [ m("input[type=file]", { onchange: upload }), @@ -396,7 +396,7 @@ const FRAME_BUDGET = 100; deserialize: value => value }) .then(svg => { - m.render(document.body, m.trust(svg)); + m.render(document.body!, m.trust(svg)); }); } diff --git a/types/mithril/test/test-class-component.ts b/types/mithril/test/test-class-component.ts index 0b70773c9e..44c81a8b56 100644 --- a/types/mithril/test/test-class-component.ts +++ b/types/mithril/test/test-class-component.ts @@ -112,7 +112,7 @@ class Comp4 implements ClassComponent { // // Test that all are mountable components // -m.route(document.body, '/', { +m.route(document.body!, '/', { '/comp0': Comp0, '/comp1': Comp1, '/comp2': Comp2, diff --git a/types/mithril/test/test-factory-component.ts b/types/mithril/test/test-factory-component.ts index 6d0102fe38..b53619fbf1 100644 --- a/types/mithril/test/test-factory-component.ts +++ b/types/mithril/test/test-factory-component.ts @@ -148,7 +148,7 @@ function comp5(): Component { // // Test that all are mountable components // -m.route(document.body, '/', { +m.route(document.body!, '/', { '/comp0': comp0, '/comp1': comp1, '/comp2': comp2, diff --git a/types/mithril/test/test-misc.ts b/types/mithril/test/test-misc.ts index 3f377fec60..548811247d 100644 --- a/types/mithril/test/test-misc.ts +++ b/types/mithril/test/test-misc.ts @@ -10,9 +10,9 @@ const params = parseQueryString('?id=123'); const qstr = buildQueryString({id: 123}); -render(document.body, 'Hello'); -render(document.body, h('h1', 'Test')); -render(document.body, [ +render(document.body!, 'Hello'); +render(document.body!, h('h1', 'Test')); +render(document.body!, [ h('h1', 'Test'), "abc", null, 123, false, h('p', 'Vnode array'), ['a', 123, undefined, h('div', 'Nested')] ]); diff --git a/types/mithril/test/test-route.ts b/types/mithril/test/test-route.ts index 7f82c9fa40..63f10e510e 100644 --- a/types/mithril/test/test-route.ts +++ b/types/mithril/test/test-route.ts @@ -66,7 +66,7 @@ const routeResolver: RouteResolver & RRState = { } }; -route(document.body, '/', { +route(document.body!, '/', { '/': component1, '/test1': { onmatch(args, path) { diff --git a/types/moment-timezone/index.d.ts b/types/moment-timezone/index.d.ts index fac79f728f..395ab77c82 100644 --- a/types/moment-timezone/index.d.ts +++ b/types/moment-timezone/index.d.ts @@ -53,7 +53,7 @@ declare module "moment" { names(): string[]; guess(ignoreCache?: boolean): string; - setDefault(timezone: string): void; + setDefault(timezone: string): MomentTimezone; } interface Moment { diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 8ce8f52fa4..cba04cb046 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -13,6 +13,7 @@ // Bastien Arata // Wan Bachtiar // Geraldine Lemeur +// Jimmy Shimizu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -201,8 +202,10 @@ export interface SocketOptions { autoReconnect?: boolean; // TCP Socket NoDelay option. default:true noDelay?: boolean; - // TCP KeepAlive on the socket with a X ms delay before start. default:0 - keepAlive?: number; + // TCP KeepAlive enabled on the socket. default:true + keepAlive?: boolean; + // TCP KeepAlive initial delay before sending first keep-alive packet when idle. default:300000 + keepAliveInitialDelay?: number; // TCP Connection timeout setting. default 0 connectTimeoutMS?: number; // TCP Socket timeout setting. default 0 diff --git a/types/mongodb/v2/index.d.ts b/types/mongodb/v2/index.d.ts index 4c26149d81..bc23cdf893 100644 --- a/types/mongodb/v2/index.d.ts +++ b/types/mongodb/v2/index.d.ts @@ -2,7 +2,6 @@ // Project: https://github.com/mongodb/node-mongodb-native/tree/2.2 // Definitions by: Federico Caselli // Alan Marcell -// Gady Piazza // Jason Dreyzehner // Gaurav Lahoti // Mariano Cortesi @@ -22,7 +21,7 @@ export function connect(uri: string, options?: MongoClientOptions): Promise; export function connect(uri: string, callback: MongoCallback): void; export function connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; -export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, ObjectId, Timestamp, DBRef } from 'bson'; +export { Binary, DBRef, Decimal128, Double, Int32, Long, MaxKey, MinKey, ObjectID, ObjectId, Timestamp } from 'bson'; // Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html export class MongoClient { @@ -158,8 +157,10 @@ export interface SocketOptions { autoReconnect?: boolean; // TCP Socket NoDelay option. default:true noDelay?: boolean; - // TCP KeepAlive on the socket with a X ms delay before start. default:0 - keepAlive?: number; + // TCP KeepAlive enabled on the socket. default:true + keepAlive?: boolean; + // TCP KeepAlive initial delay before sending first keep-alive packet when idle. default:300000 + keepAliveInitialDelay?: number; // TCP Connection timeout setting. default 0 connectTimeoutMS?: number; // TCP Socket timeout setting. default 0 diff --git a/types/moonjs/index.d.ts b/types/moonjs/index.d.ts index 13dcbbe04e..c003f7ad58 100644 --- a/types/moonjs/index.d.ts +++ b/types/moonjs/index.d.ts @@ -22,11 +22,11 @@ declare namespace Moon { } interface MoonConstructor { - new (options?: ConstructorOptions): Instance>; + new (options?: ConstructorOptions): Instance>; } interface MoonStatic extends MoonConstructor { - component(name: string, options: ComponentOptions): MoonConstructor; + component(name: string, options: ComponentOptions): MoonConstructor; config: MoonConfig; use(plugin: object): void; compile(template: string): void; diff --git a/types/moonjs/moonjs-tests.ts b/types/moonjs/moonjs-tests.ts index aa6527ea82..34d1d8d359 100644 --- a/types/moonjs/moonjs-tests.ts +++ b/types/moonjs/moonjs-tests.ts @@ -17,6 +17,7 @@ const count = app.get("count"); count; // $ExpectType number app.get("increment")(); // $ExpectType void app.callMethod("increment"); // $ExpectType any +app.get("blahblahblah"); // $ExpectError app.destroy(); diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index 109a515515..db1256e2a3 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -201,6 +201,7 @@ export declare class ConnectionPool extends events.EventEmitter { public close(): Promise; public close(callback: (err: any) => void): void; public request(): Request; + public transaction(): Transaction; } export declare class ConnectionError implements Error { @@ -297,6 +298,7 @@ export declare class Transaction extends events.EventEmitter { public commit(callback: (err?: any) => void): void; public rollback(): Promise; public rollback(callback: (err?: any) => void): void; + public request(): Request; } export declare class TransactionError implements Error { diff --git a/types/next/router.d.ts b/types/next/router.d.ts index 74aafd4a33..fe3563d473 100644 --- a/types/next/router.d.ts +++ b/types/next/router.d.ts @@ -62,7 +62,16 @@ export interface RouterProps { options?: EventChangeOptions, ): Promise; - // events + // events (deprecated soonish) + onAppUpdated?(nextRoute: string): void; + onBeforeHistoryChange?(as: string): void; + onHashChangeStart?(url: string): void; + onHashChangeComplete?(url: string): void; + onRouteChangeComplete?(url: string): void; + onRouteChangeError?(error: RouteChangeError, url: string): void; + onRouteChangeStart?(url: string): void; + + // events API (6.1.1+) readonly events: { on: (eventName: EventName, handler: EventHandler | ErrorEventHandler) => void; off: (eventName: EventName, handler: (url: string) => any) => void; diff --git a/types/node-zopfli-es/index.d.ts b/types/node-zopfli-es/index.d.ts new file mode 100644 index 0000000000..e015655d8b --- /dev/null +++ b/types/node-zopfli-es/index.d.ts @@ -0,0 +1,69 @@ +// Type definitions for node-zopfli-es 0.0 +// Project: https://github.com/jaeh/node-zopfli-es +// Definitions by: Alorel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Transform } from 'stream'; + +declare class Zopfli extends Transform { + constructor(format?: Zopfli.Format, options?: Zopfli.Options); + + static createGzip(options?: Zopfli.Options): Zopfli; + static createDeflate(options?: Zopfli.Options): Zopfli; + static createZlib(options?: Zopfli.Options): Zopfli; + + static gzipSync(options?: Zopfli.Options): Buffer; + static deflateSync(options?: Zopfli.Options): Buffer; + static zlibSync(options?: Zopfli.Options): Buffer; + + static deflate(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static deflate(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static deflate(input: Buffer, options?: Zopfli.Options): Promise; + + static gzip(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static gzip(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static gzip(input: Buffer, options?: Zopfli.Options): Promise; + + static zlib(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static zlib(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static zlib(input: Buffer, options?: Zopfli.Options): Promise; + + static compress(input: Buffer, format: Zopfli.Format, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static compress(input: Buffer, format: Zopfli.Format, cb: (err: Error, out: Buffer) => void): void; + static compress(input: Buffer, format: Zopfli.Format, options?: Zopfli.Options): Promise; +} + +declare namespace Zopfli { + type Format = 'deflate' | 'gzip' | 'zlib'; + + interface Options { + verbose?: boolean; + verbose_more?: boolean; + /** + * Maximum amount of times to rerun forward and backward pass to optimize LZ77 compression cost. + * Good values: 10, 15 for small files, 5 for files over several MB in size or it will be too slow. + */ + numiterations?: number; + /** + * If true, splits the data in multiple deflate blocks with optimal choice for the block boundaries. + * Block splitting gives better compression. + */ + blocksplitting?: boolean; + /** + * If true, chooses the optimal block split points only after doing the iterative LZ77 compression. + * If false, chooses the block split points first, then does iterative LZ77 on each individual block. + * Depending on the file, either first or last gives the best compression. + */ + blocksplittinglast?: boolean; + /** + * Maximum amount of blocks to split into (0 for unlimited, + * but this can give extreme results that hurt compression on some files). + */ + blocksplittingmax?: number; + } +} + +export = Zopfli; diff --git a/types/node-zopfli-es/node-zopfli-es-tests.ts b/types/node-zopfli-es/node-zopfli-es-tests.ts new file mode 100644 index 0000000000..3f3294cf3f --- /dev/null +++ b/types/node-zopfli-es/node-zopfli-es-tests.ts @@ -0,0 +1,51 @@ +import * as Zopfli from 'node-zopfli-es'; +import * as fs from 'fs'; + +const opts: Zopfli.Options = { + verbose: true, + numiterations: 1 +}; +let input: Buffer = Buffer.from('foo'); +const read = fs.createReadStream('foo'); +const write = fs.createWriteStream('foo'); + +function cb(e: Error, b: Buffer): void {} +function then(b: Buffer): void {} + +Zopfli.zlib(input, cb); +Zopfli.zlib(input, opts, cb); +Zopfli.zlib(input, opts).then(then); +Zopfli.zlib(input).then(then); + +Zopfli.gzip(input, cb); +Zopfli.gzip(input, opts, cb); +Zopfli.gzip(input, opts).then(then); +Zopfli.gzip(input).then(then); + +Zopfli.deflate(input, cb); +Zopfli.deflate(input, opts, cb); +Zopfli.deflate(input, opts).then(then); +Zopfli.deflate(input).then(then); + +Zopfli.compress(input, 'zlib', cb); +Zopfli.compress(input, 'zlib', opts, cb); +Zopfli.compress(input, 'zlib', opts).then(then); +Zopfli.compress(input, 'zlib').then(then); + +input = Zopfli.gzipSync(); +input = Zopfli.gzipSync(opts); + +input = Zopfli.deflateSync(); +input = Zopfli.deflateSync(opts); + +input = Zopfli.zlibSync(); +input = Zopfli.zlibSync(opts); + +read.pipe(Zopfli.createGzip()).pipe(write); +read.pipe(Zopfli.createGzip(opts)).pipe(write); + +read.pipe(Zopfli.createDeflate()).pipe(write); +read.pipe(Zopfli.createDeflate(opts)).pipe(write); + +read.pipe(Zopfli.createZlib()).pipe(write); +read.pipe(Zopfli.createZlib(opts)).pipe(write); diff --git a/types/node-zopfli-es/tsconfig.json b/types/node-zopfli-es/tsconfig.json new file mode 100644 index 0000000000..bbd6de30e8 --- /dev/null +++ b/types/node-zopfli-es/tsconfig.json @@ -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", + "node-zopfli-es-tests.ts" + ] +} diff --git a/types/node-zopfli-es/tslint.json b/types/node-zopfli-es/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/node-zopfli-es/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 43d4f25cc9..bb4b54efa7 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -2225,24 +2225,31 @@ declare module "child_process" { encoding: string | null; // specify `null`. } + export interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: string; + } + // no `options` definitely means stdout/stderr are `string`. - export function exec(command: string, callback?: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. - export function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; // `options` with well known `encoding` means stdout/stderr are definitely `string`. - export function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. - export function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + export function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; // `options` without an `encoding` means stdout/stderr are definitely `string`. - export function exec(command: string, options: ExecOptions, callback?: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; // fallback if nothing else matches. Worst case is always `string | Buffer`. - export function exec(command: string, options: ({ encoding?: string | null } & ExecOptions) | undefined | null, callback?: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + export function exec(command: string, options: ({ encoding?: string | null } & ExecOptions) | undefined | null, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace exec { @@ -2503,7 +2510,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): IterableIterator<[string, string]>; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index c3a23dc094..aae5512702 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -690,9 +690,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 9cceb11e71..de1b280260 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -2002,7 +2002,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): Iterator; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 6ab45137c4..43441e9840 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -538,9 +538,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index b93c70017b..a40d713dcf 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -2045,7 +2045,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): Iterator; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index a74a438665..4549ab7062 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -520,9 +520,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index 6acb0c62a7..8e6c649d00 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -2378,7 +2378,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): IterableIterator<[string, string]>; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; diff --git a/types/node/v8/node-tests.ts b/types/node/v8/node-tests.ts index 318062648a..9cec14a88e 100644 --- a/types/node/v8/node-tests.ts +++ b/types/node/v8/node-tests.ts @@ -654,9 +654,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 7d9b0dbb29..19259316b8 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -2459,7 +2459,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): IterableIterator<[string, string]>; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; diff --git a/types/node/v9/node-tests.ts b/types/node/v9/node-tests.ts index 30b0666773..3d7861f532 100644 --- a/types/node/v9/node-tests.ts +++ b/types/node/v9/node-tests.ts @@ -680,9 +680,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); diff --git a/types/ns-api/index.d.ts b/types/ns-api/index.d.ts index 267bb319c5..598c7dd493 100644 --- a/types/ns-api/index.d.ts +++ b/types/ns-api/index.d.ts @@ -10,47 +10,27 @@ interface nsApi { /** * Vertrektijden - departure times * - * @callback callback * @param station - Station ID - * @param callback - `function (err, data) {}` */ vertrektijden(station: string, callback: (err: string, data: {}) => void): void; /** * Reisadvies - travel advise - * - * @callback callback - * @param params - Parameters - * @param callback - `function (err, data) {}` */ reisadvies(params: {}, callback: (err: string, data: {}) => void): void; - /** - * Prijzen - tariffs - * - * @callback callback - * @param params - Parameters - * @param callback - `function (err, data) {}` - */ + /** Prijzen - tariffs */ prijzen(params: {}, callback: (err: any, data: {}) => void): void; /** * List available stations * - * @callback callback * @param [treeKey] - Group by this key - * @param callback - `function (err, data) {}` */ stations(treeKey: string, callback: (err: string, data: {}) => void): void; stations(callback: (err: string, data: {}) => void): void; - /** - * List disruptions - * - * @callback callback - * @param params - Parameters - * @param callback - `function (err, data) {}` - */ + /** List disruptions */ storingen(params: {}, callback: (err: string, data: {}) => void): void; } diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 36c659a7b2..a731343bc6 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -279,9 +279,25 @@ declare namespace Office { * Specifies the result of an asynchronous call. * * @remarks - *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
* - * Returned by the status property of the AsyncResult object. + * Returned by the {@link Office.AsyncResult.status | status} property of the {@link Office.AsyncResult | AsyncResult} object. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y
*/ enum AsyncResultStatus { /** @@ -297,7 +313,20 @@ declare namespace Office { * Specifies whether the add-in was just inserted or was already contained in the document. * * @remarks - *
HostsExcel, Project, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum InitializationReason { /** @@ -313,7 +342,24 @@ declare namespace Office { * Specifies the host Office application in which the add-in is running. * * @remarks - *
HostsExcel, Word, PowerPoint, Outlook, OneNote, Project, Access
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
OneNote Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ enum HostType { /** @@ -349,7 +395,24 @@ declare namespace Office { * Specifies the OS or other platform on which the Office host application is running. * * @remarks - *
HostsExcel, Word, PowerPoint, Outlook, OneNote, Project, Access
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
OneNote Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ enum PlatformType { /** @@ -388,7 +451,7 @@ declare namespace Office { */ interface AsyncResult { /** - * Gets the user-defined item passed to the optional `asyncContext` parameter of the invoked method in the same state as it was passed in. This the user-defined item (which can be of any JavaScript type: String, Number, Boolean, Object, Array, Null, or Undefined) passed to the optional `asyncContext` parameter of the invoked method. Returns Undefined, if you didn't pass anything to the asyncContext parameter. + * Gets the user-defined item passed to the optional `asyncContext` parameter of the invoked method in the same state as it was passed in. This returns the user-defined item (which can be of any JavaScript type: String, Number, Boolean, Object, Array, Null, or Undefined) passed to the optional `asyncContext` parameter of the invoked method. Returns Undefined, if you didn't pass anything to the asyncContext parameter. * * @remarks *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
@@ -414,9 +477,9 @@ declare namespace Office { * @remarks *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
* - * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the `getSelectedDataAsync` and `setSelectedDataAsync` methods of the Document object. + * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the {@link Office.Document.getSelectedDataAsync | getSelectedDataAsync} and {@link Office.Document.setSelectedDataAsync | setSelectedDataAsync} methods of the Document object. * - * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. For a complete listing of the "Async" methods, see the Remarks section of the AsyncResult object topic. + * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. For a complete listing of the "Async" methods, see the Remarks section of the {@link Office.AsyncResult | AsyncResult} object topic. */ value: any; } @@ -448,6 +511,7 @@ declare namespace Office { diagnostics: ContextInformation; /** * Gets the locale (language) specified by the user for the UI of the Office host application. + * * @remarks * When using in Outlook, the applicable modes are Compose or read. */ @@ -760,7 +824,8 @@ declare namespace Office { * @remarks * * - *
HostsExcel, OneNote, Outlook, PowerPoint, Word
Requirement setsIdentityAPI
+ * Requirement sets{@link https://docs.microsoft.com/office/dev/add-ins/develop/specify-office-hosts-and-api-requirements +| IdentityAPI} * * This API requires a single sign-on configuration that bridges the add-in to an Azure application. Office users sign-in with Organizational Accounts and Microsoft Accounts. Microsoft Azure returns tokens intended for both user account types to access resources in the Microsoft Graph. * @@ -1157,7 +1222,18 @@ declare namespace Office { /** * Specifies the state of the active view of the document, for example, whether the user can edit the document. * @remarks - *
HostsPowerPoint
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
PowerPoint Y Y Y
*/ enum ActiveView { /** @@ -1172,7 +1248,20 @@ declare namespace Office { /** * Specifies the type of the binding object that should be returned. * @remarks - *
HostsAccess, Excel, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
*/ enum BindingType { /** @@ -1184,7 +1273,7 @@ declare namespace Office { */ Matrix, /** - * Tabular data with a header row. Data is returned as a TableData object. + * Tabular data with a header row. Data is returned as a {@link Office.TableData | TableData} object. */ Table } @@ -1192,49 +1281,65 @@ declare namespace Office { * Specifies how to coerce data returned or set by the invoked method. * * @remarks - *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
+ * PowerPoint supports only `Office.CoercionType.Text`, `Office.CoercionType.Image`, and `Office.CoercionType.SlideRange`. * - * PowerPoint supports only `Office.CoercionType.Text`, `Office.CoercionType.Image`, and `Office.CoercionType.SlideRange`. Project supports only `Office.CoercionType.Text`. + * Project supports only `Office.CoercionType.Text`. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ enum CoercionType { /** - * Return or set data as text (string).Data is returned or set as a one-dimensional run of characters. + * Return or set data as text (string). Data is returned or set as a one-dimensional run of characters. */ Text, /** * Return or set data as tabular data with no headers. Data is returned or set as an array of arrays containing one-dimensional runs of characters. For example, three rows of string values in two columns would be: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. - * @remarks - * Only applies to data in Excel and Word. + * + * Note: Only applies to data in Excel and Word. */ Matrix, /** * Return or set data as tabular data with optional headers. Data is returned or set as an array of arrays with optional headers. - * @remarks - * Only applies to data in Access, Excel and Word. + * + * Note: Only applies to data in Access, Excel, and Word. */ Table, /** * Return or set data as HTML. - * @remarks - * Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). + * + * Note: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). */ Html, /** * Return or set data as Office Open XML. - * @remarks - * Only applies to data in Word. + * + * Note: Only applies to data in Word. */ Ooxml, /** - * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides.For example, `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. - * @remarks - * Only applies to data in PowerPoint when calling the Document.getSelectedData method to get the current slide or selected range of slides. + * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides. For example, `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. + * + * Note: Only applies to data in PowerPoint when calling the {@link Office.Document.getSelectedData | Document.getSelectedData} method to get the current slide or selected range of slides. */ SlideRange, /** * Data is returned or set as an image stream. - * @remarks - * Only applies to data in Excel, Word and PowerPoint. + * Note: Only applies to data in Excel, Word and PowerPoint. */ Image } @@ -1242,9 +1347,23 @@ declare namespace Office { * Specifies whether the document in the associated application is read-only or read-write. * * @remarks - *
HostsExcel, PowerPoint, Project, Word
+ * + * Returned by the mode property of the {@link Office.Document | Document} object. * - * Returned by the mode property of the Document object. + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y
*/ enum DocumentMode { /** @@ -1260,9 +1379,19 @@ declare namespace Office { * Specifies the type of the XML node. * * @remarks - * + *
HostsWord
Requirement SetsCustomXmlParts
* - * Requirement SetsCustomXmlParts + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y Y
*/ enum CustomXMLNodeType { /** @@ -1296,13 +1425,28 @@ declare namespace Office { } /** * Specifies the kind of event that was raised. Returned by the `type` property of an *EventArgs object. - * - * @remarks - * - *
HostsAccess, Excel, PowerPoint, Project, Word
Hosts (BindingDataChanged and BindingSelectionChanged)Access, Excel, Word
- * * * Add-ins for Project support the `Office.EventType.ResourceSelectionChanged`, `Office.EventType.TaskSelectionChanged`, and `Office.EventType.ViewSelectionChanged` event types. + * + * BindingDataChanged and BindingSelectionChanged hosts
Access, Excel, Word
+ * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Outlook Y Y Y
PowerPoint Y Y
Project Y
Word Y Y
*/ enum EventType { /** @@ -1330,27 +1474,33 @@ declare namespace Office { */ DialogEventReceived, /** - * Triggers when a document level selection happens + * Triggers when a document level selection happens. */ DocumentSelectionChanged, /** - * A Document.SelectionChanged event was raised. + * Triggers when the selected Outlook item was changed. + * + * [Api set: Mailbox 1.1] */ ItemChanged, /** - * Triggers when a customXmlPart node was deleted + * Triggers when a customXmlPart node was deleted. */ NodeDeleted, /** - * Triggers when a customXmlPart node was inserted + * Triggers when a customXmlPart node was inserted. */ NodeInserted, /** - * Triggers when a customXmlPart node was replaced + * Triggers when a customXmlPart node was replaced. */ NodeReplaced, /** - * The recurrence pattern of the selected series has changed. + * Triggers when the recurrence pattern of the selected series was changed in Outlook. + * + * [Api set: Mailbox Preview] + * + * @beta */ RecurrencePatternChanged, /** @@ -1374,7 +1524,21 @@ declare namespace Office { * Specifies the format in which to return the document. * * @remarks - *
HostsPowerPoint, Word
+ * FileType.Text is only supported in Word, FileType.Pdf is only supported in Word for Windows, Word for Mac, Word Online, and PowerPoint. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
*/ enum FileType { /** @@ -1382,7 +1546,7 @@ declare namespace Office { */ Text, /** - * Returns the entire document (.pptx, .docx, or .xslx) in Office Open XML (OOXML) format as a byte array. + * Returns the entire document (.pptx, .docx, or .xlsx) in Office Open XML (OOXML) format as a byte array. */ Compressed, /** @@ -1394,7 +1558,20 @@ declare namespace Office { * Specifies whether filtering from the host application is applied when the data is retrieved. * * @remarks - *
HostsExcel, Project, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum FilterType { /** @@ -1410,32 +1587,101 @@ declare namespace Office { * Specifies the type of place or object to navigate to. * * @remarks - *
HostsExcel, PowerPoint, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y
*/ enum GoToType { /** * Goes to a binding object using the specified binding id. + * + * Supported hosts: Excel, Word */ Binding, /** * Goes to a named item using that item's name. * In Excel, you can use any structured reference for a named range or table: "Worksheet2!Table1" + * + * Supported hosts: Excel */ NamedItem, /** * Goes to a slide using the specified id. + * + * Supported hosts: PowerPoint */ Slide, /** - * Goes to the specified index by slide number or Office.Index + * Goes to the specified index by slide number or {@link Office.Index}. + * + * Supported hosts: PowerPoint */ Index } /** - * Specifies whether to select (highlight) the location to navigate to (when using the Document.goToByIdAsync method). + * Specifies the relative PowerPoint slide + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad /th>
PowerPoint Y Y Y
+ */ + enum Index { + /** + * Represents the first PowerPoint slide + */ + First, + /** + * Represents the last PowerPoint slide + */ + Last, + /** + * Represents the next PowerPoint slide + */ + Next, + /** + * Represents the previous PowerPoint slide + */ + Previous + } + /** + * Specifies whether to select (highlight) the location to navigate to (when using the {@link Office.Document.goToByIdAsync | Document.goToByIdAsync} method). * * @remarks - *
HostsExcel, PowerPoint, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad /th>
Excel Y Y Y
PowerPoint Y
Word Y Y
*/ enum SelectionMode { Default, @@ -1444,7 +1690,7 @@ declare namespace Office { */ Selected, /** - * The cursor is moved the beginning of the location. + * The cursor is moved to the beginning of the location. */ None } @@ -1452,10 +1698,22 @@ declare namespace Office { * Specifies whether values, such as numbers and dates, returned by the invoked method are returned with their formatting applied. * * @remarks - *
HostsExcel, Project, Word
- * * For example, if the valueFormat parameter is specified as "formatted", a number formatted as currency, or a date formatted as mm/dd/yy in the host application will have its formatting preserved. * If the valueFormat parameter is specified as "unformatted", a date will be returned in its underlying sequential serial number form. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum ValueFormat { /** @@ -3416,10 +3674,21 @@ declare namespace Office { rows: any[][]; } /** - * Specifies enumerated values for the cells: property in the cellFormat parameter of {@link https://docs.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | table formatting methods}. + * Specifies enumerated values for the `cells` property in the cellFormat parameter of {@link https://docs.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | table formatting methods}. * * @remarks - *
HostsExcel
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
*/ enum Table { /** @@ -3447,12 +3716,23 @@ declare namespace Office { */ interface TextBinding extends Binding { } /** - * Specifies the project fields that are available as a parameter for the getProjectFieldAsync method. + * Specifies the project fields that are available as a parameter for the {@link Office.Document.getProjectFieldAsync | getProjectFieldAsync} method. * * @remarks - *
HostsProject
* - * A ProjectProjectFields constant can be used as a parameter of the getProjectFieldAsync method. + * A ProjectProjectFields constant can be used as a parameter of the {@link Office.Document.getProjectFieldAsync | getProjectFieldAsync} method. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectProjectFields { /** @@ -3506,12 +3786,24 @@ declare namespace Office { WSSList } /** - * Specifies the resource fields that are available as a parameter for the getResourceFieldAsync method. + * Specifies the resource fields that are available as a parameter for the {@link Office.Document.getResourceFieldAsync | getResourceFieldAsync} method. * * @remarks - * A ProjectResourceFields constant can be used as a parameter of the getResourceFieldAsync method. + * A ProjectResourceFields constant can be used as a parameter of the {@link Office.Document.getResourceFieldAsync | getResourceFieldAsync} method. * * For more information about working with fields in Project, see {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectResourceFields { /** @@ -4316,14 +4608,24 @@ declare namespace Office { Text9 } /** - * Specifies the task fields that are available as a parameter for the getTaskFieldAsync method. + * Specifies the task fields that are available as a parameter for the {@link Office.Document.getTaskFieldAsync | getTaskFieldAsync} method. * * @remarks - * A ProjectTaskFields constant can be used as a parameter of the getTaskFieldAsync method. + * A ProjectTaskFields constant can be used as a parameter of the {@link Office.Document.getTaskFieldAsync | getTaskFieldAsync} method. * * For more information about working with fields in Project, see the {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. - * - *
HostsProject
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectTaskFields { /** @@ -5454,12 +5756,22 @@ declare namespace Office { WSSID } /** - * Specifies the types of views that the getSelectedViewAsync method can recognize. + * Specifies the types of views that the {@link Office.Document.getSelectedViewAsync | getSelectedViewAsync} method can recognize. * * @remarks - *
HostsProject
+ * The {@link Office.Document.getSelectedViewAsync | getSelectedViewAsync} method returns the ProjectViewTypes constant value and name that corresponds to the active view. * - * The getSelectedViewAsync method returns the ProjectViewTypes constant value and name that corresponds to the active view. + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectViewTypes { /** @@ -8708,7 +9020,7 @@ declare namespace Office { */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -8722,7 +9034,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -8731,7 +9043,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks * @@ -9989,7 +10301,7 @@ declare namespace Office { */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -10003,7 +10315,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -10012,7 +10324,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}Restricted
@@ -11523,7 +11835,7 @@ declare namespace Office { */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -11537,7 +11849,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -11546,7 +11858,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks * @@ -18430,7 +18742,7 @@ declare namespace Excel { * @param sourceData The Range object corresponding to the source data. * @param seriesBy Optional. Specifies the way columns or rows are used as data series on the chart. See Excel.ChartSeriesBy for details. */ - add(type: Excel.ChartType, sourceData: Range | string, seriesBy?: Excel.ChartSeriesBy): Excel.Chart; + add(type: Excel.ChartType, sourceData: Range, seriesBy?: Excel.ChartSeriesBy): Excel.Chart; /** * * Creates a new chart. @@ -18441,7 +18753,7 @@ declare namespace Excel { * @param sourceData The Range object corresponding to the source data. * @param seriesBy Optional. Specifies the way columns or rows are used as data series on the chart. See Excel.ChartSeriesBy for details. */ - add(type: "Invalid" | "ColumnClustered" | "ColumnStacked" | "ColumnStacked100" | "3DColumnClustered" | "3DColumnStacked" | "3DColumnStacked100" | "BarClustered" | "BarStacked" | "BarStacked100" | "3DBarClustered" | "3DBarStacked" | "3DBarStacked100" | "LineStacked" | "LineStacked100" | "LineMarkers" | "LineMarkersStacked" | "LineMarkersStacked100" | "PieOfPie" | "PieExploded" | "3DPieExploded" | "BarOfPie" | "XYScatterSmooth" | "XYScatterSmoothNoMarkers" | "XYScatterLines" | "XYScatterLinesNoMarkers" | "AreaStacked" | "AreaStacked100" | "3DAreaStacked" | "3DAreaStacked100" | "DoughnutExploded" | "RadarMarkers" | "RadarFilled" | "Surface" | "SurfaceWireframe" | "SurfaceTopView" | "SurfaceTopViewWireframe" | "Bubble" | "Bubble3DEffect" | "StockHLC" | "StockOHLC" | "StockVHLC" | "StockVOHLC" | "CylinderColClustered" | "CylinderColStacked" | "CylinderColStacked100" | "CylinderBarClustered" | "CylinderBarStacked" | "CylinderBarStacked100" | "CylinderCol" | "ConeColClustered" | "ConeColStacked" | "ConeColStacked100" | "ConeBarClustered" | "ConeBarStacked" | "ConeBarStacked100" | "ConeCol" | "PyramidColClustered" | "PyramidColStacked" | "PyramidColStacked100" | "PyramidBarClustered" | "PyramidBarStacked" | "PyramidBarStacked100" | "PyramidCol" | "3DColumn" | "Line" | "3DLine" | "3DPie" | "Pie" | "XYScatter" | "3DArea" | "Area" | "Doughnut" | "Radar" | "Histogram" | "Pareto" | "RegionMap", sourceData: Range | string, seriesBy?: "Auto" | "Columns" | "Rows"): Excel.Chart; + add(type: "Invalid" | "ColumnClustered" | "ColumnStacked" | "ColumnStacked100" | "3DColumnClustered" | "3DColumnStacked" | "3DColumnStacked100" | "BarClustered" | "BarStacked" | "BarStacked100" | "3DBarClustered" | "3DBarStacked" | "3DBarStacked100" | "LineStacked" | "LineStacked100" | "LineMarkers" | "LineMarkersStacked" | "LineMarkersStacked100" | "PieOfPie" | "PieExploded" | "3DPieExploded" | "BarOfPie" | "XYScatterSmooth" | "XYScatterSmoothNoMarkers" | "XYScatterLines" | "XYScatterLinesNoMarkers" | "AreaStacked" | "AreaStacked100" | "3DAreaStacked" | "3DAreaStacked100" | "DoughnutExploded" | "RadarMarkers" | "RadarFilled" | "Surface" | "SurfaceWireframe" | "SurfaceTopView" | "SurfaceTopViewWireframe" | "Bubble" | "Bubble3DEffect" | "StockHLC" | "StockOHLC" | "StockVHLC" | "StockVOHLC" | "CylinderColClustered" | "CylinderColStacked" | "CylinderColStacked100" | "CylinderBarClustered" | "CylinderBarStacked" | "CylinderBarStacked100" | "CylinderCol" | "ConeColClustered" | "ConeColStacked" | "ConeColStacked100" | "ConeBarClustered" | "ConeBarStacked" | "ConeBarStacked100" | "ConeCol" | "PyramidColClustered" | "PyramidColStacked" | "PyramidColStacked100" | "PyramidBarClustered" | "PyramidBarStacked" | "PyramidBarStacked100" | "PyramidCol" | "3DColumn" | "Line" | "3DLine" | "3DPie" | "Pie" | "XYScatter" | "3DArea" | "Area" | "Doughnut" | "Radar" | "Histogram" | "Pareto" | "RegionMap", sourceData: Range, seriesBy?: "Auto" | "Columns" | "Rows"): Excel.Chart; /** * * Returns the number of charts in the worksheet. @@ -18663,7 +18975,7 @@ declare namespace Excel { * @param sourceData The range corresponding to the source data. * @param seriesBy Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, and Columns. See Excel.ChartSeriesBy for details. */ - setData(sourceData: Range | string, seriesBy?: Excel.ChartSeriesBy): void; + setData(sourceData: Range, seriesBy?: Excel.ChartSeriesBy): void; /** * * Resets the source data for the chart. @@ -18673,7 +18985,7 @@ declare namespace Excel { * @param sourceData The range corresponding to the source data. * @param seriesBy Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, and Columns. See Excel.ChartSeriesBy for details. */ - setData(sourceData: Range | string, seriesBy?: "Auto" | "Columns" | "Rows"): void; + setData(sourceData: Range, seriesBy?: "Auto" | "Columns" | "Rows"): void; /** * * Positions the chart relative to cells on the worksheet. diff --git a/types/phonegap-nfc/index.d.ts b/types/phonegap-nfc/index.d.ts index ff980eea33..abc460947d 100644 --- a/types/phonegap-nfc/index.d.ts +++ b/types/phonegap-nfc/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/chariotsolutions/phonegap-nfc // Definitions by: Michael Desigaud // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 interface Document { addEventListener(type: 'deviceready', listener: (ev: Event) => any, useCapture?: boolean): void; diff --git a/types/phonegap-nfc/phonegap-nfc-tests.ts b/types/phonegap-nfc/phonegap-nfc-tests.ts index b61009a7da..1e5a16010f 100644 --- a/types/phonegap-nfc/phonegap-nfc-tests.ts +++ b/types/phonegap-nfc/phonegap-nfc-tests.ts @@ -97,30 +97,5 @@ let eventTarget: EventTarget = { removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean) { return; } } -let ndefTagEvent = { - bubbles: false, - cancelBubble: false, - cancelable: false, - currentTarget: eventTarget, - defaultPrevented: false, - eventPhase: 2, - isTrusted: true, - returnValue: true, - srcElement: new Element(), - target: eventTarget, - timeStamp: 1394448136236, - type: "ndef", - initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean) { return; }, - preventDefault() { return; }, - stopImmediatePropagation() { return; }, - stopPropagation() { return; }, - AT_TARGET: 0, - BUBBLING_PHASE: 0, - CAPTURING_PHASE: 0, - NONE: 0, - scoped: false, - deepPath(): any { }, - tag: ndefTag -}; - -let event: NdefTagEvent = ndefTagEvent; \ No newline at end of file +let ndefTagEvent = { ...(undefined as Event), tag: ndefTag }; +let event: NdefTagEvent = ndefTagEvent; diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index 0f98e0a622..27d0f51fc6 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -19,7 +19,7 @@ export = P; * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform): P.Logger; +declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; /** * @param [options]: an options object @@ -27,7 +27,7 @@ declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream. * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform): P.Logger; +declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; declare namespace P { /** diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index 6d226a1d92..6959a6cd97 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -93,3 +93,6 @@ log.level = 'info'; pino.levels.values.error === 50; pino.levels.labels[50] === 'error'; + +const logstderr: pino.Logger = pino(process.stderr); +logstderr.error('on stderr instead of stdout'); diff --git a/types/playcanvas/engine/framework/components/animation/component.d.ts b/types/playcanvas/engine/framework/components/animation/component.d.ts index ca0547b6fe..7be1b5ea3b 100644 --- a/types/playcanvas/engine/framework/components/animation/component.d.ts +++ b/types/playcanvas/engine/framework/components/animation/component.d.ts @@ -46,6 +46,6 @@ declare namespace pc { * @param {String} name The name of the animation asset * @returns {pc.Animation} An Animation */ - getAnimation(name: string): void; + getAnimation(name: string): pc.Animation; } } diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 4859b86fc1..a5e85f802e 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for puppeteer 1.5 +// Type definitions for puppeteer 1.6 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch @@ -727,6 +727,10 @@ export interface ElementHandle extends JSHandle, Ev * If the element is detached from DOM, the method throws an error. */ hover(): Promise; + /** + * Resolves to true if the element is visible in the current viewport. + */ + isIntersectingViewport(): Promise; /** * Focuses the element, and then uses keyboard.down and keyboard.up. * @param key Name of key to press, such as ArrowLeft. See USKeyboardLayout for a list of all key names. @@ -860,6 +864,8 @@ export type ErrorCode = | "aborted" | "accessdenied" | "addressunreachable" + | "blockedbyclient" + | "blockedbyresponse" | "connectionaborted" | "connectionclosed" | "connectionfailed" @@ -1107,16 +1113,6 @@ export interface FrameBase extends Evalable { ...args: any[] ): Promise; - waitForRequest( - urlOrPredicate: string | ((req: Request) => boolean), - options?: { timeout?: number } - ): Promise; - - waitForResponse( - urlOrPredicate: string | ((res: Response) => boolean), - options?: { timeout?: number } - ): Promise; - waitForSelector( selector: string, options?: { visible?: boolean; hidden?: boolean; timeout?: number } @@ -1447,6 +1443,16 @@ export interface Page extends EventEmitter, FrameBase { */ waitForNavigation(options?: NavigationOptions): Promise; + waitForRequest( + urlOrPredicate: string | ((req: Request) => boolean), + options?: { timeout?: number } + ): Promise; + + waitForResponse( + urlOrPredicate: string | ((res: Response) => boolean), + options?: { timeout?: number } + ): Promise; + /** This method returns all of the dedicated WebWorkers associated with the page. */ workers(): Worker[]; } @@ -1705,6 +1711,8 @@ export interface Coverage { export interface StartCoverageOptions { /** Whether to reset coverage on every navigation. Defaults to `true`. */ resetOnNavigation?: boolean; + /** Whether anonymous scripts generated by the page should be reported. Defaults to `false`. */ + reportAnonymousScripts?: boolean; } export interface CoverageEntry { diff --git a/types/qhistory/index.d.ts b/types/qhistory/index.d.ts index 301f6b4391..84bd4e6d83 100644 --- a/types/qhistory/index.d.ts +++ b/types/qhistory/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/pshrmn/qhistory#readme // Definitions by: Diogo Franco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 export as namespace qhistory; diff --git a/types/qunit/index.d.ts b/types/qunit/index.d.ts index 2b7eb586ff..c5e677d187 100644 --- a/types/qunit/index.d.ts +++ b/types/qunit/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for QUnit v2.5.0 // Project: http://qunitjs.com/ // Definitions by: James Bracy +// Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Assert { @@ -234,6 +235,32 @@ interface Assert { */ throws(block: () => void, expected?: any, message?: any): void; raises(block: () => void, expected?: any, message?: any): void; + + /** + * A marker for progress in a given test. + * + * The `step()` assertion registers a passing assertion with a provided message. This makes + * it easy to check that specific portions of code are being executed, especially in + * asynchronous test cases and when used with `verifySteps()`. + * + * Together with the `verifySteps()` method, `step()` assertions give you an easy way + * to verify both the count and order of code execution. + * + * @param message Message to display for the step + */ + step(message: string): void; + + /** + * A helper assertion to verify the order and number of steps in a test. + * + * The assert.verifySteps() assertion compares a given array of string values (representing steps) + * with the order and values of previous step() calls. This assertion is helpful for verifying + * the order and count of portions of code paths, especially asynchronous ones. + * + * @param steps Array of strings representing steps to verify + * @param message A short description of the assertion + */ + verifySteps(steps: string[], message?: string): void; } @@ -313,6 +340,38 @@ interface NestedHooks { } +declare namespace QUnit { + interface BeginDetails { totalTests: number } + interface DoneDetails { failed: number, passed: number, total: number, runtime: number } + interface LogDetails { + result: boolean, + actual: any; + expected: any; + message: string; + source: string; + module: string; + name: string; + runtime: number; + } + interface ModuleDoneDetails { + name: string; + failed: number; + passed: number; + total: number; + runtime: number; + } + interface ModuleStartDetails { name: string } + interface TestDoneDetails { + name: string; + module: string; + failed: number; + passed: number; + total: number; + runtime: number; + } + interface TestStartDetails { name: string; module: string; } +} + interface QUnit { /** @@ -333,7 +392,7 @@ interface QUnit { * * @callback callback Callback to execute. */ - begin(callback: (details: { totalTests: number }) => void): void; + begin(callback: (details: QUnit.BeginDetails) => void): void; /** * Configuration for QUnit @@ -348,7 +407,7 @@ interface QUnit { * * @param callback Callback to execute */ - done(callback: (details: { failed: number, passed: number, total: number, runtime: number }) => void): void; + done(callback: (details: QUnit.DoneDetails) => void): void; /** * Advanced and extensible data dumping for JavaScript. @@ -392,16 +451,7 @@ interface QUnit { * * @param callback Callback to execute */ - log(callback: (details: { - result: boolean, - actual: any; - expected: any; - message: string; - source: string; - module: string; - name: string; - runtime: number; - }) => void): void; + log(callback: (details: QUnit.LogDetails) => void): void; /** * Group related tests under a single label. @@ -449,20 +499,14 @@ interface QUnit { * * @param callback Callback to execute */ - moduleDone(callback: (details: { - name: string; - failed: number; - passed: number; - total: number; - runtime: number; - }) => void): void; + moduleDone(callback: (details: QUnit.ModuleDoneDetails) => void): void; /** * Register a callback to fire whenever a module begins. * * @param callback Callback to execute */ - moduleStart(callback: (details: { name: string }) => void): void; + moduleStart(callback: (details: QUnit.ModuleStartDetails) => void): void; /** * Adds a test to exclusively run, preventing all other tests from running. @@ -578,7 +622,7 @@ interface QUnit { * * @param callback Callback to execute */ - testStart(callback: (details: { name: string; module: string;}) => void): void; + testStart(callback: (details: QUnit.TestStartDetails) => void): void; /** * Adds a test which expects at least one failing assertion during its run. diff --git a/types/qunit/qunit-tests.ts b/types/qunit/qunit-tests.ts index e726113604..ae519cd0bc 100644 --- a/types/qunit/qunit-tests.ts +++ b/types/qunit/qunit-tests.ts @@ -214,13 +214,33 @@ QUnit.log(function( details ) { console.log( output ); }); -QUnit.moduleDone(function( details ) { - console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total ); +QUnit.log(function( details: QUnit.LogDetails ) { + let x: { actual: number; expected: number; message: string; module: string; name: string; result: boolean; runtime: number; source: string } = details; + x = details; }); -QUnit.moduleStart(function( details ) { +QUnit.begin(function( details: QUnit.BeginDetails ) { + console.log( "Total tests running: ", details.totalTests); +}); + +QUnit.done(function( details: QUnit.DoneDetails ) { + console.log( "Finished. Failed/total: ", details.failed, details.total, details.passed, details.runtime ); +}); + +QUnit.moduleDone(function( details: QUnit.ModuleDoneDetails ) { + console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total, details.passed, details.runtime ); +}); + +QUnit.moduleStart(function( details: QUnit.ModuleStartDetails ) { console.log( "Now running: ", details.name ); }); +QUnit.testDone(function( details: QUnit.TestDoneDetails ) { + console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total, details.passed, details.runtime); +}); + +QUnit.testStart(function( details: QUnit.TestStartDetails ) { + console.log( "Now running: ", details.name, ' from module ', details.module ); +}); let Robot: any = () => {}; @@ -562,3 +582,11 @@ equivResult = QUnit.equiv({}, {}); equivResult = QUnit.equiv(1, 2); equivResult = QUnit.equiv('foo', 'bar'); equivResult = QUnit.equiv(['foo'], ['bar']); + + +QUnit.test('steps', assert => { + assert.step('one'); + assert.step('two'); + assert.step('three'); + assert.verifySteps(['one', 'two', 'three'], 'Counting to three correctly'); +}); diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index ad57afda3f..66d3707d2b 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -9,7 +9,6 @@ // Vítor Castro // Jordan Quagliatini // Simon Højberg -// Charles-Philippe Clermont // Samson Keung // Angelo Ocana // Rayner Pupo diff --git a/types/react-adal/index.d.ts b/types/react-adal/index.d.ts new file mode 100644 index 0000000000..9f3cd9bef2 --- /dev/null +++ b/types/react-adal/index.d.ts @@ -0,0 +1,411 @@ +// Type definitions for react-adal 0.4 +// Project: https://github.com/salvoravida/react-adal#readme +// Definitions by: Dmitry Korolev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; + +export type TokenCallback = ( + errorDesc: string | null, + token: string | null, + error: any +) => void; + +export type UserCallback = ( + errorDesc: string | null, + user: UserInfo | null +) => void; + +export interface AdalConfig { + /** + * Client ID assigned to your app by Azure Active Directory. + */ + clientId: string; + /** + * Endpoint at which you expect to receive tokens.Defaults to `window.location.href`. + */ + redirectUri?: string; + /** + * Azure Active Directory instance. Defaults to `https://login.microsoftonline.com/`. + */ + instance?: string; + /** + * Your target tenant. Defaults to `common`. + */ + tenant?: string; + /** + * Query parameters to add to the authentication request. + */ + extraQueryParameter?: string; + /** + * Unique identifier used to map the request with the response. Defaults to RFC4122 version 4 guid (128 bits). + */ + correlationId?: string; + /** + * User defined function of handling the navigation to Azure AD authorization endpoint in case of login. + */ + displayCall?: (url: string) => void; + /** + * Set this to true to enable login in a popup winodow instead of a full redirect. Defaults to `false`. + */ + popUp?: boolean; + /** + * Set this to the resource to request on login. Defaults to `clientId`. + */ + loginResource?: string; + /** + * Set this to redirect the user to a custom login page. + */ + localLoginUrl?: string; + /** + * Redirects to start page after login. Defaults to `true`. + */ + navigateToLoginRequestUrl?: boolean; + /** + * Set this to redirect the user to a custom logout page. + */ + logOutUri?: string; + /** + * Redirects the user to postLogoutRedirectUri after logout. Defaults to `redirectUri`. + */ + postLogoutRedirectUri?: string; + /** + * Sets browser storage to either 'localStorage' or sessionStorage'. Defaults to `sessionStorage`. + */ + cacheLocation?: "localStorage" | "sessionStorage"; + /** + * Array of keywords or URIs. Adal will attach a token to outgoing requests that have these keywords or URIs. + */ + endpoints?: { [resource: string]: string }; + /** + * Array of keywords or URIs. Adal will not attach a token to outgoing requests that have these keywords or URIs. + */ + anonymousEndpoints?: string[]; + /** + * If the cached token is about to be expired in the expireOffsetSeconds (in seconds), Adal will renew the token instead of using the cached token. Defaults to 300 seconds. + */ + expireOffsetSeconds?: number; + /** + * The number of milliseconds of inactivity before a token renewal response from AAD should be considered timed out. Defaults to 6 seconds. + */ + loadFrameTimeout?: number; + /** + * Callback to be invoked when a token is acquired. + */ + callback?: TokenCallback; +} + +export type LoggingLevel = 0 | 1 | 2 | 3; + +export interface RequestInfo { + /** + * Object comprising of fields such as id_token/error, session_state, state, e.t.c. + */ + parameters: any; + /** + * Request type. + */ + requestType: RequestType; + /** + * Whether state is valid. + */ + stateMatch: boolean; + /** + * Unique guid used to match the response with the request. + */ + stateResponse: string; + /** + * Whether `requestType` contains `id_token`, `access_token` or error. + */ + valid: boolean; +} + +export type RequestType = "LOGIN" | "RENEW_TOKEN" | "UNKNOWN"; + +export type ResponseType = "id_token token" | "token"; + +export interface UserInfo { + /** + * Username assigned from UPN or email. + */ + userName: string; + /** + * Properties parsed from `id_token`. + */ + profile: any; +} + +export interface Constants { + ACCESS_TOKEN: 'access_token'; + EXPIRES_IN: 'expires_in'; + ID_TOKEN: 'id_token'; + ERROR_DESCRIPTION: 'error_description'; + SESSION_STATE: 'session_state'; + STORAGE: { + TOKEN_KEYS: 'adal.token.keys'; + ACCESS_TOKEN_KEY: 'adal.access.token.key'; + EXPIRATION_KEY: 'adal.expiration.key'; + STATE_LOGIN: 'adal.state.login'; + STATE_RENEW: 'adal.state.renew'; + NONCE_IDTOKEN: 'adal.nonce.idtoken'; + SESSION_STATE: 'adal.session.state'; + USERNAME: 'adal.username'; + IDTOKEN: 'adal.idtoken'; + ERROR: 'adal.error'; + ERROR_DESCRIPTION: 'adal.error.description'; + LOGIN_REQUEST: 'adal.login.request'; + LOGIN_ERROR: 'adal.login.error'; + RENEW_STATUS: 'adal.token.renew.status'; + }; + RESOURCE_DELIMETER: '|'; + LOADFRAME_TIMEOUT: '6000'; + TOKEN_RENEW_STATUS_CANCELED: 'Canceled'; + TOKEN_RENEW_STATUS_COMPLETED: 'Completed'; + TOKEN_RENEW_STATUS_IN_PROGRESS: 'In Progress'; + LOGGING_LEVEL: { + ERROR: 0; + WARN: 1; + INFO: 2; + VERBOSE: 3; + }; + LEVEL_STRING_MAP: { + 0: 'ERROR:'; + 1: 'WARNING:'; + 2: 'INFO:'; + 3: 'VERBOSE:'; + }; + POPUP_WIDTH: 483; + POPUP_HEIGHT: 600; +} + +export class AuthenticationContext { + instance: string; + config: AdalConfig; + callback: TokenCallback; + popUp: boolean; + isAngular: boolean; + + /** + * Enum for request type + */ + REQUEST_TYPE: RequestType; + RESPONSE_TYPE: ResponseType; + CONSTANTS: Constants; + + constructor(options: AdalConfig); + /** + * Initiates the login process by redirecting the user to Azure AD authorization endpoint. + */ + login(): void; + /** + * Returns whether a login is in progress. + */ + loginInProgress(): boolean; + /** + * Gets token for the specified resource from the cache. + * @param resource A URI that identifies the resource for which the token is requested. + */ + getCachedToken(resource: string): string; + /** + * If user object exists, returns it. Else creates a new user object by decoding `id_token` from the cache. + */ + getCachedUser(): UserInfo; + /** + * Adds the passed callback to the array of callbacks for the specified resource. + * @param resource A URI that identifies the resource for which the token is requested. + * @param expectedState A unique identifier (guid). + * @param callback The callback provided by the caller. It will be called with token or error. + */ + registerCallback( + expectedState: string, + resource: string, + callback: TokenCallback + ): void; + /** + * Acquires token from the cache if it is not expired. Otherwise sends request to AAD to obtain a new token. + * @param resource Resource URI identifying the target resource. + * @param callback The callback provided by the caller. It will be called with token or error. + */ + acquireToken(resource: string, callback: TokenCallback): void; + /** + * Acquires token (interactive flow using a popup window) by sending request to AAD to obtain a new token. + * @param resource Resource URI identifying the target resource. + * @param extraQueryParameters Query parameters to add to the authentication request. + * @param claims Claims to add to the authentication request. + * @param callback The callback provided by the caller. It will be called with token or error. + */ + acquireTokenPopup( + resource: string, + extraQueryParameters: string | null | undefined, + claims: string | null | undefined, + callback: TokenCallback + ): void; + /** + * Acquires token (interactive flow using a redirect) by sending request to AAD to obtain a new token. In this case the callback passed in the authentication request constructor will be called. + * @param resource Resource URI identifying the target resource. + * @param extraQueryParameters Query parameters to add to the authentication request. + * @param claims Claims to add to the authentication request. + */ + acquireTokenRedirect( + resource: string, + extraQueryParameters?: string | null, + claims?: string | null + ): void; + /** + * Redirects the browser to Azure AD authorization endpoint. + * @param urlNavigate URL of the authorization endpoint. + */ + promptUser(urlNavigate: string): void; + /** + * Clears cache items. + */ + clearCache(): void; + /** + * Clears cache items for a given resource. + * @param resource Resource URI identifying the target resource. + */ + clearCacheForResource(resource: string): void; + /** + * Redirects user to logout endpoint. After logout, it will redirect to `postLogoutRedirectUri` if added as a property on the config object. + */ + logOut(): void; + /** + * Calls the passed in callback with the user object or error message related to the user. + * @param callback The callback provided by the caller. It will be called with user or error. + */ + getUser(callback: UserCallback): void; + /** + * Checks if the URL fragment contains access token, id token or error description. + * @param hash Hash passed from redirect page. + */ + isCallback(hash: string): boolean; + /** + * Gets login error. + */ + getLoginError(): string; + /** + * Creates a request info object from the URL fragment and returns it. + */ + getRequestInfo(hash: string): RequestInfo; + /** + * Saves token or error received in the response from AAD in the cache. In case of `id_token`, it also creates the user object. + */ + saveTokenFromHash(requestInfo: RequestInfo): void; + /** + * Gets resource for given endpoint if mapping is provided with config. + * @param endpoint Resource URI identifying the target resource. + */ + getResourceForEndpoint(resource: string): string; + /** + * This method must be called for processing the response received from AAD. It extracts the hash, processes the token or error, saves it in the cache and calls the callbacks with the result. + * @param hash Hash fragment of URL. Defaults to `window.location.hash`. + */ + handleWindowCallback(hash?: string): void; + + /** + * Checks the logging Level, constructs the log message and logs it. Users need to implement/override this method to turn on logging. + * @param level Level can be set 0, 1, 2 and 3 which turns on 'error', 'warning', 'info' or 'verbose' level logging respectively. + * @param message Message to log. + * @param error Error to log. + */ + log(level: LoggingLevel, message: string, error: any): void; + /** + * Logs messages when logging level is set to 0. + * @param message Message to log. + * @param error Error to log. + */ + error(message: string, error: any): void; + /** + * Logs messages when logging level is set to 1. + * @param message Message to log. + */ + warn(message: string): void; + /** + * Logs messages when logging level is set to 2. + * @param message Message to log. + */ + info(message: string): void; + /** + * Logs messages when logging level is set to 3. + * @param message Message to log. + */ + verbose(message: string): void; + + /** + * Logs Pii messages when Logging Level is set to 0 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + * @param error Error to log. + */ + errorPii(message: string, error: any): void; + + /** + * Logs Pii messages when Logging Level is set to 1 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + warnPii(message: string): void; + + /** + * Logs messages when Logging Level is set to 2 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + infoPii(message: string): void; + + /** + * Logs messages when Logging Level is set to 3 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + verbosePii(message: string): void; +} + +/** + * Return user token + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + */ +export function adalGetToken( + authContext: AuthenticationContext, + resourceUrl: string +): Promise; + +/** + * Allows to make requests with adal token + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + * @param fetch Fetch client + * @param url Request url + * @param options Fetch options + */ +export function adalFetch( + authContext: AuthenticationContext, + resource: string, + fetch: (input: string, init: any) => Promise, + url: string, + options: any +): Promise; + +/** + * Wrap for the app + * @param authContext Authentication context + * @param app Render app callback + * @param doNotLogin Don`t need to login? + */ +export function runWithAdal( + authContext: AuthenticationContext, + app: () => void, + doNotLogin: boolean +): void; + +/** + * Creates a HOC that can be used to manage authentication for the certain components + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + */ +export function withAdalLogin( + authContext: AuthenticationContext, + resource: string +): ( + wrappedComponent: React.ComponentClass | React.StatelessComponent, + renderLoading: () => JSX.Element | null, + renderError: (error: any) => JSX.Element | null +) => React.ComponentClass; diff --git a/types/react-adal/react-adal-tests.tsx b/types/react-adal/react-adal-tests.tsx new file mode 100644 index 0000000000..961246560f --- /dev/null +++ b/types/react-adal/react-adal-tests.tsx @@ -0,0 +1,75 @@ +import * as React from 'react'; +import { AuthenticationContext, adalFetch, adalGetToken, runWithAdal, withAdalLogin, AdalConfig } from 'react-adal'; + +const resourceUrl = 'https://graph.microsoft.net'; + +const adalConfig: AdalConfig = { + cacheLocation: "localStorage", + clientId: '9ha8cqc6-4668-459a-9272-f48c80a053y5', + endpoints: { + api: resourceUrl + }, + postLogoutRedirectUri: 'https://localhost:3000', + tenant: 'tenantname.onmicrosoft.com' + }; + +const authContext = new AuthenticationContext(adalConfig); + +const adalApiFetch = (fetch: any, url: string, options: any) => { + return adalFetch(authContext, resourceUrl, fetch, url, options); +}; + +const getToken = () => adalGetToken(authContext, resourceUrl); + +class App extends React.Component { + render() { + return null; + } +} + +// user must login to use the app +runWithAdal(authContext, () => { + // ReactDOM.render(, document.getElementById('react-app') as HTMLElement); +}, false); + +const withAdalLoginApi = withAdalLogin(authContext, resourceUrl); + +const Loading: React.SFC = (props) => { + return null; +}; + +const ErrorPage: React.SFC = (props) => { + return null; +}; + +class SignInPage extends React.Component { + render() { + return null; + } +} + +class ProtectedPage1 extends React.Component { + render() { + return null; + } +} + +const ProtectedPage2: React.SFC = (props) => { + return null; +}; + +const AdalProtectedPage1 = withAdalLoginApi(ProtectedPage1, () => , () => ); +const AdalProtectedPage2 = withAdalLoginApi(ProtectedPage2, () =>

loading...

, () =>

It seems something went wrong...

); + +// user must login to use only specific pages +runWithAdal(authContext, () => { + const routes =
+ // $ExpectError + // $ExpectError + // $ExpectError +
; + // $ExpectError + const App = ; + // $ExpectError + ReactDOM.render(, document.getElementById('react-app') as HTMLElement); +}, true); diff --git a/types/react-adal/tsconfig.json b/types/react-adal/tsconfig.json new file mode 100644 index 0000000000..b77e4dffc1 --- /dev/null +++ b/types/react-adal/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-adal-tests.tsx" + ] +} diff --git a/types/react-adal/tslint.json b/types/react-adal/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-adal/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index b73ffcc0d9..9275511fc9 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -86,11 +86,23 @@ export interface Format { eventTimeRangeEndFormat?: string; } +export interface HeaderProps { + culture: BigCalendarProps['culture']; + date: Date; + format: string; + label: string; + localizer: object; +} + export interface Components { event?: React.SFC | React.Component | React.ComponentClass | JSX.Element; eventWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dayWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dateCellWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + /** + * component used as a header for each column in the TimeGridHeader + */ + header?: React.ComponentType; toolbar?: React.SFC | React.Component | React.ComponentClass | JSX.Element; agenda?: { date?: React.SFC | React.Component | React.ComponentClass | JSX.Element; diff --git a/types/react-event-listener/index.d.ts b/types/react-event-listener/index.d.ts index 4b343c67e4..fcbabb9d68 100644 --- a/types/react-event-listener/index.d.ts +++ b/types/react-event-listener/index.d.ts @@ -125,8 +125,8 @@ export interface EventListenerProps { onMouseOverCapture?(ev: MouseEvent): any; onMouseUp?(ev: MouseEvent): any; onMouseUpCapture?(ev: MouseEvent): any; - onMouseWheel?(ev: MouseWheelEvent): any; - onMouseWheelCapture?(ev: MouseWheelEvent): any; + onMouseWheel?(ev: WheelEvent): any; + onMouseWheelCapture?(ev: WheelEvent): any; onMsGestureChange?(ev: MSGestureEvent): any; onMsGestureChangeCapture?(ev: MSGestureEvent): any; onMsGestureDoubleTap?(ev: MSGestureEvent): any; diff --git a/types/react-flag-icon-css/index.d.ts b/types/react-flag-icon-css/index.d.ts new file mode 100644 index 0000000000..ad1777670a --- /dev/null +++ b/types/react-flag-icon-css/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for react-flag-icon-css 1.0 +// Project: https://github.com/matteocng/react-flag-icon-css#readme +// Definitions by: Jon Freedman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as CSS from 'csstype'; +import { PureComponent, ReactNode } from 'react'; + +export type FlagIconSize = 'lg' | '2x' | '3x' | '4x' | '5x'; +export type FlagIconFlip = 'horizontal' | 'vertical'; +export type FlagIconRotate = 30 | 60 | 90 | 180 | 270; + +export interface FlagIconOptions { + /** + * Use CSS modules styles (your module bundler must be correctly setup). + */ + useCssModules?: boolean; + /** + * An object literal whose keys are your custom codes. + */ + customCodes?: { + [key: string]: string; + }; + /** + * Set this if useCssModules is true and a) you want to apply styles to FlagIcon + * using .theme-base and/or b) you are using custom flags. + */ + themeStyles?: { + [key: string]: CSS.Properties & CSS.PropertiesHyphen; + }; +} + +export interface FlagIconProps { + /** + * ISO 3166-1-alpha-2 code. + */ + code: string; + size?: FlagIconSize; + flip?: FlagIconFlip; + rotate?: FlagIconRotate; + Component?: string; + /** + * Uses the 1x1 image if true. + */ + squared?: boolean; + /** + * This is always appended as-is to class in the HTML. + */ + className?: string; + /** + * This is mapped to a CSS module and appended to class in the HTML. + */ + styleName?: string; + children?: ReactNode; +} + +export class FlagIcon extends PureComponent { +} + +export default function FlagIconFactory(react: any, opts?: Readonly): (props: FlagIconProps) => FlagIcon; + +export function CustomFlagIconFactory(react: any, opts?: Readonly): (props: FlagIconProps) => FlagIcon; diff --git a/types/react-flag-icon-css/package.json b/types/react-flag-icon-css/package.json new file mode 100644 index 0000000000..e6696d08e7 --- /dev/null +++ b/types/react-flag-icon-css/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "csstype": "^2.2.0" + } +} diff --git a/types/react-flag-icon-css/react-flag-icon-css-tests.tsx b/types/react-flag-icon-css/react-flag-icon-css-tests.tsx new file mode 100644 index 0000000000..5b656cff7b --- /dev/null +++ b/types/react-flag-icon-css/react-flag-icon-css-tests.tsx @@ -0,0 +1,88 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import FlagIconFactory, { CustomFlagIconFactory, FlagIconSize } from 'react-flag-icon-css'; + +const FlagIcon = FlagIconFactory(React, {useCssModules: false}); + +/** + * based on https://github.com/matteocng/react-flag-icon-css#basic-usage + */ +interface SimpleFlagComponentProps { + code: string; + size: FlagIconSize; +} + +export class SimpleFlagComponent extends React.PureComponent { + render() { + return ( + + ); + } +} + +const rootEL = document.getElementById('react-app') as HTMLElement; + +const appProps: SimpleFlagComponentProps = { + code: 'it', + size: '3x' +}; +ReactDOM.render(, rootEL); + +/** + * based on https://github.com/matteocng/react-flag-icon-css#exampleCustomFlagsIndex + */ +const styles = { + ['.flag-icon-ex1']: { + 'background-image': '../images/4x3/ex1.svg' + }, + ['.flag-icon-ex1.flag-icon-squared']: { + 'background-image': '../images/1x1/ex1.svg' + } +}; + +const codes = { + ex1: 'Example 1 country' +}; + +const optionsCssModules = {customCodes: codes, themeStyles: styles}; +const FlagIconCssModules = CustomFlagIconFactory(React, optionsCssModules); + +export class CustomFlagComponent extends React.PureComponent { + render() { + return ( + + ); + } +} + +const appCustomProps: SimpleFlagComponentProps = { + code: 'ex1', + size: 'lg' +}; +ReactDOM.render(, rootEL); + +/** + * based on 'props:children' test + */ +interface ChildrenFlagComponentProps { + code: string; + size: FlagIconSize; + children: React.ReactNode; +} + +export class ChildrenFlagComponent extends React.PureComponent { + render() { + return ( + + ); + } +} + +const appChildrenProps: ChildrenFlagComponentProps = { + code: 'ex1', + size: 'lg', + children: FlagIcon({ + code: 'it' + }) +}; +ReactDOM.render(, rootEL); diff --git a/types/react-flag-icon-css/tsconfig.json b/types/react-flag-icon-css/tsconfig.json new file mode 100644 index 0000000000..ac4affcceb --- /dev/null +++ b/types/react-flag-icon-css/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-flag-icon-css-tests.tsx" + ] +} diff --git a/types/react-flag-icon-css/tslint.json b/types/react-flag-icon-css/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/react-flag-icon-css/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-infinite-scroll-component/index.d.ts b/types/react-infinite-scroll-component/index.d.ts index 4e2ba078f5..2e23e4f6bc 100644 --- a/types/react-infinite-scroll-component/index.d.ts +++ b/types/react-infinite-scroll-component/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for react-infinite-scroll-component 4.1 +// Type definitions for react-infinite-scroll-component 4.2 // Project: https://github.com/ankeetmaini/react-infinite-scroll-component#readme // Definitions by: Stephanie Roy +// Bartosz Dotryw // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -61,9 +62,10 @@ declare namespace InfiniteScroll { releaseToRefreshContent?: boolean; /** - * A threshold value after that the InfiniteScroll will call next. By default it's 0.8. It means the next will be called when the user comes below 80% of the total height. + * A threshold value defining when InfiniteScroll will call next. Default value is 0.8. It means the next will be called when user comes below 80% of the total height. + * If you pass threshold in pixels (scrollThreshold="200px"), next will be called once you scroll at least (100% - scrollThreshold) pixels down. */ - scrollThreshold?: number; + scrollThreshold?: number | string; /** * A function that will listen to the scroll event on the scrolling container. Note that the scroll event is throttled, so you may not receive as many events as you would expect. diff --git a/types/react-measure/index.d.ts b/types/react-measure/index.d.ts index c61b22b187..241d482a53 100644 --- a/types/react-measure/index.d.ts +++ b/types/react-measure/index.d.ts @@ -46,7 +46,7 @@ export interface MeasuredComponentProps { type MeasuredComponent = React.ComponentType; -export interface MeasureProps { +export interface MeasureProps { client?: boolean; offset?: boolean; scroll?: boolean; @@ -60,5 +60,5 @@ export interface MeasureProps { export declare function withContentRect(types: ReadonlyArray | MeasurementType): (fn: MeasuredComponent) => React.ComponentType; -declare class Measure extends React.Component> {} +declare class Measure extends React.Component {} export default Measure; diff --git a/types/react-native-calendars/index.d.ts b/types/react-native-calendars/index.d.ts new file mode 100644 index 0000000000..6294af4682 --- /dev/null +++ b/types/react-native-calendars/index.d.ts @@ -0,0 +1,418 @@ +// Type definitions for react-native-calendars 1.20 +// Project: https://github.com/wix/react-native-calendars#readme +// Definitions by: Tyler Zhang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; +import { ViewProps, StyleProp } from 'react-native'; + +export interface DateObject { + year: number; + month: number; + day: number; + timestamp: number; + dateString: string; +} + +export interface CalendarTheme { + backgroundColor?: string; + calendarBackground?: string; + textSectionTitleColor?: string; + selectedDayBackgroundColor?: string; + selectedDayTextColor?: string; + todayTextColor?: string; + dayTextColor?: string; + textDisabledColor?: string; + dotColor?: string; + selectedDotColor?: string; + arrowColor?: string; + monthTextColor?: string; + textDayFontFamily?: string; + textMonthFontFamily?: string; + textDayHeaderFontFamily?: string; + textMonthFontWeight?: string; + textDayFontSize?: number; + textMonthFontSize?: number; + textDayHeaderFontSize?: number; +} + +export interface DayComponentProps { + state: '' | 'selected' | 'disabled' | 'today'; + theme: CalendarTheme; + onPress: () => any; + onLongPress: () => any; + date: DateObject; + marking: false | Marking[]; +} + +export interface CalendarBaseProps { + /** + * Styles for the view + */ + style?: StyleProp; + + /** + * Specify theme properties to override specific styles for calendar parts. Default = {} + */ + theme?: CalendarTheme; + + /** + * Initially visible month. Default = Date() + */ + current?: Date | string; + + /** + * Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + */ + minDate?: Date | string; + + /** + * Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + */ + maxDate?: Date | string; + + /** + * Handler which gets executed on day press. Default = undefined + */ + onDayPress?: (day: number) => void; + + /** + * Handler which gets executed on day long press. Default = undefined + */ + onDayLongPress?: (day: number) => void; + + /** + * Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + */ + monthFormat?: string; + + /** + * Handler which gets executed when visible month changes in calendar. Default = undefined + */ + onMonthChange?: (month: number) => void; + + /** + * Hide month navigation arrows. Default = false + */ + hideArrows?: boolean; + + /** + * Replace default arrows with custom ones (direction can be 'left' or 'right') + */ + renderArrow?: (direction: 'left' | 'right') => React.ReactNode; + + /** + * Do not show days of other months in month page. Default = false + */ + hideExtraDays?: boolean; + + /** + * If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + * day from another month that is visible in calendar page. Default = false + */ + disableMonthChange?: boolean; + + /** + * If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + */ + firstDay?: number; + + /** + * Hide day names. Default = false + */ + hideDayNames?: boolean; + + /** + * Show week numbers to the left. Default = false + */ + showWeekNumbers?: boolean; + + /** + * Handler which gets executed when press arrow icon left. It receive a callback can go back month + */ + onPressArrowLeft?: (month: number) => void; + + /** + * Handler which gets executed when press arrow icon left. It receive a callback can go next month + */ + onPressArrowRight?: (month: number) => void; + + /** + * Custom day renderer + */ + dayComponent?: React.Component | React.SFC; +} + +export interface DotForMultiDot { + key: string; + color: string; + selectedDotColor?: string; +} + +export interface MultiDotMarking { + dots: DotForMultiDot[]; + selected?: boolean; + selectedColor?: string; + disabled?: boolean; +} + +export interface DotMarking { + selected?: boolean; + marked?: boolean; + selectedColor?: string; + dotColor?: string; + activeOpacity?: number; + disabled?: boolean; + disableTouchEvent?: boolean; +} + +export interface PeriodMarking { + textColor?: string; + startingDay?: boolean; + color?: string; + selected?: boolean; + endingDay?: boolean; + disabled?: boolean; +} + +export interface MultiPeriodMarking { + periods: Array<{ + startingDay?: boolean; + endingDay?: boolean; + color?: string; + }>; +} + +export interface CustomMarking { + customStyles: any; +} + +export type Marking = + MultiDotMarking | + DotMarking | + PeriodMarking | + MultiPeriodMarking | + CustomMarking; + +export interface MultiDotMarkingProps { + markingType: 'multi-dot'; + markedDates: { + [date: string]: MultiDotMarking; + }; +} + +export interface DotMarkingProps { + markingType?: 'simple'; + markedDates: { + [date: string]: DotMarking; + }; +} + +export interface PeriodMarkingProps { + markingType: 'period'; + markedDates: { + [date: string]: PeriodMarking; + }; +} + +export interface CustomMarkingProps { + markingType: 'custom'; + markedDates: { + [date: string]: CustomMarking; + }; +} + +/** + * This type of marking is only fully supported by as it will expand the height + * of the component + */ +export interface MultiPeriodMarkingProps { + markingType: 'multi-period'; + markedDates: { + [date: string]: MultiPeriodMarking + }; +} + +export type CalendarMarkingProps = + MultiDotMarkingProps | + DotMarkingProps | + PeriodMarkingProps | + MultiPeriodMarkingProps | + CustomMarkingProps | + {}; + +export class Calendar extends React.Component {} + +export interface CalendarListBaseProps extends CalendarBaseProps { + /** + * Callback which gets executed when visible months change in scroll view. Default = undefined + */ + onVisibleMonthsChange?: (months: number) => void; + + /** + * Max amount of months allowed to scroll to the past. Default = 50 + */ + pastScrollRange?: number; + + /** + * Max amount of months allowed to scroll to the future. Default = 50 + */ + futureScrollRange?: number; + + /** + * Enable or disable scrolling of calendar list + */ + scrollEnabled?: boolean; + + /** + * Enable or disable vertical scroll indicator. Default = false + */ + showScrollIndicator?: boolean; + + /** + * Enable horizontal scrolling, default = false + */ + horizontal?: boolean; + + /** + * Enable paging on horizontal, default = false + */ + pagingEnabled?: boolean; + + /** + * Set custom calendarWidth. + */ + calendarWidth?: boolean; +} + +export class CalendarList extends React.Component {} + +export interface AgendaProps { + /** + * the list of items that have to be displayed in agenda. If you want to render item as empty date + * the value of date key kas to be an empty array []. If there exists no value for date key it is + * considered that the date in question is not yet loaded + */ + items: { + [key: string]: T[]; + }; + + /** + * callback that gets called when items for a certain month should be loaded (month became visible) + */ + loadItemsForMonth?: (date: DateObject) => void; + + /** + * callback that fires when the calendar is opened or closed + */ + onCalendarToggled?: (calendarOpened: boolean) => void; + + /** + * callback that gets called on day press + */ + onDayPress?: (day: number) => void; + + /** + * callback that gets called when day changes while scrolling agenda list + */ + onDayChange?: (day: number) => void; + + /** + * initially selected day + */ + selected?: Date | string; + + /** + * Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + */ + minDate?: Date | string; + + /** + * Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + */ + maxDate?: Date | string; + + /** + * Max amount of months allowed to scroll to the past. Default = 50 + */ + pastScrollRange?: number; + + /** + * Max amount of months allowed to scroll to the future. Default = 50 + */ + futureScrollRange?: number; + + /** + * specify how each item should be rendered in agenda + */ + renderItem: (item: T, firstItemInDay?: T) => React.ReactNode; + + /** + * specify how each date should be rendered. day can be undefined if the item is not first in that day. + */ + renderDay?: (day: DateObject | undefined, item: T) => React.ReactNode; + + /** + * specify how empty date content with no items should be rendered + */ + renderEmptyDate?: () => React.ReactNode; + + /** + * specify how agenda knob should look like + */ + renderKnob?: () => React.ReactNode; + + /** + * specify what should be rendered instead of ActivityIndicator + */ + renderEmptyData?: () => React.ReactNode; + + /** + * specify your item comparison function for increased performance + */ + rowHasChanged?: (r1: any, r2: any) => boolean; + + /** + * Hide knob button. Default = false + */ + hideKnob?: boolean; + + /** + * A RefreshControl component, used to provide pull-to-refresh funtionality for the ScrollView + */ + refreshControl?: React.ReactNode; + + /** + * If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. + * Make sure to also set the refreshing prop correctly. + */ + onRefresh?: () => any; + + /** + * Set this true while waiting for new data from a refresh + */ + refreshing?: boolean; + + /** + * Display loading indicator. Default = false + */ + displayLoadingIndicator?: boolean; + + /** + * agenda theme + */ + theme?: { + agendaDayTextColor?: string; + agendaDayNumColor?: string; + agendaTodayColor?: string; + agendaKnobColor?: string; + } & CalendarTheme; + + /** + * agenda container style + */ + style?: StyleProp; +} + +export class Agenda extends React.Component & CalendarMarkingProps> {} diff --git a/types/react-native-calendars/react-native-calendars-tests.tsx b/types/react-native-calendars/react-native-calendars-tests.tsx new file mode 100644 index 0000000000..5b438937e1 --- /dev/null +++ b/types/react-native-calendars/react-native-calendars-tests.tsx @@ -0,0 +1,374 @@ +import * as React from "react"; +import { Text, View } from "react-native"; +import { Calendar, CalendarList, Agenda } from "react-native-calendars"; + + { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} +/>; + + { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} + markedDates={{ + "2012-05-16": { selected: true, marked: true, selectedColor: "blue" }, + "2012-05-17": { marked: true }, + "2012-05-18": { marked: true, dotColor: "red", activeOpacity: 0 }, + "2012-05-19": { disabled: true, disableTouchEvent: true } + }} +/>; + +const vacation = { key: "vacation", color: "red", selectedDotColor: "blue" }; +const massage = { key: "massage", color: "blue", selectedDotColor: "blue" }; +const workout = { key: "workout", color: "green" }; + +; + +; + +; + +; + +; + + { + return ( + + + {date.day} + + + ); + }} +/>; + + { + console.log("now these months are visible", months); + }} + // Max amount of months allowed to scroll to the past. Default = 50 + pastScrollRange={50} + // Horizontal + horizontal={true} + // Max amount of months allowed to scroll to the future. Default = 50 + futureScrollRange={50} + // Enable or disable scrolling of calendar list + scrollEnabled={true} + // Enable or disable vertical scroll indicator. Default = false + showScrollIndicator={true} + // Initially visible month. Default = Date() + current={"2012-03-01"} + // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + minDate={"2012-05-10"} + // Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + maxDate={"2012-05-30"} + // Handler which gets executed on day press. Default = undefined + onDayPress={day => { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} +/>; + + { + console.log("trigger items loading"); + }} + // callback that fires when the calendar is opened or closed + onCalendarToggled={calendarOpened => { + console.log(calendarOpened); + }} + // callback that gets called on day press + onDayPress={day => { + console.log("day pressed"); + }} + // callback that gets called when day changes while scrolling agenda list + onDayChange={day => { + console.log("day changed"); + }} + // initially selected day + selected={"2012-05-16"} + // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + minDate={"2012-05-10"} + // Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + maxDate={"2012-05-30"} + // Max amount of months allowed to scroll to the past. Default = 50 + pastScrollRange={50} + // Max amount of months allowed to scroll to the future. Default = 50 + futureScrollRange={50} + // specify how each item should be rendered in agenda + renderItem={(item, firstItemInDay) => { + return ; + }} + // specify how each date should be rendered. day can be undefined if the item is not first in that day. + renderDay={(day, item) => { + return ; + }} + // specify how empty date content with no items should be rendered + renderEmptyDate={() => { + return ; + }} + // specify how agenda knob should look like + renderKnob={() => { + return ; + }} + // specify what should be rendered instead of ActivityIndicator + renderEmptyData={() => { + return ; + }} + // specify your item comparison function for increased performance + rowHasChanged={(r1, r2) => { + return r1.text !== r2.text; + }} + // Hide knob button. Default = false + hideKnob={true} + // By default, agenda dates are marked if they have at least one item, but you can override this if needed + markedDates={{ + "2012-05-16": { selected: true, marked: true }, + "2012-05-17": { marked: true }, + "2012-05-18": { disabled: true } + }} + // If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make sure to also set the refreshing prop correctly. + onRefresh={() => console.log("refreshing...")} + // Set this true while waiting for new data from a refresh + refreshing={false} + // Add a custom RefreshControl component, used to provide pull-to-refresh functionality for the ScrollView. + refreshControl={null} + // agenda theme + theme={{ + agendaDayTextColor: "yellow", + agendaDayNumColor: "green", + agendaTodayColor: "red", + agendaKnobColor: "blue" + }} + // agenda container style + style={{}} +/>; diff --git a/types/react-native-calendars/tsconfig.json b/types/react-native-calendars/tsconfig.json new file mode 100644 index 0000000000..e13f60597a --- /dev/null +++ b/types/react-native-calendars/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "react-native-calendars-tests.tsx" + ] +} diff --git a/types/react-native-calendars/tslint.json b/types/react-native-calendars/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-calendars/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-no-ssr/index.d.ts b/types/react-no-ssr/index.d.ts new file mode 100644 index 0000000000..77d52af1ff --- /dev/null +++ b/types/react-no-ssr/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for react-no-ssr 1.1 +// Project: https://github.com/kadirahq/react-no-ssr +// Definitions by: Rafał Filipek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; + +export default class NoSSR extends React.Component<{ + onSSR?: React.ReactChild; +}> {} diff --git a/types/react-no-ssr/react-no-ssr-tests.tsx b/types/react-no-ssr/react-no-ssr-tests.tsx new file mode 100644 index 0000000000..62ad9b1989 --- /dev/null +++ b/types/react-no-ssr/react-no-ssr-tests.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; +import NoSSR from 'react-no-ssr'; + +export class NoSSRTest extends React.Component { + render() { + return ( +
+ +
+ + }> +
+ +
+ ); + } +} diff --git a/types/react-no-ssr/tsconfig.json b/types/react-no-ssr/tsconfig.json new file mode 100644 index 0000000000..23e59891d8 --- /dev/null +++ b/types/react-no-ssr/tsconfig.json @@ -0,0 +1,18 @@ +{ + "files": ["index.d.ts", "react-no-ssr-tests.tsx"], + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "experimentalDecorators": true, + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/react-no-ssr/tslint.json b/types/react-no-ssr/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-no-ssr/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-portal/index.d.ts b/types/react-portal/index.d.ts index 7595c5e8ad..2994290013 100644 --- a/types/react-portal/index.d.ts +++ b/types/react-portal/index.d.ts @@ -1,25 +1,35 @@ -// Type definitions for react-portal 3.0 +// Type definitions for react-portal 4.0 // Project: https://github.com/tajo/react-portal#readme // Definitions by: Shun Takahashi +// Horus Lugo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 import * as React from "react"; -interface CallBackProps extends React.Props { - closePortal(): void; +export interface PortalProps extends React.Props { + children: React.ReactNode; + node?: Element | null; } -interface ReactPortalProps { - isOpened?: boolean; - openByClickOn?: React.ReactElement; +export const Portal: React.ComponentClass; + +export interface PortalFunctionParams { + openPortal: (event?: any) => void; + closePortal: () => void; + portal: (children: React.ReactNode) => React.ReactElement>; + isOpen: boolean; +} + +export interface PortalWithStateProps extends React.Props { + children: (params: PortalFunctionParams) => React.ReactNode; + node?: Element | null; + defaultOpen?: boolean; + openByClickOn?: React.ReactElement; closeOnEsc?: boolean; closeOnOutsideClick?: boolean; - onOpen?(node: HTMLDivElement): void; - beforeClose?(node: HTMLDivElement, resetPortalState: () => void): void; + onOpen?(): void; onClose?(): void; - onUpdate?(): void; } -declare const ReactPortal: React.ComponentClass; -export = ReactPortal; +export const PortalWithState: React.ComponentClass; diff --git a/types/react-portal/react-portal-tests.tsx b/types/react-portal/react-portal-tests.tsx index 5313b101bd..7ee7183e45 100644 --- a/types/react-portal/react-portal-tests.tsx +++ b/types/react-portal/react-portal-tests.tsx @@ -1,44 +1,79 @@ // Example from https://github.com/tajo/react-portal -import * as React from "react"; -import * as ReactDOM from "react-dom"; -import Portal = require("react-portal"); +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Portal, PortalWithState } from 'react-portal'; -export default class App extends React.Component { - render() { - const button1 = ; - - return ( -
- {}} - beforeClose={(node: HTMLDivElement, resetPortalState) => resetPortalState()} - onClose={() => {}} - onUpdate={() => {}} - > - -

Pseudo Modal

-

This react component is appended to the document body.

-
-
- -
- ); - } +interface AppState { + isPortalOneActive: boolean; + isPortalTwoActive: boolean; } -export class PseudoModal extends React.Component<{ closePortal?(): void }> { - render() { - return ( -
- {this.props.children} -

-
- ); - } +export default class App extends React.Component<{}, AppState> { + constructor(props: any) { + super(props); + + this.state = { + isPortalOneActive: false, + isPortalTwoActive: false + }; + } + + render() { + return ( +
+

React Portal Examples

+

+ + https://github.com/tajo/react-portal + +

+ +

Portal (stateless)

+ + {this.state.isPortalOneActive && ( + +

This thing was portaled!

+
+ )} + +

Portal (stateless, custom node)

+ + {this.state.isPortalTwoActive && ( + +

This thing was portaled!

+
+ )} + +

PortalWithState

+ + {({ openPortal, closePortal, isOpen, portal }) => [ + , + portal( +

+ This is more advanced Portal. It handles its own state.{' '} + , hit ESC or + click outside of me. +

+ ) + ]} +
+
+ ); + } } -ReactDOM.render(, document.getElementById('react-body')); +ReactDOM.render(, document.getElementById('root')); diff --git a/types/react-portal/v3/index.d.ts b/types/react-portal/v3/index.d.ts new file mode 100644 index 0000000000..7595c5e8ad --- /dev/null +++ b/types/react-portal/v3/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for react-portal 3.0 +// Project: https://github.com/tajo/react-portal#readme +// Definitions by: Shun Takahashi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from "react"; + +interface CallBackProps extends React.Props { + closePortal(): void; +} + +interface ReactPortalProps { + isOpened?: boolean; + openByClickOn?: React.ReactElement; + closeOnEsc?: boolean; + closeOnOutsideClick?: boolean; + onOpen?(node: HTMLDivElement): void; + beforeClose?(node: HTMLDivElement, resetPortalState: () => void): void; + onClose?(): void; + onUpdate?(): void; +} + +declare const ReactPortal: React.ComponentClass; +export = ReactPortal; diff --git a/types/react-portal/v3/react-portal-tests.tsx b/types/react-portal/v3/react-portal-tests.tsx new file mode 100644 index 0000000000..ca6c0289de --- /dev/null +++ b/types/react-portal/v3/react-portal-tests.tsx @@ -0,0 +1,44 @@ +// Example from https://github.com/tajo/react-portal +import * as React from "react"; +import * as ReactDOM from "react-dom"; +import * as Portal from "react-portal"; + +export default class App extends React.Component { + render() { + const button1 = ; + + return ( +
+ {}} + beforeClose={(node: HTMLDivElement, resetPortalState) => resetPortalState()} + onClose={() => {}} + onUpdate={() => {}} + > + +

Pseudo Modal

+

This react component is appended to the document body.

+
+
+ +
+ ); + } +} + +export class PseudoModal extends React.Component<{ closePortal?(): void }> { + render() { + return ( +
+ {this.props.children} +

+
+ ); + } +} + +ReactDOM.render(, document.getElementById('react-body')); diff --git a/types/react-portal/v3/tsconfig.json b/types/react-portal/v3/tsconfig.json new file mode 100644 index 0000000000..3b6f5c966a --- /dev/null +++ b/types/react-portal/v3/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "paths": { + "react-portal": [ "react-portal/v3" ] + } + }, + "files": [ + "index.d.ts", + "react-portal-tests.tsx" + ] +} diff --git a/types/react-portal/v3/tslint.json b/types/react-portal/v3/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-portal/v3/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-qr-reader/index.d.ts b/types/react-qr-reader/index.d.ts new file mode 100644 index 0000000000..d58da0e89f --- /dev/null +++ b/types/react-qr-reader/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for react-qr-reader 2.1 +// Project: https://github.com/JodusNodus/react-qr-reader +// Definitions by: David Kevork +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from "react"; + +export as namespace QrReader; + +export default QrReader; + +export namespace QrReader { + interface props { + onScan: (data: string | null) => void; + onError: (err: any) => void; + onLoad?: () => void; + onImageLoad?: (event: React.SyntheticEvent) => void; + delay?: number | false; + facingMode?: 'user' | 'environment'; + legacyMode?: boolean; + resolution?: number; + showViewFinder?: boolean; + style?: any; + className?: string; + } +} + +declare class QrReader extends React.Component { +} diff --git a/types/react-qr-reader/react-qr-reader-tests.tsx b/types/react-qr-reader/react-qr-reader-tests.tsx new file mode 100644 index 0000000000..20632f8029 --- /dev/null +++ b/types/react-qr-reader/react-qr-reader-tests.tsx @@ -0,0 +1,14 @@ +import * as React from "react"; +import QrReader from "react-qr-reader"; + +export class Test extends React.Component { + render() { + return ( + { console.log(err); }} + onScan={(data) => { console.log(data); }} + facingMode={'user'} + /> + ); + } +} diff --git a/types/react-qr-reader/tsconfig.json b/types/react-qr-reader/tsconfig.json new file mode 100644 index 0000000000..89aebb0de5 --- /dev/null +++ b/types/react-qr-reader/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-qr-reader-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-qr-reader/tslint.json b/types/react-qr-reader/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-qr-reader/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index 25b3ae2668..8aa723c232 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -73,9 +73,6 @@ type Shared< // Will not pass through the injected props if they are passed in during // render. Also adds new prop requirements from TNeedsProps. export interface InferableComponentEnhancerWithProps { - ( - component: StatelessComponent - ): ComponentClass & {WrappedComponent: StatelessComponent}

>( component: ComponentType

): ComponentClass> & TNeedsProps> & {WrappedComponent: ComponentType

} diff --git a/types/react-redux/react-redux-tests.tsx b/types/react-redux/react-redux-tests.tsx index f446df9a1e..5d2395d811 100644 --- a/types/react-redux/react-redux-tests.tsx +++ b/types/react-redux/react-redux-tests.tsx @@ -832,7 +832,12 @@ namespace TestDispatchToPropsAsObject {

} -namespace TestInferredFunctionalComponent { +namespace TestInferredFunctionalComponentWithExplicitOwnProps { + type Props = { + title: string, + extraText: string, + onClick: () => void, + }; const Header = connect( ( @@ -845,7 +850,30 @@ namespace TestInferredFunctionalComponent { (dispatch) => ({ onClick: () => dispatch({ type: 'test' }) }) - )(({ title, extraText, onClick }) => { + )(({ title, extraText, onClick }: Props) => { + return

{title} {extraText}

; + }); +
+} + +namespace TestInferredFunctionalComponentWithImplicitOwnProps { + + type Props = { + title: string, + extraText: string, + onClick: () => void, + }; + + const Header = connect( + ( + { app: { title }}: { app: { title: string }}, + ) => ({ + title, + }), + (dispatch) => ({ + onClick: () => dispatch({ type: 'test' }) + }) + )(({ title, extraText, onClick }: Props) => { return

{title} {extraText}

; });
@@ -1126,4 +1154,4 @@ namespace TestFailsMoreSpecificInjectedProps { // Since it is possible the injected props could fail to satisfy the decoration props, // the following line should fail to compile. connect(mapStateToProps, mapDispatchToProps)(Component) // $ExpectError -} \ No newline at end of file +} diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index 05d5fe30bb..6814ecf19f 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -64,9 +64,9 @@ export interface StaticContext { statusCode?: number; } -export interface RouteComponentProps { +export interface RouteComponentProps { history: H.History; - location: H.Location; + location: H.Location; match: match

; staticContext?: C; } diff --git a/types/react-select/index.d.ts b/types/react-select/index.d.ts index bde3c3c6a0..9c4728254c 100644 --- a/types/react-select/index.d.ts +++ b/types/react-select/index.d.ts @@ -1,646 +1,21 @@ -// Type definitions for react-select 1.3 -// Project: https://github.com/JedWatson/react-select -// Definitions by: ESQUIBET Hugo -// Gilad Gray -// Izaak Baker -// Tadas Dailyda -// Mark Vujevits -// Mike Deverell -// MartynasZilinskas -// Onat Yigit Mercan -// Ian Johnson -// Anton Novik -// David Schkalee -// Arthur Udalov -// Sebastian Silbermann -// Guillaume Chartier +// Type definitions for react-select 2.0 +// Project: https://github.com/JedWatson/react-select#readme +// Definitions by: Claas Ahlrichs +// Jon Freedman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.9 -import * as React from 'react'; +import SelectBase from './lib/Select'; +import { StateManager } from './lib/stateManager'; -export default class ReactSelectClass extends React.Component> { - focus(): void; - setValue(value: Option): void; -} -// Other components -export class Creatable extends React.Component> { } -export class Async extends React.Component> { } -export class AsyncCreatable extends React.Component> { } +export default SelectBase; +// export default StateManager; -export type OptionComponentType = React.ComponentType>; -export type ValueComponentType = React.ComponentType>; - -export type HandlerRendererResult = JSX.Element | null | false; - -// Handlers -export type FocusOptionHandler = (option: Option) => void; -export type SelectValueHandler = (option: Option) => void; -export type ArrowRendererHandler = (props: ArrowRendererProps) => HandlerRendererResult; -export type ClearRendererHandler = () => HandlerRendererResult; -export type FilterOptionHandler = (option: Option, filter: string) => boolean; -export type FilterOptionsHandler = (options: Options, filter: string, currentValues: Options) => Options; -export type InputRendererHandler = (props: { [key: string]: any }) => HandlerRendererResult; -export type MenuRendererHandler = (props: MenuRendererProps) => HandlerRendererResult; -export type OnCloseHandler = () => void; -export type OnInputChangeHandler = (inputValue: string) => string; -export type OnInputKeyDownHandler = React.KeyboardEventHandler; -export type OnMenuScrollToBottomHandler = () => void; -export type OnOpenHandler = () => void; -export type OnFocusHandler = React.FocusEventHandler; -export type OnBlurHandler = React.FocusEventHandler; -export type OptionRendererHandler = (option: Option) => HandlerRendererResult; -export type ValueRendererHandler = (option: Option, index?: number) => HandlerRendererResult; -export type OnValueClickHandler = (option: Option, event: React.MouseEvent) => void; -export type IsOptionUniqueHandler = (arg: { option: Option, options: Options, labelKey: string, valueKey: string }) => boolean; -export type IsValidNewOptionHandler = (arg: { label: string }) => boolean; -export type NewOptionCreatorHandler = (arg: { label: string, labelKey: string, valueKey: string }) => Option; -export type PromptTextCreatorHandler = (filterText: string) => string; -export type ShouldKeyDownEventCreateNewOptionHandler = (arg: { keyCode: number }) => boolean; - -export type OnChangeSingleHandler = OnChangeHandler>; -export type OnChangeMultipleHandler = OnChangeHandler>; -export type OnChangeHandler | Options> = (newValue: TOption | null) => void; -export type OnNewOptionClickHandler = (option: Option) => void; - -export type LoadOptionsHandler = LoadOptionsAsyncHandler | LoadOptionsLegacyHandler; -export type LoadOptionsAsyncHandler = (input: string) => Promise>; -export type LoadOptionsLegacyHandler = (input: string, callback: (err: any, result: AutocompleteResult) => void) => void; - -export interface AutocompleteResult { - /** The search-results to be displayed */ - options: Options; - /** - * Should be set to true, if and only if a longer query with the same prefix - * would return a subset of the results - * If set to true, more specific queries will not be sent to the server. - */ - complete: boolean; -} - -export type Options = Array>; - -export interface Option { - /** Text for rendering */ - label?: string; - /** Value for searching */ - value?: TValue; - /** - * Allow this option to be cleared - * @default true - */ - clearableValue?: boolean; - /** - * Do not allow this option to be selected - * @default false - */ - disabled?: boolean; - /** - * In the event that a custom menuRenderer is provided, Option should be able - * to accept arbitrary key-value pairs. See react-virtualized-select. - */ - [property: string]: any; -} - -export type OptionValues = string | number | boolean; - -export interface MenuRendererProps { - /** - * The currently focused option; should be visible in the menu by default. - * default {} - */ - focusedOption: Option; - - /** - * Callback to focus a new option; receives the option as a parameter. - */ - focusOption: FocusOptionHandler; - - /** - * Option labels are accessible with this string key. - */ - labelKey: string; - - /** - * Ordered array of options to render. - */ - options: Options; - - /** - * Callback to select a new option; receives the option as a parameter. - */ - selectValue: SelectValueHandler; - - /** - * Array of currently selected options. - */ - valueArray: Options; - - /** - * Callback to remove selection from option; receives the option as a parameter. - */ - removeValue: SelectValueHandler; - - /** - * function which returns a custom way to render the options in the menu - */ - optionRenderer: OptionRendererHandler; -} - -export interface OptionComponentProps { - /** - * Classname(s) to apply to the option component. - */ - className?: string; - - /** - * Currently focused option. - */ - focusOption?: Option; - - inputValue?: string; - instancePrefix?: string; - - /** - * True if this option is disabled. - */ - isDisabled?: boolean; - - /** - * True if this option is focused. - */ - isFocused?: boolean; - - /** - * True if this option is selected. - */ - isSelected?: boolean; - - /** - * Callback to be invoked when this option is focused. - */ - onFocus?: (option: Option, event: any) => void; - - /** - * Callback to be invoked when this option is selected. - */ - onSelect?: (option: Option, event: any) => void; - - /** - * Option to be rendered by this component. - */ - option: Option; - - /** - * Index of the option being rendered in the list - */ - optionIndex?: number; - - /** - * Callback to invoke when removing an option from a multi-selection. (Not necessarily the one - * being rendered) - */ - removeValue?: (value: TValue | TValue[]) => void; - - /** - * Callback to invoke to select an option. (Not necessarily the one being rendered) - */ - selectValue?: (value: TValue | TValue[]) => void; -} - -export interface ArrowRendererProps { - /** - * Arrow mouse down event handler. - */ - onMouseDown: React.MouseEventHandler; - - /** - * whether the Select is open or not. - */ - isOpen: boolean; -} - -export interface ValueComponentProps { - disabled: ReactSelectProps['disabled']; - id: string; - instancePrefix: string; - onClick: OnValueClickHandler | null; - onRemove?: SelectValueHandler; - placeholder: ReactSelectProps['placeholder']; - value: Option; - values?: Array>; -} - -export interface ReactSelectProps extends React.Props> { - /** - * text to display when `allowCreate` is true. - * @default 'Add "{label}"?' - */ - addLabelText?: string; - /** - * renders a custom drop-down arrow to be shown in the right-hand side of the select. - * @default undefined - */ - arrowRenderer?: ArrowRendererHandler; - /** - * blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices. - * @default false - */ - autoBlur?: boolean; - /** - * autofocus the component on mount - * @deprecated. Use autoFocus instead - * @default false - */ - autofocus?: boolean; - /** - * autofocus the component on mount - * @default false - */ - autoFocus?: boolean; - /** - * If enabled, the input will expand as the length of its value increases - */ - autosize?: boolean; - /** - * whether pressing backspace removes the last item when there is no input value - * @default true - */ - backspaceRemoves?: boolean; - /** - * Message to use for screenreaders to press backspace to remove the current item - * {label} is replaced with the item label - * @default "Press backspace to remove..." - */ - backspaceToRemoveMessage?: string; - /** - * CSS className for the outer element - */ - className?: string; - /** - * Prefix prepended to element default className if no className is defined - */ - classNamePrefix?: string; - /** - * title for the "clear" control when `multi` is true - * @default "Clear all" - */ - clearAllText?: string; - /** - * Renders a custom clear to be shown in the right-hand side of the select when clearable true - * @default undefined - */ - clearRenderer?: ClearRendererHandler; - /** - * title for the "clear" control - * @default "Clear value" - */ - clearValueText?: string; - /** - * whether to close the menu when a value is selected - * @default true - */ - closeOnSelect?: boolean; - /** - * whether it is possible to reset value. if enabled, an X button will appear at the right side. - * @default true - */ - clearable?: boolean; - /** - * whether backspace removes an item if there is no text input - * @default true - */ - deleteRemoves?: boolean; - /** - * delimiter to use to join multiple values - * @default "," - */ - delimiter?: string; - /** - * whether the Select is disabled or not - * @default false - */ - disabled?: boolean; - /** - * whether escape clears the value when the menu is closed - * @default true - */ - escapeClearsValue?: boolean; - /** - * method to filter a single option - */ - filterOption?: FilterOptionHandler; - /** - * method to filter the options array - */ - filterOptions?: FilterOptionsHandler; - /** - * id for the underlying HTML input element - * @default undefined - */ - id?: string; - /** - * whether to strip diacritics when filtering - * @default true - */ - ignoreAccents?: boolean; - /** - * whether to perform case-insensitive filtering - * @default true - */ - ignoreCase?: boolean; - /** - * custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'} - * @default {} - */ - inputProps?: { [key: string]: any }; - /** - * renders a custom input - */ - inputRenderer?: InputRendererHandler; - /** - * allows for synchronization of component id's on server and client. - * @see https://github.com/JedWatson/react-select/pull/1105 - */ - instanceId?: string; - /** - * whether the Select is loading externally or not (such as options being loaded). - * if true, a loading spinner will be shown at the right side. - * @default false - */ - isLoading?: boolean; - /** - * (legacy mode) joins multiple values into a single form field with the delimiter - * @default false - */ - joinValues?: boolean; - /** - * the option property to use for the label - * @default "label" - */ - labelKey?: string; - /** - * (any, start) match the start or entire string when filtering - * @default "any" - */ - matchPos?: string; - /** - * (any, label, value) which option property to filter on - * @default "any" - */ - matchProp?: string; - /** - * buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport - * @default 0 - */ - menuBuffer?: number; - /** - * optional style to apply to the menu container - */ - menuContainerStyle?: React.CSSProperties; - /** - * renders a custom menu with options - */ - menuRenderer?: MenuRendererHandler; - /** - * optional style to apply to the menu - */ - menuStyle?: React.CSSProperties; - /** - * multi-value input - * @default false - */ - multi?: boolean; - /** - * field name, for hidden `` tag - */ - name?: string; - /** - * placeholder displayed when there are no matching search results or a falsy value to hide it - * @default "No results found" - */ - noResultsText?: string | JSX.Element; - /** - * onBlur handler: function (event) {} - */ - onBlur?: OnBlurHandler; - /** - * whether to clear input on blur or not - * @default true - */ - onBlurResetsInput?: boolean; - /** - * whether the input value should be reset when options are selected. - * Also input value will be set to empty if 'onSelectResetsInput=true' and - * Select will get new value that not equal previous value. - * @default true - */ - onSelectResetsInput?: boolean; - /** - * whether to clear input when closing the menu through the arrow - * @default true - */ - onCloseResetsInput?: boolean; - /** - * onChange handler: function (newValue) {} - */ - onChange?: OnChangeHandler; - /** - * fires when the menu is closed - */ - onClose?: OnCloseHandler; - /** - * onFocus handler: function (event) {} - */ - onFocus?: OnFocusHandler; - /** - * onInputChange handler: function (inputValue) {} - */ - onInputChange?: OnInputChangeHandler; - /** - * onInputKeyDown handler: function (keyboardEvent) {} - */ - onInputKeyDown?: OnInputKeyDownHandler; - /** - * fires when the menu is scrolled to the bottom; can be used to paginate options - */ - onMenuScrollToBottom?: OnMenuScrollToBottomHandler; - /** - * fires when the menu is opened - */ - onOpen?: OnOpenHandler; - /** - * boolean to enable opening dropdown when focused - * @default false - */ - openOnClick?: boolean; - /** - * open the options menu when the input gets focus (requires searchable = true) - * @default true - */ - openOnFocus?: boolean; - /** - * className to add to each option component - */ - optionClassName?: string; - /** - * option component to render in dropdown - */ - optionComponent?: OptionComponentType; - /** - * function which returns a custom way to render the options in the menu - */ - optionRenderer?: OptionRendererHandler; - /** - * array of Select options - * @default false - */ - options?: Options; - /** - * number of options to jump when using page up/down keys - * @default 5 - */ - pageSize?: number; - /** - * field placeholder, displayed when there's no value - * @default "Select..." - */ - placeholder?: string | JSX.Element; - /** - * whether the selected option is removed from the dropdown on multi selects - * @default true - */ - removeSelected?: boolean; - /** - * applies HTML5 required attribute when needed - * @default false - */ - required?: boolean; - /** - * value to use when you clear the control - */ - resetValue?: any; - /** - * use react-select in right-to-left direction - * @default false - */ - rtl?: boolean; - /** - * whether the viewport will shift to display the entire menu when engaged - * @default true - */ - scrollMenuIntoView?: boolean; - /** - * whether to enable searching feature or not - * @default true; - */ - searchable?: boolean; - /** - * whether to select the currently focused value when the [tab] key is pressed - */ - tabSelectsValue?: boolean; - /** - * initial field value - */ - value?: Option | Options | string | string[] | number | number[] | boolean; - /** - * the option property to use for the value - * @default "value" - */ - valueKey?: string; - /** - * function which returns a custom way to render the value selected - * @default false - */ - valueRenderer?: ValueRendererHandler; - /** - * optional style to apply to the control - */ - style?: React.CSSProperties; - - /** - * optional tab index of the control - */ - tabIndex?: string | number; - - /** - * value component to render - */ - valueComponent?: ValueComponentType; - - /** - * optional style to apply to the component wrapper - */ - wrapperStyle?: React.CSSProperties; - - /** - * onClick handler for value labels: function (value, event) {} - */ - onValueClick?: OnValueClickHandler; - - /** - * pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false - */ - simpleValue?: boolean; -} - -export interface ReactCreatableSelectProps extends ReactSelectProps { - /** - * Searches for any matching option within the set of options. This function prevents - * duplicate options from being created. - */ - isOptionUnique?: IsOptionUniqueHandler; - - /** - * Determines if the current input text represents a valid option. - */ - isValidNewOption?: IsValidNewOptionHandler; - - /** - * factory to create new options - */ - newOptionCreator?: NewOptionCreatorHandler; - - /** - * Creates prompt/placeholder for option text. - */ - promptTextCreator?: PromptTextCreatorHandler; - - /** - * Decides if a keyDown event (eg its 'keyCode') should result in the creation of a new option. - */ - shouldKeyDownEventCreateNewOption?: ShouldKeyDownEventCreateNewOptionHandler; - - /** - * new option click handler: function (option) {} - */ - onNewOptionClick?: OnNewOptionClickHandler; -} - -export interface ReactAsyncSelectProps extends ReactSelectProps { - /** - * Whether to auto-load the default async options set. - */ - autoload?: boolean; - - /** - * object to use to cache results; can be null to disable cache - */ - cache?: { [key: string]: any } | boolean; - - /** - * function to call to load options asynchronously - */ - loadOptions: LoadOptionsHandler; - - /** - * replaces the placeholder while options are loading - */ - loadingPlaceholder?: string | JSX.Element; - /** - * displayed in the drop down list when the user did not type anything yet - */ - searchPromptText?: string; -} - -export type ReactAsyncCreatableSelectProps = ReactAsyncSelectProps & ReactCreatableSelectProps; +export { SelectBase }; +export { default as Async } from './lib/Async'; +export { default as AsyncCreatable } from './lib/AsyncCreatable'; +export { default as Creatable } from './lib/Creatable'; +export { createFilter } from './lib/filters'; +export { default as makeAnimated } from './lib/animated/index'; +export { components } from './lib/components/index'; +export { mergeStyles } from './lib/styles'; diff --git a/types/react-select/lib/Async.d.ts b/types/react-select/lib/Async.d.ts new file mode 100644 index 0000000000..8acc5532b7 --- /dev/null +++ b/types/react-select/lib/Async.d.ts @@ -0,0 +1,47 @@ +import * as React from 'react'; +import Select, { Props as SelectProps } from './Select'; +import { handleInputChange } from './utils'; +import manageState from './stateManager'; +import { OptionsType, InputActionMeta } from './types'; + +export interface AsyncProps { + /* The default set of options to show before the user starts searching. When + set to `true`, the results for loadOptions('') will be autoloaded. */ + defaultOptions: OptionsType | boolean; + /* Function that returns a promise, which is the set of options to be used + once the promise resolves. */ + loadOptions: (inputValue: string, callback: ((options: OptionsType) => void)) => Promise | void; + /* If cacheOptions is truthy, then the loaded data will be cached. The cache + will remain until `cacheOptions` changes value. */ + cacheOptions: any; +} + +export type Props = SelectProps & AsyncProps; + +export const defaultProps: Props; + +export interface State { + defaultOptions?: OptionsType; + inputValue: string; + isLoading: boolean; + loadedInputValue?: string; + loadedOptions: OptionsType; + passEmptyOptions: boolean; +} + +export class Async extends React.Component, State> { + static defaultProps: Props; + select: React.Ref; + lastRequest: {}; + mounted: boolean; + optionsCache: { [key: string]: OptionsType }; + + focus(): void; + blur(): void; + loadOptions(inputValue: string, callback: (options: OptionsType) => void): void; + handleInputChange: (newValue: string, actionMeta: InputActionMeta) => string; +} + +export function makeAsyncSelect(SelectComponent: React.ComponentType): Async; + +export default Async; diff --git a/types/react-select/lib/AsyncCreatable.d.ts b/types/react-select/lib/AsyncCreatable.d.ts new file mode 100644 index 0000000000..5fbdd8e52c --- /dev/null +++ b/types/react-select/lib/AsyncCreatable.d.ts @@ -0,0 +1,25 @@ +import { Component, Ref as ElementRef } from 'react'; +import { Props as AsyncProps, State as AsyncState } from './Async'; +import { Props as CreatableProps, State as CreatableState } from './Creatable'; +import { OptionsType, ValueType, ActionMeta, InputActionMeta } from './types'; +import { cleanValue } from './utils'; + +type Props = AsyncProps & CreatableProps; + +type State = AsyncState & CreatableState; + +export class AsyncCreatable extends Component, State> { + static defaultProps: Props; + select: ElementRef; + lastRequest: {}; + mounted: boolean; + optionsCache: { [key: string]: OptionsType }; + + focus(): void; + blur(): void; + loadOptions(inputValue: string, callback: (options: OptionsType) => void): void; + handleInputChange: (newValue: string, actionMeta: InputActionMeta) => string; + onChange: (newValue: ValueType, actionMeta: ActionMeta) => void; +} + +export default AsyncCreatable; diff --git a/types/react-select/lib/Creatable.d.ts b/types/react-select/lib/Creatable.d.ts new file mode 100644 index 0000000000..c194441a8b --- /dev/null +++ b/types/react-select/lib/Creatable.d.ts @@ -0,0 +1,49 @@ +import * as React from 'react'; +import Select, { Props as SelectProps } from './Select'; +import { OptionsType, ValueType, ActionMeta } from './types'; +import { cleanValue } from './utils'; +import manageState from './stateManager'; + +export interface CreatableProps { + /* Allow options to be created while the `isLoading` prop is true. Useful to + prevent the "create new ..." option being displayed while async results are + still being loaded. */ + allowCreateWhileLoading?: boolean; + /* Gets the label for the "create new ..." option in the menu. Is given the + current input value. */ + formatCreateLabel?: (inputValue: string) => Node; + /* Determines whether the "create new ..." option should be displayed based on + the current input value, select value and options array. */ + isValidNewOption?: (a: string, b: ValueType, c: OptionsType) => boolean; + /* Returns the data for the new option when it is created. Used to display the + value, and is passed to `onChange`. */ + getNewOptionData?: (a: string, b: Node) => OptionType; + /* If provided, this will be called with the input value when a new option is + created, and `onChange` will **not** be called. Use this when you need more + control over what happens when new options are created. */ + onCreateOption?: (inputValue: string) => void; + /* Sets the position of the createOption element in your options list. Defaults to 'last' */ + createOptionPosition?: 'first' | 'last'; +} + +export type Props = SelectProps & CreatableProps; + +export const defaultProps: Props; + +export interface State { + newOption: OptionType | undefined; + options: OptionsType; +} + +export class Creatable extends React.Component, State> { + static defaultProps: Props; + select: React.Ref; + + onChange: (newValue: ValueType, actionMeta: ActionMeta) => void; + focus(): void; + blur(): void; +} + +export function makeCreatableSelect(SelectComponent: React.ComponentType): Creatable; + +export default Creatable; diff --git a/types/react-select/lib/Select.d.ts b/types/react-select/lib/Select.d.ts new file mode 100644 index 0000000000..0298ea0288 --- /dev/null +++ b/types/react-select/lib/Select.d.ts @@ -0,0 +1,419 @@ +import * as React from 'react'; + +import { Option } from './filters'; +import { + InstructionsContext, + ValueEventContext, +} from './accessibility/index'; + +import { + classNames, + noop, + scrollIntoView, +} from './utils'; + +import { + formatGroupLabel, + getOptionLabel, + getOptionValue, + isOptionDisabled, +} from './builtins'; + +import { + PlaceholderOrValue, + SelectComponents, + SelectComponentsConfig, +} from './components/index'; +import { StylesConfig } from './styles'; + +import { + ActionMeta, + ActionTypes, + FocusDirection, + FocusEventHandler, + GroupType, + InputActionMeta, + KeyboardEventHandler, + MenuPlacement, + MenuPosition, + OptionsType, + ValueType, + GroupedOptionsType, +} from './types'; + +export type MouseOrTouchEvent = + | React.MouseEvent + | React.TouchEvent; +export type FormatOptionLabelContext = 'menu' | 'value'; +export interface FormatOptionLabelMeta { + context: FormatOptionLabelContext; + inputValue: string; + selectValue: ValueType; +} + +export interface Props { + /* Aria label (for assistive tech) */ + 'aria-label'?: string; + /* HTML ID of an element that should be used as the label (for assistive tech) */ + 'aria-labelledby'?: string; + /* Focus the control when it is mounted */ + autoFocus?: boolean; + /* Remove the currently focused option when the user presses backspace */ + backspaceRemovesValue?: boolean; + /* Remove focus from the input when the user selects an option (handy for dismissing the keyboard on touch devices) */ + blurInputOnSelect?: boolean; + /* When the user reaches the top/bottom of the menu, prevent scroll on the scroll-parent */ + captureMenuScroll?: boolean; + /* className attribute applied to the outer component */ + className?: string; + /* classNamePrefix attribute used as a base for inner component classNames */ + classNamePrefix?: string | null; + /* Close the select menu when the user selects an option */ + closeMenuOnSelect?: boolean; + /* + If `true`, close the select menu when the user scrolls the document/body. + + If a function, takes a standard javascript `ScrollEvent` you return a boolean: + + `true` => The menu closes + + `false` => The menu stays open + + This is useful when you have a scrollable modal and want to portal the menu out, + but want to avoid graphical issues. + */ + closeMenuOnScroll?: boolean | EventListener; + /* + This complex object includes all the compositional components that are used + in `react-select`. If you wish to overwrite a component, pass in an object + with the appropriate namespace. + + If you only wish to restyle a component, we recommend using the `styles` prop + instead. For a list of the components that can be passed in, and the shape + that will be passed to them, see [the components docs](/api#components) + */ + components?: SelectComponentsConfig; + /* Whether the value of the select, e.g. SingleValue, should be displayed in the control. */ + controlShouldRenderValue?: boolean; + /* Delimiter used to join multiple values into a single HTML Input value */ + delimiter?: string; + /* Clear all values when the user presses escape AND the menu is closed */ + escapeClearsValue?: boolean; + /* Custom method to filter whether an option should be displayed in the menu */ + filterOption?: (( + option: Option, + rawInput: string + ) => boolean) | null; + /* Formats group labels in the menu as React components */ + formatGroupLabel?: typeof formatGroupLabel; + /* Formats option labels in the menu and control as React components */ + formatOptionLabel?: (a: OptionType, b: FormatOptionLabelMeta) => Node; + /* Resolves option data to a string to be displayed as the label by components */ + getOptionLabel?: typeof getOptionLabel; + /* Resolves option data to a string to compare options and specify value attributes */ + getOptionValue?: typeof getOptionValue; + /* Hide the selected option from the menu */ + hideSelectedOptions?: boolean; + /* The id to set on the SelectContainer component. */ + id?: string; + /* The value of the search input */ + inputValue?: string; + /* The id of the search input */ + inputId?: string; + /* Define an id prefix for the select components e.g. {your-id}-value */ + instanceId?: number | string; + /* Is the select value clearable */ + isClearable?: boolean; + /* Is the select disabled */ + isDisabled?: boolean; + /* Is the select in a state of loading (async) */ + isLoading?: boolean; + /* Override the built-in logic to detect whether an option is disabled */ + isOptionDisabled?: (a: OptionType, b: OptionsType) => boolean | false; + /* Override the built-in logic to detect whether an option is selected */ + isOptionSelected?: (a: OptionType, b: OptionsType) => boolean; + /* Support multiple selected options */ + isMulti?: boolean; + /* Is the select direction right-to-left */ + isRtl?: boolean; + /* Whether to enable search functionality */ + isSearchable?: boolean; + /* Async: Text to display when loading options */ + loadingMessage?: (obj: { inputValue: string }) => string | null; + /* Minimum height of the menu before flipping */ + minMenuHeight?: number; + /* Maximum height of the menu before scrolling */ + maxMenuHeight?: number; + /* Whether the menu is open */ + menuIsOpen?: boolean; + /* Default placement of the menu in relation to the control. 'auto' will flip + when there isn't enough space below the control. */ + menuPlacement?: MenuPlacement; + /* The CSS position value of the menu, when "fixed" extra layout management is required */ + menuPosition?: MenuPosition; + /* Whether the menu should use a portal, and where it should attach */ + menuPortalTarget?: HTMLElement | null; + /* Whether to block scroll events when the menu is open */ + menuShouldBlockScroll?: boolean; + /* Whether the menu should be scrolled into view when it opens */ + menuShouldScrollIntoView?: boolean; + /* Name of the HTML Input (optional - without this, no input will be rendered) */ + name?: string; + /* Text to display when there are no options */ + noOptionsMessage?: (obj: { inputValue: string }) => string | null; + /* Handle blur events on the control */ + onBlur?: FocusEventHandler; + /* Handle change events on the select */ + onChange?: (value: ValueType, action: ActionMeta) => void; + /* Handle focus events on the control */ + onFocus?: FocusEventHandler; + /* Handle change events on the input */ + onInputChange?: (newValue: string, actionMeta: InputActionMeta) => void; + /* Handle key down events on the select */ + onKeyDown?: KeyboardEventHandler; + /* Handle the menu opening */ + onMenuOpen?: () => void; + /* Handle the menu closing */ + onMenuClose?: () => void; + /* Fired when the user scrolls to the top of the menu */ + onMenuScrollToTop?: (event: React.SyntheticEvent) => void; + /* Fired when the user scrolls to the bottom of the menu */ + onMenuScrollToBottom?: (event: React.SyntheticEvent) => void; + /* Allows control of whether the menu is opened when the Select is focused */ + openMenuOnFocus?: boolean; + /* Allows control of whether the menu is opened when the Select is clicked */ + openMenuOnClick?: boolean; + /* Array of options that populate the select menu */ + options?: GroupedOptionsType | OptionsType; + /* Number of options to jump in menu when page{up|down} keys are used */ + pageSize?: number; + /* Placeholder text for the select value */ + placeholder?: string; + /* Status to relay to screen readers */ + screenReaderStatus?: (obj: { count: number }) => string; + /* Style modifier methods */ + styles?: StylesConfig; + /* Sets the tabIndex attribute on the input */ + tabIndex?: string; + /* Select the currently focused option when the user presses tab */ + tabSelectsValue?: boolean; + /* The value of the select; reflected by the selected option */ + value?: ValueType; + + defaultInputValue?: string; + defaultMenuIsOpen?: boolean; + defaultValue?: ValueType; +} + +export const defaultProps: Props; + +export interface MenuOptions { + render: OptionType[]; + focusable: OptionType[]; +} + +export interface State { + ariaLiveSelection: string; + ariaLiveContext: string; + inputIsHidden: boolean; + isFocused: boolean; + isComposing: boolean; + focusedOption: OptionType | null; + focusedValue: OptionType | null; + menuOptions: MenuOptions; + selectValue: OptionsType; +} + +export type ElRef = React.Ref; + +export default class Select extends React.Component, State> { + static defaultProps: Props; + + // Misc. Instance Properties + // ------------------------------ + + blockOptionHover: boolean; + clearFocusValueOnUpdate: boolean; + commonProps: any; // TODO + components: SelectComponents; + hasGroups: boolean; + initialTouchX: number; + initialTouchY: number; + inputIsHiddenAfterUpdate: boolean | null; + instancePrefix: string; + openAfterFocus: boolean; + scrollToFocusedOptionOnUpdate: boolean; + userIsDragging: boolean | null; + + // Refs + // ------------------------------ + + controlRef: ElRef; + getControlRef: (ref: HTMLElement) => void; + focusedOptionRef: ElRef; + getFocusedOptionRef: (ref: HTMLElement) => void; + menuListRef: ElRef; + getMenuListRef: (ref: HTMLElement) => void; + inputRef: ElRef; + getInputRef: (ref: HTMLElement) => void; + + // Lifecycle + // ------------------------------ + + cacheComponents: (components: SelectComponents) => void; + + // ============================== + // Consumer Handlers + // ============================== + + onMenuOpen(): void; + onMenuClose(): void; + onInputChange(newValue: string, actionMeta: InputActionMeta): void; + + // ============================== + // Methods + // ============================== + + focusInput(): void; + blurInput(): void; + + // aliased for consumers + focus(): void; + blur(): void; + + openMenu(focusOption: 'first' | 'last'): void; + focusValue(direction: 'previous' | 'next'): void; + + focusOption(direction: FocusDirection): void; + setValue: ( + newValue: ValueType, + action: ActionTypes, + option?: OptionType + ) => void; + selectOption: (newValue: OptionType) => void; + removeValue: (removedValue: OptionType) => void; + clearValue: () => void; + popValue: () => void; + + // ============================== + // Getters + // ============================== + + getCommonProps(): { + cx: any; + clearValue: () => void; + getStyles: (key: string, props: {}) => {}; + getValue: () => OptionType[]; + hasValue: boolean; + isMulti: boolean; + isRtl: boolean; + options: OptionsType; + selectOption: (newValue: OptionType) => void; + setValue: (newValue: ValueType, action: ActionTypes, option?: OptionType) => void; + selectProps: Readonly<{ + children?: Node; + }> & Readonly>; +}; + + getNextFocusedValue(nextSelectValue: OptionsType): OptionType; + + getNextFocusedOption(options: OptionsType): OptionType; + getOptionLabel: (data: OptionType) => string; + getOptionValue: (data: OptionType) => string; + getStyles: (key: string, props: {}) => {}; + getElementId: (element: 'group' | 'input' | 'listbox' | 'option') => string; + getActiveDescendentId: () => any; + + // ============================== + // Helpers + // ============================== + announceAriaLiveSelection: (props: { + event: string, + context: ValueEventContext, + }) => void; + announceAriaLiveContext: (props: { + event: string, + context?: InstructionsContext, + }) => void; + + hasValue(): boolean; + hasOptions(): boolean; + countOptions(): number; + isClearable(): boolean; + isOptionDisabled(option: OptionType, selectValue: OptionsType): boolean; + isOptionSelected(option: OptionType, selectValue: OptionsType): boolean; + filterOption(option: {}, inputValue: string): boolean; + formatOptionLabel(data: OptionType, context: FormatOptionLabelContext): Node; + formatGroupLabel(data: GroupType): Node; + + // ============================== + // Mouse Handlers + // ============================== + + onMenuMouseDown: (event: React.MouseEvent) => void; + onMenuMouseMove: (event: React.MouseEvent) => void; + onControlMouseDown: (event: MouseOrTouchEvent) => void; + onDropdownIndicatorMouseDown: (event: MouseOrTouchEvent) => void; + onClearIndicatorMouseDown: (event: MouseOrTouchEvent) => void; + onScroll: (event: Event) => void; + + // ============================== + // Composition Handlers + // ============================== + + startListeningComposition(): void; + stopListeningComposition(): void; + onCompositionStart: () => void; + onCompositionEnd: () => void; + + // ============================== + // Touch Handlers + // ============================== + + startListeningToTouch(): void; + stopListeningToTouch(): void; + onTouchStart: (event: TouchEvent) => void; + onTouchMove: (event: TouchEvent) => void; + onTouchEnd: (event: TouchEvent) => void; + onControlTouchEnd: (event: React.TouchEvent) => void; + onClearIndicatorTouchEnd: (event: React.TouchEvent) => void; + onDropdownIndicatorTouchEnd: (event: React.TouchEvent) => void; + + // ============================== + // Focus Handlers + // ============================== + + handleInputChange: (event: React.KeyboardEvent) => void; + onInputFocus: (event: React.FocusEvent) => void; + onInputBlur: (event: React.FocusEvent) => void; + onOptionHover: (focusedOption: OptionType) => void; + shouldHideSelectedOptions: () => boolean; + + // ============================== + // Keyboard Handlers + // ============================== + + onKeyDown: (event: React.KeyboardEvent) => void; + + // ============================== + // Menu Options + // ============================== + + buildMenuOptions(props: Props, selectValue: OptionsType): MenuOptions; + + // ============================== + // Renderers + // ============================== + constructAriaLiveMessage(): string; + + renderInput(): Node; + renderPlaceholderOrValue(): PlaceholderOrValue | null; + renderClearIndicator(): Node; + renderLoadingIndicator(): Node; + renderIndicatorSeparator(): Node; + renderDropdownIndicator(): Node; + renderMenu(): Node; + renderFormField(): Node; + + renderLiveRegion(): Node; +} diff --git a/types/react-select/lib/accessibility/index.d.ts b/types/react-select/lib/accessibility/index.d.ts new file mode 100644 index 0000000000..633aaeda72 --- /dev/null +++ b/types/react-select/lib/accessibility/index.d.ts @@ -0,0 +1,10 @@ +export interface InstructionsContext { isSearchable?: boolean; isMulti?: boolean; label?: string; } +export interface ValueEventContext { value: string; } + +export function instructionsAriaMessage(event: any, context?: InstructionsContext): string; + +export function valueEventAriaMessage(event: any, context: ValueEventContext): string; + +export function valueFocusAriaMessage({ focusedValue, getOptionLabel, selectValue }: any): string; +export function optionFocusAriaMessage({ focusedOption, getOptionLabel, options }: any): string; +export function resultsAriaMessage({ inputValue, screenReaderMessage }: any): string; diff --git a/types/react-select/lib/animated/Input.d.ts b/types/react-select/lib/animated/Input.d.ts new file mode 100644 index 0000000000..ad752a96c5 --- /dev/null +++ b/types/react-select/lib/animated/Input.d.ts @@ -0,0 +1,10 @@ +import * as React from 'react'; +import { InputProps } from '../components/Input'; +import { BaseTransition } from './transitions'; +import { PropsWithInnerRef } from '../types'; + +export type AnimatedInputProps = BaseTransition & PropsWithInnerRef & InputProps; + +export function AnimatedInput(WrappedComponent: React.ComponentType): React.ComponentType; + +export default AnimatedInput; diff --git a/types/react-select/lib/animated/MultiValue.d.ts b/types/react-select/lib/animated/MultiValue.d.ts new file mode 100644 index 0000000000..8a8f37ad16 --- /dev/null +++ b/types/react-select/lib/animated/MultiValue.d.ts @@ -0,0 +1,12 @@ +import { ComponentType } from 'react'; +import { MultiValueProps } from '../components/MultiValue'; +import { Collapse, fn } from './transitions'; + +export type AnimatedMultiValueProps = { + in: boolean, + onExited: fn, +} & MultiValueProps; + +export function AnimatedMultiValue(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedMultiValue; diff --git a/types/react-select/lib/animated/Placeholder.d.ts b/types/react-select/lib/animated/Placeholder.d.ts new file mode 100644 index 0000000000..1dbd3ba203 --- /dev/null +++ b/types/react-select/lib/animated/Placeholder.d.ts @@ -0,0 +1,9 @@ +import { ComponentType } from 'react'; +import { PlaceholderProps } from '../components/Placeholder'; +import { Fade, collapseDuration } from './transitions'; + +export type AnimatedPlaceholderProps = PlaceholderProps; + +export function AnimatedPlaceholder(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedPlaceholder; diff --git a/types/react-select/lib/animated/SingleValue.d.ts b/types/react-select/lib/animated/SingleValue.d.ts new file mode 100644 index 0000000000..6cd1bea908 --- /dev/null +++ b/types/react-select/lib/animated/SingleValue.d.ts @@ -0,0 +1,9 @@ +import { ComponentType } from 'react'; +import { SingleValueProps } from '../components/SingleValue'; +import { Fade } from './transitions'; + +export type AnimatedSingleValueProps = SingleValueProps; + +export function AnimatedSingleValue(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedSingleValue; diff --git a/types/react-select/lib/animated/ValueContainer.d.ts b/types/react-select/lib/animated/ValueContainer.d.ts new file mode 100644 index 0000000000..6bd15c0c19 --- /dev/null +++ b/types/react-select/lib/animated/ValueContainer.d.ts @@ -0,0 +1,9 @@ +import { ComponentType } from 'react'; +import { TransitionGroup } from 'react-transition-group'; +import { ValueContainerProps } from '../components/containers'; + +export type AnimatedValueContainerProps = ValueContainerProps; + +export function AnimatedValueContainer(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedValueContainer; diff --git a/types/react-select/lib/animated/index.d.ts b/types/react-select/lib/animated/index.d.ts new file mode 100644 index 0000000000..6760d55e81 --- /dev/null +++ b/types/react-select/lib/animated/index.d.ts @@ -0,0 +1,17 @@ +import { ComponentType } from 'react'; +import { SelectComponents, defaultComponents } from '../components/index'; +import { default as AnimatedInput, AnimatedInputProps } from './Input'; +import { default as AnimatedMultiValue, AnimatedMultiValueProps } from './MultiValue'; +import { default as AnimatedPlaceholder, AnimatedPlaceholderProps } from './Placeholder'; +import { default as AnimatedSingleValue, AnimatedSingleValueProps } from './SingleValue'; +import { default as AnimatedValueContainer, AnimatedValueContainerProps } from './ValueContainer'; + +export function makeAnimated(externalComponents?: SelectComponents): SelectComponents; + +export const Input: ComponentType; +export const MultiValue: ComponentType>; +export const Placeholder: ComponentType>; +export const SingleValue: ComponentType>; +export const ValueContainer: ComponentType>; + +export default makeAnimated; diff --git a/types/react-select/lib/animated/transitions.d.ts b/types/react-select/lib/animated/transitions.d.ts new file mode 100644 index 0000000000..ee2bd3c83b --- /dev/null +++ b/types/react-select/lib/animated/transitions.d.ts @@ -0,0 +1,50 @@ +import * as React from 'react'; +import { Transition } from 'react-transition-group'; + +export type fn = () => void; +export interface BaseTransition { + /** Whether we are in a transition. */ + in: boolean; + /** Function to be called once transition finishes. */ + onExited: fn; +} + +// ============================== +// Fade Transition +// ============================== + +export type FadeProps = BaseTransition & { + component: React.ComponentType, + duration: number, +}; +export const Fade: React.ComponentType; + +// ============================== +// Collapse Transition +// ============================== + +export const collapseDuration: number; + +export type TransitionState = 'exiting' | 'exited'; +export type Width = number | 'auto'; +export interface CollapseProps { children: any; in: boolean; } +export interface CollapseState { width: Width; } + +// wrap each MultiValue with a collapse transition; decreases width until +// finally removing from DOM +export class Collapse extends React.Component { + duration: number; + transition: { + exiting: any, + exited: any, + }; + + // width must be calculated; cannot transition from `undefined` to `number` + getWidth: (ref: React.Ref) => void; + + // get base styles + getStyle: (width: Width) => any; + + // get transition styles + getTransition: (state: TransitionState) => any; +} diff --git a/types/react-select/lib/builtins.d.ts b/types/react-select/lib/builtins.d.ts new file mode 100644 index 0000000000..b1e1c37cc8 --- /dev/null +++ b/types/react-select/lib/builtins.d.ts @@ -0,0 +1,10 @@ +import { ReactNode as Node } from 'react'; +import { GroupType } from './types'; + +export function formatGroupLabel(group: GroupType): Node; + +export function getOptionLabel(option: any): string; + +export function getOptionValue(option: any): string; + +export function isOptionDisabled(option: any): boolean; diff --git a/types/react-select/lib/components/Control.d.ts b/types/react-select/lib/components/Control.d.ts new file mode 100644 index 0000000000..019f75bee9 --- /dev/null +++ b/types/react-select/lib/components/Control.d.ts @@ -0,0 +1,29 @@ +import { ComponentType, ReactNode as Node, Ref as ElementRef } from 'react'; + +import { borderRadius, colors, spacing } from '../theme'; +import { CommonProps, PropsWithStyles } from '../types'; + +interface State { + /** Whether the select is disabled. */ + isDisabled: boolean; + /** Whether the select is focused. */ + isFocused: boolean; +} + +export type ControlProps = CommonProps & + PropsWithStyles & + State & { + /** Children to render. */ + children: Node, + innerRef: ElementRef, + /** The mouse down event and the innerRef to pass down to the controller element. */ + innerProps: { + onMouseDown: (event: React.MouseEvent) => void, + }, + }; + +export function css(state: State): any; // TODO css type + +declare const Control: ComponentType>; + +export default Control; diff --git a/types/react-select/lib/components/Group.d.ts b/types/react-select/lib/components/Group.d.ts new file mode 100644 index 0000000000..d37964c0b4 --- /dev/null +++ b/types/react-select/lib/components/Group.d.ts @@ -0,0 +1,24 @@ +import { ReactNode as Node, ComponentType } from 'react'; + +import { spacing } from '../theme'; +import { CommonProps } from '../types'; + +interface ComponentProps { + /** The children to be rendered. */ + children: Node; + /** Component to wrap the label, recieves headingProps. */ + Heading: ComponentType; + /** Label to be displayed in the heading component. */ + label: Node; +} +export type GroupProps = CommonProps & ComponentProps; + +export function groupCSS(): any; // TODO css type + +export const Group: ComponentType>; + +export function groupHeadingCSS(): any; // TODO css type + +export const GroupHeading: ComponentType; + +export default Group; diff --git a/types/react-select/lib/components/Input.d.ts b/types/react-select/lib/components/Input.d.ts new file mode 100644 index 0000000000..16f07491d2 --- /dev/null +++ b/types/react-select/lib/components/Input.d.ts @@ -0,0 +1,23 @@ +import { ComponentType, Ref as ElementRef } from 'react'; + +import { colors, spacing } from '../theme'; + +import { PropsWithStyles, ClassNamesState } from '../types'; + +export type InputProps = PropsWithStyles & { + cx: (a: string | null, b: ClassNamesState, c: string) => string | void, + /** Reference to the internal element */ + innerRef: (element: ElementRef) => void, + /** Set whether the input should be visible. Does not affect input size. */ + isHidden: boolean, + /** Whether the input is disabled */ + isDisabled?: boolean, + className?: string, +}; + +export function inputCSS(props: InputProps): any; // TODO css type; +export function inputStyle(isHidden: boolean): any; // TODO css type + +export const Input: ComponentType; + +export default Input; diff --git a/types/react-select/lib/components/Menu.d.ts b/types/react-select/lib/components/Menu.d.ts new file mode 100644 index 0000000000..85b5ef0fae --- /dev/null +++ b/types/react-select/lib/components/Menu.d.ts @@ -0,0 +1,158 @@ +import { + Component, + ReactElement, + Ref as ElementRef, + ReactNode as Node, + ComponentType +} from 'react'; +import { createPortal } from 'react-dom'; + +import { + animatedScrollTo, + getBoundingClientObj, + RectType, + getScrollParent, + getScrollTop, + scrollTo, +} from '../utils'; +import { borderRadius, colors, spacing } from '../theme'; +import { + InnerRef, + MenuPlacement, + MenuPosition, + CommonProps, +} from '../types'; + +// ============================== +// Menu +// ============================== + +// Get Menu Placement +// ------------------------------ + +interface MenuState { placement: 'bottom' | 'top' | null; maxHeight: number; } +interface PlacementArgs { + maxHeight: number; + menuEl: ElementRef; + minHeight: number; + placement: 'bottom' | 'top' | 'auto'; + shouldScroll: boolean; + isFixedPosition: boolean; +} + +export function getMenuPlacement(args: PlacementArgs): MenuState; + +// Menu Component +// ------------------------------ + +export type MenuProps = CommonProps & { + /** The children to be rendered. */ + children: ReactElement, + /** Callback to update the portal after possible flip. */ + getPortalPlacement: (state: MenuState) => void, + /** Props to be passed to the menu wrapper. */ + innerProps: object, + /** Set the maximum height of the menu. */ + maxMenuHeight: number, + /** Set whether the menu should be at the top, at the bottom. The auto options sets it to bottom. */ + menuPlacement: MenuPlacement, + /* The CSS position value of the menu, when "fixed" extra layout management is required */ + menuPosition: MenuPosition, + /** Set the minimum height of the menu. */ + minMenuHeight: number, + /** Set whether the page should scroll to show the menu. */ + menuShouldScrollIntoView: boolean, +}; + +export function menuCSS(state: MenuState): any; // TODO css type + +export class Menu extends Component, MenuState> { + static contextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; + getPlacement: (ref: ElementRef) => void; + getState: () => MenuProps & MenuState; +} + +export default Menu; + +// ============================== +// Menu List +// ============================== + +interface MenuListState { + /** Set classname for isMulti */ + isMulti: boolean; + /* Set the max height of the Menu component */ + maxHeight: number; +} + +export interface MenuListProps { + /** The children to be rendered. */ + children: Node; + /** Inner ref to DOM Node */ + innerRef: InnerRef; +} +export type MenuListComponentProps = CommonProps & + MenuListProps & + MenuListState; +export function menuListCSS(state: MenuState): any; // TODO css type +export const MenuList: ComponentType>; + +// ============================== +// Menu Notices +// ============================== + +export function noOptionsMessageCSS(): any; // TODO css type +export function loadingMessageCSS(): any; // TODO css type + +export type NoticeProps = CommonProps & { + /** The children to be rendered. */ + children: Node, + /** Props to be passed on to the wrapper. */ + innerProps: { [key: string]: any }, +}; + +export const NoOptionsMessage: ComponentType>; +// NoOptionsMessage.defaultProps = { +// children: 'No options', +// }; + +export const LoadingMessage: ComponentType>; +// LoadingMessage.defaultProps = { +// children: 'Loading...', +// }; + +// ============================== +// Menu Portal +// ============================== + +export type MenuPortalProps = CommonProps & { + appendTo: HTMLElement, + children: Node, // ideally Menu + controlElement: HTMLElement, + menuPlacement: MenuPlacement, + menuPosition: MenuPosition, +}; +interface MenuPortalState { + placement: 'bottom' | 'top' | null; +} +interface PortalStyleArgs { + offset: number; + position: MenuPosition; + rect: RectType; +} + +export function menuPortalCSS(args: PortalStyleArgs): any; // TODO css type + +export class MenuPortal extends Component, MenuPortalState> { + static childContextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; + getChildContext(): { + getPortalPlacement: (state: MenuState) => void; + }; + + // callback for occassions where the menu must "flip" + getPortalPlacement: (state: MenuState) => void; +} diff --git a/types/react-select/lib/components/MultiValue.d.ts b/types/react-select/lib/components/MultiValue.d.ts new file mode 100644 index 0000000000..495b4fc96f --- /dev/null +++ b/types/react-select/lib/components/MultiValue.d.ts @@ -0,0 +1,57 @@ +import { ComponentType, Component, ReactNode as Node } from 'react'; + +import { borderRadius, colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +export type MultiValueProps = CommonProps &{ + children: Node, + components: any, + cropWithEllipsis: boolean, + data: OptionType, + innerProps: any, + isFocused: boolean, + isDisabled: boolean, + removeProps: { + onTouchEnd: (event: any) => void, + onClick: (event: any) => void, + onMouseDown: (event: any) => void, + }, +}; + +export function multiValueCSS(): any; // TODO css type +export function multiValueLabelCSS(props: MultiValueProps): any; // TODO css type +export function multiValueRemoveCSS(props: MultiValueProps): any; // TODO css type + +export interface MultiValueGenericProps { + children: Node; + data: OptionType; + innerProps: { className?: string }; + selectProps: any; +} +export const MultiValueGeneric: ComponentType>; + +export const MultiValueContainer: typeof MultiValueGeneric; +export const MultiValueLabel: typeof MultiValueGeneric; +export type MultiValueRemoveProps = CommonProps & { + children: Node, + innerProps: { + className: string, + onTouchEnd: (event: any) => void, + onClick: (event: any) => void, + onMouseDown: (event: any) => void, + }, + selectProps: any, +}; +export class MultiValueRemove extends Component> { + static defaultProps: { + children: Node, + }; +} + +export class MultiValue extends Component> { + static defaultProps: { + cropWithEllipsis: boolean, + }; +} + +export default MultiValue; diff --git a/types/react-select/lib/components/Option.d.ts b/types/react-select/lib/components/Option.d.ts new file mode 100644 index 0000000000..743083fff8 --- /dev/null +++ b/types/react-select/lib/components/Option.d.ts @@ -0,0 +1,41 @@ +import { ComponentType, ReactNode as Node, MouseEventHandler } from 'react'; + +import { colors, spacing } from '../theme'; +import { CommonProps, PropsWithStyles, InnerRef } from '../types'; + +interface State { + /** Wether the option is disabled. */ + isDisabled: boolean; + /** Wether the option is focused. */ + isFocused: boolean; + /** Whether the option is selected. */ + isSelected: boolean; +} +interface InnerProps { + id: string; + key: string; + onClick: MouseEventHandler; + onMouseOver: MouseEventHandler; + tabIndex: number; +} +export type OptionProps = PropsWithStyles & + CommonProps & + State & { + /** The children to be rendered. */ + children: Node, + /** Inner ref to DOM Node */ + innerRef: InnerRef, + /** props passed to the wrapping element for the group. */ + innerProps: InnerProps, + /* Text to be displayed representing the option. */ + label: string, + /* Type is used by the menu to determine whether this is an option or a group. + In the case of option this is always `option`. */ + type: 'option', + }; + +export function optionCSS(state: State): any; // TODO css type + +export const Option: ComponentType>; + +export default Option; diff --git a/types/react-select/lib/components/Placeholder.d.ts b/types/react-select/lib/components/Placeholder.d.ts new file mode 100644 index 0000000000..f674f74cc2 --- /dev/null +++ b/types/react-select/lib/components/Placeholder.d.ts @@ -0,0 +1,17 @@ +import { ComponentType, ReactNode as Node } from 'react'; + +import { colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +export type PlaceholderProps = CommonProps & { + /** The children to be rendered. */ + children: Node, + /** props passed to the wrapping element for the group. */ + innerProps: { [key: string]: any }, +}; + +export function placeholderCSS(): any; // TODO css type + +export const Placeholder: ComponentType>; + +export default Placeholder; diff --git a/types/react-select/lib/components/SingleValue.d.ts b/types/react-select/lib/components/SingleValue.d.ts new file mode 100644 index 0000000000..c5f922d84c --- /dev/null +++ b/types/react-select/lib/components/SingleValue.d.ts @@ -0,0 +1,23 @@ +import { ComponentType } from 'react'; +import { colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +interface State { + /** Whether this is disabled */ + isDisabled: boolean; +} +interface ValueProps { + /** The children to be rendered. */ + children: string; + /* The data of the selected option rendered in the Single Value componentn */ + data: OptionType; + /** Props passed to the wrapping element for the group. */ + innerProps: any; +} +export type SingleValueProps = CommonProps & ValueProps & State; + +export function css(props: SingleValueProps): any; // TODO css type + +export const SingleValue: ComponentType>; + +export default SingleValue; diff --git a/types/react-select/lib/components/containers.d.ts b/types/react-select/lib/components/containers.d.ts new file mode 100644 index 0000000000..373a552062 --- /dev/null +++ b/types/react-select/lib/components/containers.d.ts @@ -0,0 +1,57 @@ +import { Component, ReactNode as Node, ComponentType } from 'react'; +import { spacing } from '../theme'; +import { CommonProps, KeyboardEventHandler } from '../types'; + +// ============================== +// Root Container +// ============================== + +export interface ContainerState { + /** Whether the select is disabled. */ + isDisabled: boolean; + /** Whether the text in the select is indented from right to left. */ + isRtl: boolean; +} + +export type ContainerProps = CommonProps & + ContainerState & { + /** The children to be rendered. */ + children: Node, + /** Inner props to be passed down to the container. */ + innerProps: { onKeyDown: KeyboardEventHandler }, + }; +export function containerCSS(state: ContainerState): any; // TODO css type; +export const SelectContainer: ComponentType>; + +// ============================== +// Value Container +// ============================== + +export type ValueContainerProps = CommonProps & { + /** Set when the value container should hold multiple values */ + isMulti: boolean, + /** Whether the value container currently holds a value. */ + hasValue: boolean, + /** The children to be rendered. */ + children: Node, +}; +export function valueContainerCSS(): any; // TODO css type; +export class ValueContainer extends Component> {} + +// ============================== +// Indicator Container +// ============================== + +export interface IndicatorsState { + /** Whether the text should be rendered right to left. */ + isRtl: boolean; +} + +export type IndicatorContainerProps = CommonProps & + IndicatorsState & { + /** The children to be rendered. */ + children: Node, + }; + +export function indicatorsContainerCSS(): any; // TODO css type; +export const IndicatorsContainer: ComponentType>; diff --git a/types/react-select/lib/components/index.d.ts b/types/react-select/lib/components/index.d.ts new file mode 100644 index 0000000000..7d493a562a --- /dev/null +++ b/types/react-select/lib/components/index.d.ts @@ -0,0 +1,142 @@ +import { + ComponentType, + ReactElement as Element, +} from 'react'; +import { + IndicatorContainerProps, + ContainerProps, + ValueContainerProps, + IndicatorsContainer, + SelectContainer, + ValueContainer, +} from './containers'; +import { + IndicatorProps, + LoadingIconProps, + ClearIndicator, + DropdownIndicator, + LoadingIndicator, + IndicatorSeparator, + DownChevron, + CrossIcon, +} from './indicators'; + +import Control, { ControlProps } from './Control'; +import Group, { GroupProps, GroupHeading } from './Group'; +import Input, { InputProps } from './Input'; +import Menu, { + MenuProps, + MenuList, + MenuListComponentProps, + MenuPortal, + MenuPortalProps, + NoticeProps, + NoOptionsMessage, + LoadingMessage, +} from './Menu'; +import MultiValue, { + MultiValueProps, + MultiValueContainer, + MultiValueLabel, + MultiValueRemove, +} from './MultiValue'; +import Option, { OptionProps } from './Option'; +import Placeholder, { PlaceholderProps } from './Placeholder'; +import SingleValue, { SingleValueProps } from './SingleValue'; + +export type PlaceholderOrValue = + | Element>> + | Element>> + | Array>>>; + +export type IndicatorComponentType = ComponentType>; + +export interface SelectComponents { + ClearIndicator: IndicatorComponentType | null; + Control: ComponentType>; + DropdownIndicator: IndicatorComponentType | null; + DownChevron: ComponentType; + CrossIcon: ComponentType; + Group: ComponentType>; + GroupHeading: ComponentType; + IndicatorsContainer: ComponentType>; + IndicatorSeparator: IndicatorComponentType | null; + Input: ComponentType; + LoadingIndicator: ComponentType> | null; + Menu: ComponentType>; + MenuList: ComponentType>; + MenuPortal: ComponentType>; + LoadingMessage: ComponentType>; + NoOptionsMessage: ComponentType>; + MultiValue: ComponentType>; + MultiValueContainer: ComponentType; + MultiValueLabel: ComponentType; + MultiValueRemove: ComponentType; + Option: ComponentType>; + Placeholder: ComponentType>; + SelectContainer: ComponentType>; + SingleValue: ComponentType>; + ValueContainer: ComponentType>; +} + +export interface SelectComponentsConfig { + ClearIndicator?: IndicatorComponentType | null; + Control?: ComponentType>; + DropdownIndicator?: IndicatorComponentType | null; + DownChevron?: ComponentType; + CrossIcon?: ComponentType; + Group?: ComponentType>; + GroupHeading?: ComponentType; + IndicatorsContainer?: ComponentType>; + IndicatorSeparator?: IndicatorComponentType | null; + Input?: ComponentType; + LoadingIndicator?: ComponentType> | null; + Menu?: ComponentType>; + MenuList?: ComponentType>; + MenuPortal?: ComponentType>; + LoadingMessage?: ComponentType>; + NoOptionsMessage?: ComponentType>; + MultiValue?: ComponentType>; + MultiValueContainer?: ComponentType; + MultiValueLabel?: ComponentType; + MultiValueRemove?: ComponentType; + Option?: ComponentType>; + Placeholder?: ComponentType>; + SelectContainer?: ComponentType>; + SingleValue?: ComponentType>; + ValueContainer?: ComponentType>; +} + +export namespace components { + const ClearIndicator: IndicatorComponentType | null; + const Control: ComponentType>; + const DropdownIndicator: IndicatorComponentType | null; + const DownChevron: ComponentType; + const CrossIcon: ComponentType; + const Group: ComponentType>; + const GroupHeading: ComponentType; + const IndicatorsContainer: ComponentType>; + const IndicatorSeparator: IndicatorComponentType | null; + const Input: ComponentType; + const LoadingIndicator: ComponentType> | null; + const Menu: ComponentType>; + const MenuList: ComponentType>; + const MenuPortal: ComponentType>; + const LoadingMessage: ComponentType>; + const NoOptionsMessage: ComponentType>; + const MultiValue: ComponentType>; + const MultiValueContainer: ComponentType; + const MultiValueLabel: ComponentType; + const MultiValueRemove: ComponentType; + const Option: ComponentType>; + const Placeholder: ComponentType>; + const SelectContainer: ComponentType>; + const SingleValue: ComponentType>; + const ValueContainer: ComponentType>; +} + +export interface Props { + components: SelectComponentsConfig; +} + +export function defaultComponents(props: Props): SelectComponentsConfig; diff --git a/types/react-select/lib/components/indicators.d.ts b/types/react-select/lib/components/indicators.d.ts new file mode 100644 index 0000000000..d27cc518da --- /dev/null +++ b/types/react-select/lib/components/indicators.d.ts @@ -0,0 +1,67 @@ +import { ComponentType, ReactElement as ElementType } from 'react'; + +import { colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +// ============================== +// Dropdown & Clear Icons +// ============================== + +export function CrossIcon(props: any): any; // TODO svg type +export function DownChevron(props: any): any; // TODO svg type + +// ============================== +// Dropdown & Clear Buttons +// ============================== + +export type IndicatorProps = CommonProps & { + /** The children to be rendered inside the indicator. */ + children: ElementType, + /** Props that will be passed on to the children. */ + innerProps: any, + /** The focused state of the select. */ + isFocused: boolean, + /** Whether the text is right to left */ + isRtl: boolean, +}; + +export type baseCSS = (props: IndicatorProps) => any; // TODO css type + +export const dropdownIndicatorCSS: baseCSS; +export const DropdownIndicator: ComponentType>; + +export const clearIndicatorCSS: baseCSS; +export const ClearIndicator: ComponentType>; + +// ============================== +// Separator +// ============================== + +export interface SeparatorState { isDisabled: boolean; } + +export function indicatorSeparatorCSS(state: SeparatorState): any; // TODO css type + +export const IndicatorSeparator: ComponentType>; + +// ============================== +// Loading +// ============================== + +export function loadingIndicatorCSS(state: { + isFocused: boolean, + size: number, +}): any; // TODO css type + +export type LoadingIconProps = { + /** Props that will be passed on to the children. */ + innerProps: any, + /** The focused state of the select. */ + isFocused: boolean, + /** Whether the text is right to left */ + isRtl: boolean, +} & CommonProps & { + /** Set size of the container. */ + size: number, +}; +export const LoadingIndicator: ComponentType>; +// TODO LoadingIndicator.defaultProps: { size: number }; diff --git a/types/react-select/lib/diacritics.d.ts b/types/react-select/lib/diacritics.d.ts new file mode 100644 index 0000000000..855a0e152a --- /dev/null +++ b/types/react-select/lib/diacritics.d.ts @@ -0,0 +1 @@ +export function stripDiacritics(str: string): string; diff --git a/types/react-select/lib/filters.d.ts b/types/react-select/lib/filters.d.ts new file mode 100644 index 0000000000..33d1a7fddf --- /dev/null +++ b/types/react-select/lib/filters.d.ts @@ -0,0 +1,16 @@ +export interface Config { + ignoreCase?: boolean; + ignoreAccents?: boolean; + stringify?: (obj: any) => string; + trim?: boolean; + matchFrom?: 'any' | 'start'; +} + +import { stripDiacritics } from './diacritics'; + +export interface Option { label: string; value: string; data: any; } + +export function createFilter(config: Config | null): ( + option: Option, + rawInput: string +) => boolean; diff --git a/types/react-select/lib/stateManager.d.ts b/types/react-select/lib/stateManager.d.ts new file mode 100644 index 0000000000..07a17f52f7 --- /dev/null +++ b/types/react-select/lib/stateManager.d.ts @@ -0,0 +1,36 @@ +import { Component, ComponentType, Ref as ElementRef } from 'react'; + +import { ActionMeta, InputActionMeta, ValueType } from './types'; + +export interface Props { + defaultInputValue?: string; + defaultMenuIsOpen?: boolean; + defaultValue?: ValueType; + inputValue?: string; + menuIsOpen?: boolean; + value?: ValueType; +} +interface State { + inputValue: string; + menuIsOpen: boolean; + value: ValueType; +} + +export class StateManager extends Component, State> { + static defaultProps: Props; + + select: ElementRef; + + focus(): void; + blur(): void; + getProp(key: string): any; + callProp(name: string, ...args: any[]): any; + onChange: (value: any, actionMeta: ActionMeta) => void; + onInputChange: (value: any, actionMeta: InputActionMeta) => void; + onMenuOpen: () => void; + onMenuClose: () => void; +} + +export function manageState(SelectComponent: ComponentType): StateManager; + +export default manageState; diff --git a/types/react-select/lib/styles.d.ts b/types/react-select/lib/styles.d.ts new file mode 100644 index 0000000000..9c5178fed1 --- /dev/null +++ b/types/react-select/lib/styles.d.ts @@ -0,0 +1,99 @@ +import { + containerCSS, + indicatorsContainerCSS, + valueContainerCSS, +} from './components/containers'; +import { css as controlCSS } from './components/Control'; +import { groupCSS, groupHeadingCSS } from './components/Group'; +import { + clearIndicatorCSS, + dropdownIndicatorCSS, + loadingIndicatorCSS, + indicatorSeparatorCSS, +} from './components/indicators'; +import { inputCSS } from './components/Input'; +import { placeholderCSS } from './components/Placeholder'; +import { optionCSS } from './components/Option'; +import { + menuCSS, + menuListCSS, + menuPortalCSS, + noOptionsMessageCSS, + loadingMessageCSS, +} from './components/Menu'; +import { css as singleValueCSS } from './components/SingleValue'; +import { + multiValueCSS, + multiValueLabelCSS, + multiValueRemoveCSS, +} from './components/MultiValue'; + +export interface Props { [key: string]: any; } + +/** + * @param base -- the component's default style + * @param state -- the component's current state e.g. `isFocused` + * @returns + */ +export type styleFn = (base: any, state: any) => any; + +export interface Styles { + clearIndicator?: styleFn; + container?: styleFn; + control?: styleFn; + dropdownIndicator?: styleFn; + group?: styleFn; + groupHeading?: styleFn; + indicatorsContainer?: styleFn; + indicatorSeparator?: styleFn; + input?: styleFn; + loadingIndicator?: styleFn; + // TODO loadingMessageCSS?: styleFn; + loadingMessage?: styleFn; + menu?: styleFn; + menuList?: styleFn; + menuPortal?: styleFn; + multiValue?: styleFn; + multiValueLabel?: styleFn; + multiValueRemove?: styleFn; + // TODO noOptionsMessageCSS?: styleFn; + noOptionsMessage?: styleFn; + option?: styleFn; + placeholder?: styleFn; + singleValue?: styleFn; + valueContainer: styleFn; +} +export interface StylesConfig { + clearIndicator?: styleFn; + container?: styleFn; + control?: styleFn; + dropdownIndicator?: styleFn; + group?: styleFn; + groupHeading?: styleFn; + indicatorsContainer?: styleFn; + indicatorSeparator?: styleFn; + input?: styleFn; + loadingIndicator?: styleFn; + // TODO loadingMessageCSS?: styleFn; + loadingMessage?: styleFn; + menu?: styleFn; + menuList?: styleFn; + menuPortal?: styleFn; + multiValue?: styleFn; + multiValueLabel?: styleFn; + multiValueRemove?: styleFn; + // TODO noOptionsMessageCSS?: styleFn; + noOptionsMessage?: styleFn; + option?: styleFn; + placeholder?: styleFn; + singleValue?: styleFn; + valueContainer?: styleFn; +} +export type GetStyles = (a: string, b: Props) => any; + +export const defaultStyles: Styles; + +// Merge Utility +// Allows consumers to extend a base Select with additional styles + +export function mergeStyles(source: any, target: any): any; diff --git a/types/react-select/lib/theme.d.ts b/types/react-select/lib/theme.d.ts new file mode 100644 index 0000000000..7282dd20ad --- /dev/null +++ b/types/react-select/lib/theme.d.ts @@ -0,0 +1,53 @@ +export const borderRadius: number; + +export const colors: { + text: string; + textLight: string; + primary: string; + primary75: string; + primary50: string; + primary25: string; + danger: string; + dangerLight: string; + + neutral0: string; + neutral1: string; + neutral2: string; + neutral3: string; + neutral4: string; + neutral5: string; + neutral10: string; + neutral20: string; + neutral30: string; + neutral40: string; + neutral50: string; + neutral60: string; + neutral70: string; + neutral80: string; + neutral90: string; + neutral100: string; + + neutral1a: string; + neutral2a: string; + neutral3a: string; + neutral4a: string; + neutral5a: string; + neutral10a: string; + neutral20a: string; + neutral30a: string; + neutral40a: string; + neutral50a: string; + neutral60a: string; + neutral70a: string; + neutral80a: string; + neutral90a: string; +}; + +export const spacing: { + /* Used to calculate consistent margin/padding on elements */ + baseUnit: number, + /* The minimum height of the control */ + controlHeight: number, + /* The amount of space between the control and menu */ + menuGutter: number, +}; diff --git a/types/react-select/lib/types.d.ts b/types/react-select/lib/types.d.ts new file mode 100644 index 0000000000..08ebfae965 --- /dev/null +++ b/types/react-select/lib/types.d.ts @@ -0,0 +1,100 @@ +import * as React from 'react'; + +export type OptionsType = OptionType[]; + +export interface GroupType { + options: OptionsType; + [key: string]: any; +} + +export type GroupedOptionsType = Array>; + +export type ValueType = OptionType | OptionsType | null | undefined; + +export type FocusEventHandler = (event: React.FocusEvent) => void; +export type MouseEventHandler = (event: React.MouseEvent) => void; +export type KeyboardEventHandler = (event: React.KeyboardEvent) => void; + +export type InnerRef = React.Ref; +export interface PropsWithInnerRef { + /** The inner reference. */ + innerRef: React.Ref; +} + +export interface PropsWithStyles { + /* + Get the styles of a particular part of the select. Pass in the name of the + property as the first argument, and the current props as the second argument. + See the `styles` object for the properties available. + */ + getStyles: (name: string, props: any) => {}; +} + +export type ClassNameList = string[]; +export type ClassNamesState = { [key: string]: boolean } | undefined; + +export interface CommonProps { + clearValue: () => void; + className?: string; + cx: (a: string | null, b: ClassNamesState | undefined, c: string | undefined) => string | void; + /* + Get the styles of a particular part of the select. Pass in the name of the + property as the first argument, and the current props as the second argument. + See the `styles` object for the properties available. + */ + getStyles: (name: string, props: any) => {}; + getValue: () => ValueType; + hasValue: boolean; + isMulti: boolean; + options: OptionsType; + selectOption: (option: OptionType) => void; + selectProps: any; + setValue: (value: ValueType, action: ActionTypes) => void; +} + +export type ActionTypes = + | 'select-option' + | 'deselect-option' + | 'remove-value' + | 'pop-value' + | 'set-value' + | 'clear' + | 'create-option'; + +export interface ActionMeta { + action: ActionTypes; +} + +export type InputActionTypes = + | 'set-value' + | 'input-change' + | 'input-blur' + | 'menu-close'; + +export interface InputActionMeta { + action: InputActionTypes; +} + +export type MenuPlacement = 'auto' | 'bottom' | 'top'; +export type MenuPosition = 'absolute' | 'fixed'; + +export type FocusDirection = + | 'up' + | 'down' + | 'pageup' + | 'pagedown' + | 'first' + | 'last'; + +export type OptionProps = PropsWithInnerRef & { + data: any, + id: number, + index: number, + isDisabled: boolean, + isFocused: boolean, + isSelected: boolean, + label: string, + onClick: MouseEventHandler, + onMouseOver: MouseEventHandler, + value: any, +}; diff --git a/types/react-select/lib/utils.d.ts b/types/react-select/lib/utils.d.ts new file mode 100644 index 0000000000..c907d59c2a --- /dev/null +++ b/types/react-select/lib/utils.d.ts @@ -0,0 +1,121 @@ +import * as React from 'react'; +import { + ClassNamesState, + InputActionMeta, + OptionsType, + ValueType, +} from './types'; + +// ============================== +// NO OP +// ============================== + +export function noop(): void; +export function emptyString(): string; + +// ============================== +// Class Name Prefixer +// ============================== + +export function classNames( + prefix?: string | null, + cssKey?: string | null, + state?: ClassNamesState, + className?: string, +): string; + +// ============================== +// Clean Value +// ============================== + +export function cleanValue(value: ValueType): OptionsType; + +// ============================== +// Handle Input Change +// ============================== + +export function handleInputChange( + inputValue: string, + actionMeta: InputActionMeta, + onInputChange?: (inputValue: string, actionMeta: InputActionMeta) => string | void +): string; + +// ============================== +// Scroll Helpers +// ============================== + +export function isDocumentElement(el: Element): boolean; + +// Normalized Scroll Top +// ------------------------------ + +export function normalizedHeight(el: Element): number; + +// Normalized scrollTo & scrollTop +// ------------------------------ + +export function getScrollTop(el: Element): number; + +export function scrollTo(el: Element, top: number): void; + +// Get Scroll Parent +// ------------------------------ + +export function getScrollParent(element: React.Ref): Element; + +// Animated Scroll To +// ------------------------------ + +export function animatedScrollTo( + element: Element, + to: number, + duration: number, + callback: (element: Element) => void +): void; + +// Scroll Into View +// ------------------------------ + +export function scrollIntoView( + menuEl: HTMLElement, + focusedEl: HTMLElement +): void; + +// ============================== +// Get bounding client object +// ============================== + +// cannot get keys using array notation with DOMRect +export function getBoundingClientObj(element: HTMLElement): { + bottom: number; + height: number; + left: number; + right: number; + top: number; + width: number; +}; +export interface RectType { + left: number; + right: number; + bottom: number; + height: number; + width: number; +} + +// ============================== +// String to Key (kebabify) +// ============================== + +export function toKey(str: string): string; + +// ============================== +// Touch Capability Detector +// ============================== + +export function isTouchCapable(): boolean; + +// ============================== +// Mobile Device Detector +// ============================== + +export function isMobileDevice(): boolean; diff --git a/types/react-select/test/AtlaskitDummy.ts b/types/react-select/test/AtlaskitDummy.ts new file mode 100644 index 0000000000..e6e75e9e32 --- /dev/null +++ b/types/react-select/test/AtlaskitDummy.ts @@ -0,0 +1,11 @@ +export const Tooltip = (props: any) => null; + +export const EmojiIcon = (props: any) => null; + +export const EditorPanelIcon = (props: any) => null; + +export const Spinner = (props: any) => null; + +export const Button = (props: any) => null; + +export const Modal = (props: any) => null; diff --git a/types/react-select/test/ChronoNodeDummy.ts b/types/react-select/test/ChronoNodeDummy.ts new file mode 100644 index 0000000000..1e4aed01b0 --- /dev/null +++ b/types/react-select/test/ChronoNodeDummy.ts @@ -0,0 +1 @@ +export function parseDate(a: any): any {} diff --git a/types/react-select/test/data.ts b/types/react-select/test/data.ts new file mode 100644 index 0000000000..a4bff0225d --- /dev/null +++ b/types/react-select/test/data.ts @@ -0,0 +1,132 @@ +import { GroupedOptionsType, GroupType } from "react-select/lib/types"; + +export interface ColourOption { + value: string; + label: string; + color: string; + disabled?: boolean; +} + +export const colourOptions: ColourOption[] = [ + { value: 'ocean', label: 'Ocean', color: '#00B8D9' }, + { value: 'blue', label: 'Blue', color: '#0052CC', disabled: true }, + { value: 'purple', label: 'Purple', color: '#5243AA' }, + { value: 'red', label: 'Red', color: '#FF5630' }, + { value: 'orange', label: 'Orange', color: '#FF8B00' }, + { value: 'yellow', label: 'Yellow', color: '#FFC400' }, + { value: 'green', label: 'Green', color: '#36B37E' }, + { value: 'forest', label: 'Forest', color: '#00875A' }, + { value: 'slate', label: 'Slate', color: '#253858' }, + { value: 'silver', label: 'Silver', color: '#666666' }, +]; + +export interface FlavourOption { + value: string; + label: string; + rating: 'safe' | 'good' | 'wild' | 'crazy'; +} + +export const flavourOptions: FlavourOption[] = [ + { value: 'vanilla', label: 'Vanilla', rating: 'safe' }, + { value: 'chocolate', label: 'Chocolate', rating: 'good' }, + { value: 'strawberry', label: 'Strawberry', rating: 'wild' }, + { value: 'salted-caramel', label: 'Salted Caramel', rating: 'crazy' }, +]; + +export interface StateOption { + value: string; + label: string; +} + +export const stateOptions: StateOption[] = [ + { value: 'AL', label: 'Alabama' }, + { value: 'AK', label: 'Alaska' }, + { value: 'AS', label: 'American Samoa' }, + { value: 'AZ', label: 'Arizona' }, + { value: 'AR', label: 'Arkansas' }, + { value: 'CA', label: 'California' }, + { value: 'CO', label: 'Colorado' }, + { value: 'CT', label: 'Connecticut' }, + { value: 'DE', label: 'Delaware' }, + { value: 'DC', label: 'District Of Columbia' }, + { value: 'FM', label: 'Federated States Of Micronesia' }, + { value: 'FL', label: 'Florida' }, + { value: 'GA', label: 'Georgia' }, + { value: 'GU', label: 'Guam' }, + { value: 'HI', label: 'Hawaii' }, + { value: 'ID', label: 'Idaho' }, + { value: 'IL', label: 'Illinois' }, + { value: 'IN', label: 'Indiana' }, + { value: 'IA', label: 'Iowa' }, + { value: 'KS', label: 'Kansas' }, + { value: 'KY', label: 'Kentucky' }, + { value: 'LA', label: 'Louisiana' }, + { value: 'ME', label: 'Maine' }, + { value: 'MH', label: 'Marshall Islands' }, + { value: 'MD', label: 'Maryland' }, + { value: 'MA', label: 'Massachusetts' }, + { value: 'MI', label: 'Michigan' }, + { value: 'MN', label: 'Minnesota' }, + { value: 'MS', label: 'Mississippi' }, + { value: 'MO', label: 'Missouri' }, + { value: 'MT', label: 'Montana' }, + { value: 'NE', label: 'Nebraska' }, + { value: 'NV', label: 'Nevada' }, + { value: 'NH', label: 'New Hampshire' }, + { value: 'NJ', label: 'New Jersey' }, + { value: 'NM', label: 'New Mexico' }, + { value: 'NY', label: 'New York' }, + { value: 'NC', label: 'North Carolina' }, + { value: 'ND', label: 'North Dakota' }, + { value: 'MP', label: 'Northern Mariana Islands' }, + { value: 'OH', label: 'Ohio' }, + { value: 'OK', label: 'Oklahoma' }, + { value: 'OR', label: 'Oregon' }, + { value: 'PW', label: 'Palau' }, + { value: 'PA', label: 'Pennsylvania' }, + { value: 'PR', label: 'Puerto Rico' }, + { value: 'RI', label: 'Rhode Island' }, + { value: 'SC', label: 'South Carolina' }, + { value: 'SD', label: 'South Dakota' }, + { value: 'TN', label: 'Tennessee' }, + { value: 'TX', label: 'Texas' }, + { value: 'UT', label: 'Utah' }, + { value: 'VT', label: 'Vermont' }, + { value: 'VI', label: 'Virgin Islands' }, + { value: 'VA', label: 'Virginia' }, + { value: 'WA', label: 'Washington' }, + { value: 'WV', label: 'West Virginia' }, + { value: 'WI', label: 'Wisconsin' }, + { value: 'WY', label: 'Wyoming' }, +]; + +export const optionLength = [ + { value: 1, label: 'general' }, + { + value: 2, + label: + 'Evil is the moment when I lack the strength to be true to the Good that compels me.', + }, + { + value: 3, + label: + // tslint:disable-next-line:max-line-length + "It is now an easy matter to spell out the ethic of a truth: 'Do all that you can to persevere in that which exceeds your perseverance. Persevere in the interruption. Seize in your being that which has seized and broken you.", + }, +]; + +// let bigOptions = []; +// for (let i = 0; i < 10000; i++) { +// bigOptions = bigOptions.concat(colourOptions); +// } + +const colourGroup: GroupType = { + label: 'Colours', + options: colourOptions +}; +const flavourGroup: GroupType = { + label: 'Flavours', + options: flavourOptions, +}; + +export const groupedOptions: GroupedOptionsType = [ colourGroup, flavourGroup ]; diff --git a/types/react-select/test/examples/AccessingInternals.tsx b/types/react-select/test/examples/AccessingInternals.tsx new file mode 100644 index 0000000000..8948bc19e7 --- /dev/null +++ b/types/react-select/test/examples/AccessingInternals.tsx @@ -0,0 +1,114 @@ +import * as React from 'react'; + +import Select from 'react-select'; +import AsyncSelect from 'react-select/lib/Async'; +import CreatableSelect from 'react-select/lib/Creatable'; +import { Note } from '../styled-components'; +import { ColourOption, colourOptions } from '../data'; + +const filterColors = (inputValue: string) => + colourOptions.filter(i => + i.label.toLowerCase().includes(inputValue.toLowerCase()) + ); + +const promiseOptions = (inputValue: string) => + new Promise(resolve => { + setTimeout(() => { + resolve(filterColors(inputValue)); + }, 1000); + }); + +export default class AccessingInterals extends React.Component { + selectRef: Select; + asyncRef: AsyncSelect; + creatableRef: CreatableSelect; + focus = () => { + console.log(this.selectRef); + this.selectRef.focus(); + } + focusCreatable = () => { + console.log(this.creatableRef); + this.creatableRef.focus(); + } + focusAsync = () => { + console.log(this.asyncRef); + this.asyncRef.focus(); + } + blurAsync = () => { + this.asyncRef.blur(); + } + blurCreatable = () => { + this.creatableRef.blur(); + } + blur = () => this.selectRef.blur(); + onSelectRef = (ref: any) => { + console.log(ref); + this.selectRef = ref; + } + render() { + return ( + +

+ Creatable Select +

+ { this.creatableRef = ref; }} + isClearable + options={colourOptions} + /> + + + + + + +

+ Async Select +

+ { this.asyncRef = ref; }} + cacheOptions + defaultOptions + loadOptions={promiseOptions} + /> + + + + + + +

Select

+ +); diff --git a/types/react-select/test/examples/BasicSingle.tsx b/types/react-select/test/examples/BasicSingle.tsx new file mode 100644 index 0000000000..69697566c2 --- /dev/null +++ b/types/react-select/test/examples/BasicSingle.tsx @@ -0,0 +1,101 @@ +import * as React from 'react'; + +import Select from 'react-select'; +import { colourOptions } from '../data'; +import { Note } from '../styled-components'; + +const Checkbox = (props: any) => ; + +interface State { + isClearable: boolean; + isDisabled: boolean; + isLoading: boolean; + isRtl: boolean; + isSearchable: boolean; +} + +export default class SingleSelect extends React.Component { + state = { + isClearable: true, + isDisabled: false, + isLoading: false, + isRtl: false, + isSearchable: true, + }; + + toggleClearable = () => + this.setState(state => ({ isClearable: !state.isClearable })) + toggleDisabled = () => + this.setState(state => ({ isDisabled: !state.isDisabled })) + toggleLoading = () => + this.setState(state => ({ isLoading: !state.isLoading })) + toggleRtl = () => this.setState(state => ({ isRtl: !state.isRtl })); + toggleSearchable = () => + this.setState(state => ({ isSearchable: !state.isSearchable })) + render() { + const { + isClearable, + isSearchable, + isDisabled, + isLoading, + isRtl, + } = this.state; + return ( + + ; + +interface State { + menuIsOpen: boolean; +} + +export default class controlledMenu extends React.Component { + state = { + menuIsOpen: false, + }; + toggleMenuIsOpen = () => + this.setState(state => ({ menuIsOpen: !state.menuIsOpen })) + render() { + const { menuIsOpen } = this.state; + return ( + + ; + +interface State { + ignoreCase: boolean; + ignoreAccents: boolean; + trim: boolean; + matchFromStart: boolean; +} + +export default class SelectCreateFilter extends React.Component { + state: State = { + ignoreCase: false, + ignoreAccents: false, + trim: false, + matchFromStart: false, + }; + toggleOption = (key: string) => () => { + this.setState((state: any) => ({ ...state, [key]: !state[key] })); + } + render() { + const { + ignoreCase, + ignoreAccents, + trim, + matchFromStart, + } = this.state; + + const filterConfig = { + ignoreCase, + ignoreAccents, + trim, + matchFrom: this.state.matchFromStart ? ('start' as 'start') : ('any' as 'any'), + }; + + return ( + + + ); +} diff --git a/types/react-select/test/examples/CustomControl.tsx b/types/react-select/test/examples/CustomControl.tsx new file mode 100644 index 0000000000..3ed018e05e --- /dev/null +++ b/types/react-select/test/examples/CustomControl.tsx @@ -0,0 +1,32 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; +const controlStyles = { + borderRadius: '1px solid black', + padding: '5px', + background: colourOptions[2].color, + color: 'white' +}; + +const ControlComponent = (props: any) => ( +
+ {

Custom Control

} + +
+); + +export default class CustomControl extends React.Component { + render() { + return ( + +); diff --git a/types/react-select/test/examples/CustomFilterOptions.tsx b/types/react-select/test/examples/CustomFilterOptions.tsx new file mode 100644 index 0000000000..62a13f2a89 --- /dev/null +++ b/types/react-select/test/examples/CustomFilterOptions.tsx @@ -0,0 +1,34 @@ +import * as React from 'react'; +import Select from 'react-select'; +import { colourOptions } from '../data'; + +interface State { + ignoreCase: boolean; + ignoreAccents: boolean; + trim: boolean; + matchFrom: boolean; +} + +const filterOptions = (candidate: any, input: string) => { + if (input) { + return candidate.value === customOptions[0].value; + } + return true; +}; + +const customOptions = [{ value: 'custom', label: 'Using a custom filter to always display this option on search' }, ...colourOptions]; + +export default class SelectCreateFilter extends React.Component { + render() { + return ( + +
+ ); + } +} diff --git a/types/react-select/test/examples/CustomGroup.tsx b/types/react-select/test/examples/CustomGroup.tsx new file mode 100644 index 0000000000..7085e2901c --- /dev/null +++ b/types/react-select/test/examples/CustomGroup.tsx @@ -0,0 +1,24 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; + +const groupStyles = { + border: `2px dotted ${colourOptions[2].color}`, + borderRadius: '5px', + background: '#f2fcff' +}; + +const Group = (props: any) => ( +
+ +
+); + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ Group }} + /> +); diff --git a/types/react-select/test/examples/CustomGroupHeading.tsx b/types/react-select/test/examples/CustomGroupHeading.tsx new file mode 100644 index 0000000000..abf09de9ef --- /dev/null +++ b/types/react-select/test/examples/CustomGroupHeading.tsx @@ -0,0 +1,31 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; +import { EditorPanelIcon, Tooltip } from '../AtlaskitDummy'; + +const groupStyles = { + border: `2px dotted ${colourOptions[2].color}`, + color: 'white', + background: colourOptions[2].color, + padding: '5px 0px', + display: 'flex', +}; + +const GroupHeading = (props: any) => ( +
+ + + + +
+); + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ GroupHeading }} + styles={{ groupHeading: (base: any) => ({ ...base, flex: '1 1', color: 'white', margin: 0 }) }} + /> +); diff --git a/types/react-select/test/examples/CustomIndicatorSeparator.tsx b/types/react-select/test/examples/CustomIndicatorSeparator.tsx new file mode 100644 index 0000000000..c63d4a0f0e --- /dev/null +++ b/types/react-select/test/examples/CustomIndicatorSeparator.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import Select from 'react-select'; +import { colourOptions } from '../data'; + +const indicatorSeparatorStyle = { + alignSelf: 'stretch', + backgroundColor: colourOptions[2].color, + marginBottom: 8, + marginTop: 8, + width: 1, +}; + +const IndicatorSeparator = ({ innerProps }: any) => { + return ( + + ); +}; + +export default () => ( + +); diff --git a/types/react-select/test/examples/CustomInput.tsx b/types/react-select/test/examples/CustomInput.tsx new file mode 100644 index 0000000000..e2bd0eb7d6 --- /dev/null +++ b/types/react-select/test/examples/CustomInput.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const Input = (props: any) => { + if (props.isHidden) { + return ; + } + return ( +
+ + + +
+ ); +}; + +export default () => ( + option.rating !== 'safe'} + /> +
+ ); + } +} diff --git a/types/react-select/test/examples/CustomLoadingIndicator.tsx b/types/react-select/test/examples/CustomLoadingIndicator.tsx new file mode 100644 index 0000000000..627599d52a --- /dev/null +++ b/types/react-select/test/examples/CustomLoadingIndicator.tsx @@ -0,0 +1,47 @@ +import * as React from 'react'; +import { Spinner, Tooltip } from '../AtlaskitDummy'; +import AsyncSelect from 'react-select/lib/Async'; +import { colourOptions } from '../data'; + +const LoadingIndicator = (props: any) => { + return ( + + + + ); +}; + +interface State { + inputValue: string; +} + +const filterColors = (inputValue: string) => + colourOptions.filter(i => + i.label.toLowerCase().includes(inputValue.toLowerCase()) + ); + +const promiseOptions = (inputValue: string) => + new Promise(resolve => { + setTimeout(() => { + resolve(filterColors(inputValue)); + }, 1000); + }); + +export default class CustomLoadingIndicator extends React.Component { + state = { inputValue: '' }; + handleInputChange = (newValue: string) => { + const inputValue = newValue.replace(/\W/g, ''); + this.setState({ inputValue }); + return inputValue; + } + render() { + return ( + + ); + } +} diff --git a/types/react-select/test/examples/CustomLoadingMessage.tsx b/types/react-select/test/examples/CustomLoadingMessage.tsx new file mode 100644 index 0000000000..04776ebfd6 --- /dev/null +++ b/types/react-select/test/examples/CustomLoadingMessage.tsx @@ -0,0 +1,50 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import AsyncSelect from 'react-select/lib/Async'; +import { colourOptions } from '../data'; + +const LoadingMessage = (props: any) => { + return ( + +
+ {props.children} +
+
+ ); +}; + +interface State { + inputValue: string; +} + +const filterColors = (inputValue: string) => + colourOptions.filter(i => + i.label.toLowerCase().includes(inputValue.toLowerCase()) + ); + +const promiseOptions = (inputValue: string) => + new Promise(resolve => { + setTimeout(() => { + resolve(filterColors(inputValue)); + }, 1000); + }); + +export default class CustomLoadingIndicator extends React.Component { + state = { inputValue: '' }; + handleInputChange = (newValue: string) => { + const inputValue = newValue.replace(/\W/g, ''); + this.setState({ inputValue }); + return inputValue; + } + render() { + return ( + ({ ...base, backgroundColor: colourOptions[2].color, color: 'white' }) }} + components={{ LoadingMessage }} + /> + ); + } +} diff --git a/types/react-select/test/examples/CustomMenu.tsx b/types/react-select/test/examples/CustomMenu.tsx new file mode 100644 index 0000000000..b774a7fa1e --- /dev/null +++ b/types/react-select/test/examples/CustomMenu.tsx @@ -0,0 +1,37 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; + +function getLength(options: any) { + return options.reduce((acc: any, curr: any) => { + if (curr.options) return acc + getLength(curr.options); + return acc + 1; + }, 0); +} + +const menuHeaderStyle = { + padding: '8px 12px', +}; + +const Menu = (props: any) => { + const optionsLength = getLength(props.options); + return ( + +
+ Custom Menu with {optionsLength} options +
+ + {props.children} + +
+ ); +}; + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ Menu }} + /> +); diff --git a/types/react-select/test/examples/CustomMenuList.tsx b/types/react-select/test/examples/CustomMenuList.tsx new file mode 100644 index 0000000000..48a3cf62f7 --- /dev/null +++ b/types/react-select/test/examples/CustomMenuList.tsx @@ -0,0 +1,29 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; + +const menuHeaderStyle = { + padding: '8px 12px', + background: colourOptions[2].color, + color: 'white', +}; + +const MenuList = (props: any) => { + return ( + +
+ Custom Menu List +
+ {props.children} +
+ ); +}; + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ MenuList }} + /> +); diff --git a/types/react-select/test/examples/CustomMultiValueContainer.tsx b/types/react-select/test/examples/CustomMultiValueContainer.tsx new file mode 100644 index 0000000000..1b556751e1 --- /dev/null +++ b/types/react-select/test/examples/CustomMultiValueContainer.tsx @@ -0,0 +1,23 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const MultiValueContainer = (props: any) => { + return ( + + + + ); +}; + +export default () => ( + ({ ...base, backgroundColor: colourOptions[2].color, color: 'white' }) }} + defaultValue={[colourOptions[4], colourOptions[5]]} + isMulti + options={colourOptions} + /> +); diff --git a/types/react-select/test/examples/CustomMultiValueRemove.tsx b/types/react-select/test/examples/CustomMultiValueRemove.tsx new file mode 100644 index 0000000000..81dfaf35e9 --- /dev/null +++ b/types/react-select/test/examples/CustomMultiValueRemove.tsx @@ -0,0 +1,25 @@ +import * as React from 'react'; +import { EmojiIcon, Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const MultiValueRemove = (props: any) => { + return ( + + + + + + ); +}; + +export default () => ( + ({ ...base, ...msgStyles }) }} + isSearchable + name="color" + options={[]} + /> + ); + } +} diff --git a/types/react-select/test/examples/CustomOption.tsx b/types/react-select/test/examples/CustomOption.tsx new file mode 100644 index 0000000000..aa115e78bf --- /dev/null +++ b/types/react-select/test/examples/CustomOption.tsx @@ -0,0 +1,22 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const Option = (props: any) => { + return ( + + + + ); +}; + +export default () => ( + ({ ...base, fontSize: '1em', color: colourOptions[2].color, fontWeight: 400 }) }} + options={colourOptions} + /> +); diff --git a/types/react-select/test/examples/CustomSelectContainer.tsx b/types/react-select/test/examples/CustomSelectContainer.tsx new file mode 100644 index 0000000000..393b8d1dd8 --- /dev/null +++ b/types/react-select/test/examples/CustomSelectContainer.tsx @@ -0,0 +1,24 @@ +import * as React from 'react'; +import Select, { components } from 'react-select'; +import { Tooltip } from '../AtlaskitDummy'; +import { colourOptions } from '../data'; + +const SelectContainer = ({ children, ...props }: any) => { + return ( + + + {children} + + + ); +}; + +export default () => ( + ({ ...base, padding: 5, borderRadius: 5, background: colourOptions[2].color, color: 'white', display: 'flex' }) }} + components={{ SingleValue }} + isSearchable + name="color" + options={colourOptions} + /> + ); + } +} diff --git a/types/react-select/test/examples/CustomValueContainer.tsx b/types/react-select/test/examples/CustomValueContainer.tsx new file mode 100644 index 0000000000..31d18ef50b --- /dev/null +++ b/types/react-select/test/examples/CustomValueContainer.tsx @@ -0,0 +1,28 @@ +import * as React from 'react'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const ValueContainer = ({ children, ...props }: any) => ( + + {children} + +); + +export default class CustomControl extends React.Component { + render() { + return ( + v.some(i => i.date.isSame(o.date, 'day'))} + maxMenuHeight={380} + onChange={this.props.onChange} + onInputChange={this.handleInputChange} + options={options} + value={value} + /> + ); + } +} + +export default class Experimental extends React.Component { + state = { + value: defaultOptions[0], + }; + handleChange = (value: any) => { + this.setState({ value }); + } + render() { + const { value } = this.state; + const displayValue = value && value.value ? value.value.toString() : 'null'; + return ( +
+
Value: {displayValue}
+ +
+ ); + } +} diff --git a/types/react-select/test/examples/MenuPortal.tsx b/types/react-select/test/examples/MenuPortal.tsx new file mode 100644 index 0000000000..32590acfb1 --- /dev/null +++ b/types/react-select/test/examples/MenuPortal.tsx @@ -0,0 +1,91 @@ +import * as React from 'react'; +import { Modal, Button } from '../AtlaskitDummy'; +import Select from 'react-select'; +import { H1, Note } from '../styled-components'; + +import { colourOptions } from '../data'; + +interface State { + isOpen: boolean; + isFixed: boolean; + portalPlacement: 'auto' | 'bottom' | 'top'; +} + +export default class MenuPortal extends React.Component { + state: State = { + isOpen: false, + isFixed: false, + portalPlacement: 'bottom', + }; + open = () => { + console.log('menuPortal is Open'); + this.setState({ isOpen: true }); + } + close = () => { this.setState({ isOpen: false }); }; + setPlacement = ({ currentTarget }: any) => { + const portalPlacement = currentTarget && currentTarget.value; + this.setState({ portalPlacement }); + } + toggleMode = () => { + this.setState(state => ({ isFixed: !state.isFixed })); + } + render() { + const { close, open } = this; + const { isOpen, isFixed, portalPlacement } = this.state; + return ( + + + { + isOpen ? + +

Portaled Menu Element

+ + + + + + + + + Fixed + + + + Portal + +
+ : null + } +
+ ); + } +} diff --git a/types/react-select/test/examples/OnSelectResetsInput.tsx b/types/react-select/test/examples/OnSelectResetsInput.tsx new file mode 100644 index 0000000000..af1327b1bb --- /dev/null +++ b/types/react-select/test/examples/OnSelectResetsInput.tsx @@ -0,0 +1,47 @@ +import * as React from 'react'; +import Select from 'react-select'; +import { colourOptions } from '../data'; +import { InputActionMeta } from 'react-select/lib/types'; + +export default class OnSelectResetsInput extends React.Component { + state = { + inputValue: '', + menuIsOpen: undefined + }; + onInputChange = (inputValue: string, { action }: InputActionMeta) => { + console.log(inputValue, action); + switch (action) { + case 'input-change': + this.setState({ inputValue }); + return; + case 'menu-close': + console.log(this.state.inputValue); + let menuIsOpen; + if (this.state.inputValue) { + menuIsOpen = true; + } + this.setState({ + menuIsOpen + }); + return; + default: + return; + } + } + render() { + const { inputValue, menuIsOpen } = this.state; + return ( + + + ); + } +} + +// styled components + +const Menu = (props: any) => { + const shadow = colors.neutral10a; + return ( +
+ ); +}; +const Blanket = (props: any) => ( +
+); +const Dropdown = ({ children, isOpen, target, onClose }: any) => ( +
// TODO css type + {target} + {isOpen ? {children} : null} + {isOpen ? : null} +
+); +const Svg = (p: any) => ( + +); +const DropdownIndicator = () => ( +
// TODO css type + + + +
+); +const ChevronDown = () => ( + + + +); diff --git a/types/react-select/test/examples/StyledMulti.tsx b/types/react-select/test/examples/StyledMulti.tsx new file mode 100644 index 0000000000..a4dedb4156 --- /dev/null +++ b/types/react-select/test/examples/StyledMulti.tsx @@ -0,0 +1,53 @@ +import * as React from 'react'; +import * as chroma from 'chroma-js'; + +import { colourOptions } from '../data'; +import Select from 'react-select'; + +const colourStyles = { + control: (styles: any) => ({ ...styles, backgroundColor: 'white' }), + option: (styles: any, { data, isDisabled, isFocused, isSelected }: any) => { + const color = chroma(data.color); + return { + ...styles, + backgroundColor: isDisabled + ? null + : isSelected ? data.color : isFocused ? color.alpha(0.1).css() : null, + color: isDisabled + ? '#ccc' + : isSelected + ? chroma.contrast(color, 'white') > 2 ? 'white' : 'black' + : data.color, + cursor: isDisabled ? 'not-allowed' : 'default', + }; + }, + multiValue: (styles: any, { data }: any) => { + const color = chroma(data.color); + return { + ...styles, + backgroundColor: color.alpha(0.1).css(), + }; + }, + multiValueLabel: (styles: any, { data }: any) => ({ + ...styles, + color: data.color, + }), + multiValueRemove: (styles: any, { data }: any) => ({ + ...styles, + color: data.color, + ':hover': { + backgroundColor: data.color, + color: 'white', + }, + }), +}; + +export default () => ( + +); diff --git a/types/react-select/test/styled-components.tsx b/types/react-select/test/styled-components.tsx new file mode 100644 index 0000000000..fa18465cd8 --- /dev/null +++ b/types/react-select/test/styled-components.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; + +export const Note = ({ Tag = 'div', ...props }: any) => ( + +); + +export const H1 = (props: any) =>

; +export const H2 = (props: any) =>

; diff --git a/types/react-select/tsconfig.json b/types/react-select/tsconfig.json index 7855eceaf1..8c7a1921bd 100644 --- a/types/react-select/tsconfig.json +++ b/types/react-select/tsconfig.json @@ -1,10 +1,4 @@ { - "files": [ - "index.d.ts", - "lib/Option/index.d.ts", - "lib/utils/defaultMenuRenderer/index.d.ts", - "react-select-tests.tsx" - ], "compilerOptions": { "module": "commonjs", "lib": [ @@ -12,16 +6,99 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "jsx": "react", "typeRoots": [ "../" ], + "jsx": "react", "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } + }, + "files": [ + "index.d.ts", + "lib/animated/Input.d.ts", + "lib/animated/MultiValue.d.ts", + "lib/animated/Placeholder.d.ts", + "lib/animated/SingleValue.d.ts", + "lib/animated/ValueContainer.d.ts", + "lib/animated/transitions.d.ts", + "lib/animated/index.d.ts", + "lib/components/containers.d.ts", + "lib/components/Control.d.ts", + "lib/components/Group.d.ts", + "lib/components/Input.d.ts", + "lib/components/Menu.d.ts", + "lib/components/MultiValue.d.ts", + "lib/components/Option.d.ts", + "lib/components/Placeholder.d.ts", + "lib/components/SingleValue.d.ts", + "lib/components/indicators.d.ts", + "lib/components/index.d.ts", + "lib/accessibility/index.d.ts", + "lib/theme.d.ts", + "lib/Creatable.d.ts", + "lib/Async.d.ts", + "lib/AsyncCreatable.d.ts", + "lib/filters.d.ts", + "lib/styles.d.ts", + "lib/stateManager.d.ts", + "lib/builtins.d.ts", + "lib/utils.d.ts", + "lib/diacritics.d.ts", + "lib/types.d.ts", + "lib/Select.d.ts", + "test/data.ts", + "test/styled-components.tsx", + "test/AtlaskitDummy.ts", + "test/ChronoNodeDummy.ts", + "test/examples/AccessingInternals.tsx", + "test/examples/AnimatedMulti.tsx", + "test/examples/AsyncCallbacks.tsx", + "test/examples/AsyncCreatable.tsx", + "test/examples/AsyncMulti.tsx", + "test/examples/AsyncPromises.tsx", + "test/examples/BasicGrouped.tsx", + "test/examples/BasicMulti.tsx", + "test/examples/BasicSingle.tsx", + "test/examples/ControlledMenu.tsx", + "test/examples/CreatableAdvanced.tsx", + "test/examples/CreatableInputOnly.tsx", + "test/examples/CreatableMulti.tsx", + "test/examples/CreatableSingle.tsx", + "test/examples/CreateFilter.tsx", + "test/examples/CustomClearIndicator.tsx", + "test/examples/CustomControl.tsx", + "test/examples/CustomDropdownIndicator.tsx", + "test/examples/CustomFilterOptions.tsx", + "test/examples/CustomGetOptionLabel.tsx", + "test/examples/CustomGroup.tsx", + "test/examples/CustomGroupHeading.tsx", + "test/examples/CustomIndicatorsContainer.tsx", + "test/examples/CustomIndicatorSeparator.tsx", + "test/examples/CustomInput.tsx", + "test/examples/CustomIsOptionDisabled.tsx", + "test/examples/CustomLoadingIndicator.tsx", + "test/examples/CustomLoadingMessage.tsx", + "test/examples/CustomMenu.tsx", + "test/examples/CustomMenuList.tsx", + "test/examples/CustomMultiValueContainer.tsx", + "test/examples/CustomMultiValueLabel.tsx", + "test/examples/CustomMultiValueRemove.tsx", + "test/examples/CustomNoOptionsMessage.tsx", + "test/examples/CustomOption.tsx", + "test/examples/CustomPlaceholder.tsx", + "test/examples/CustomSelectContainer.tsx", + "test/examples/CustomSingleValue.tsx", + "test/examples/CustomValueContainer.tsx", + "test/examples/Experimental.tsx", + "test/examples/MenuPortal.tsx", + "test/examples/OnSelectResetsInput.tsx", + "test/examples/Popout.tsx", + "test/examples/StyledMulti.tsx", + "test/examples/StyledSingle.tsx" + ] } diff --git a/types/react-select/tslint.json b/types/react-select/tslint.json index 3db14f85ea..f93cf8562a 100644 --- a/types/react-select/tslint.json +++ b/types/react-select/tslint.json @@ -1 +1,3 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-select/v1/index.d.ts b/types/react-select/v1/index.d.ts new file mode 100644 index 0000000000..31ff0db561 --- /dev/null +++ b/types/react-select/v1/index.d.ts @@ -0,0 +1,654 @@ +// Type definitions for react-select 1.3 +// Project: https://github.com/JedWatson/react-select +// Definitions by: ESQUIBET Hugo +// Gilad Gray +// Izaak Baker +// Tadas Dailyda +// Mark Vujevits +// Mike Deverell +// MartynasZilinskas +// Onat Yigit Mercan +// Ian Johnson +// Anton Novik +// David Schkalee +// Arthur Udalov +// Sebastian Silbermann +// Endurance Idehen +// Guillaume Chartier +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; + +export default class ReactSelectClass extends React.Component> { + focus(): void; + setValue(value: Option): void; +} +// Other components +export class Creatable extends React.Component> { } +export class Async extends React.Component> { } +export class AsyncCreatable extends React.Component> { } + +export type OptionComponentType = React.ComponentType>; +export type ValueComponentType = React.ComponentType>; + +export type HandlerRendererResult = JSX.Element | null | false; + +// Handlers +export type FocusOptionHandler = (option: Option) => void; +export type SelectValueHandler = (option: Option) => void; +export type ArrowRendererHandler = (props: ArrowRendererProps) => HandlerRendererResult; +export type ClearRendererHandler = () => HandlerRendererResult; +export type FilterOptionHandler = (option: Option, filter: string) => boolean; +export type FilterOptionsHandler = (options: Options, filter: string, currentValues: Options) => Options; +export type InputRendererHandler = (props: { [key: string]: any }) => HandlerRendererResult; +export type MenuRendererHandler = (props: MenuRendererProps) => HandlerRendererResult; +export type OnCloseHandler = () => void; +export type OnInputChangeHandler = (inputValue: string) => string; +export type OnInputKeyDownHandler = React.KeyboardEventHandler; +export type OnMenuScrollToBottomHandler = () => void; +export type OnOpenHandler = () => void; +export type OnFocusHandler = React.FocusEventHandler; +export type OnBlurHandler = React.FocusEventHandler; +export type OptionRendererHandler = (option: Option) => HandlerRendererResult; +export type ValueRendererHandler = (option: Option, index?: number) => HandlerRendererResult; +export type OnValueClickHandler = (option: Option, event: React.MouseEvent) => void; +export type IsOptionUniqueHandler = (arg: { option: Option, options: Options, labelKey: string, valueKey: string }) => boolean; +export type IsValidNewOptionHandler = (arg: { label: string }) => boolean; +export type NewOptionCreatorHandler = (arg: { label: string, labelKey: string, valueKey: string }) => Option; +export type PromptTextCreatorHandler = (filterText: string) => string; +export type ShouldKeyDownEventCreateNewOptionHandler = (arg: { keyCode: number }) => boolean; + +export type OnChangeSingleHandler = OnChangeHandler>; +export type OnChangeMultipleHandler = OnChangeHandler>; +export type OnChangeHandler | Options> = (newValue: TOption | null) => void; +export type OnNewOptionClickHandler = (option: Option) => void; + +export type LoadOptionsHandler = LoadOptionsAsyncHandler | LoadOptionsLegacyHandler; +export type LoadOptionsAsyncHandler = (input: string) => Promise>; +export type LoadOptionsLegacyHandler = (input: string, callback: (err: any, result: AutocompleteResult) => void) => void; + +export interface AutocompleteResult { + /** The search-results to be displayed */ + options: Options; + /** + * Should be set to true, if and only if a longer query with the same prefix + * would return a subset of the results + * If set to true, more specific queries will not be sent to the server. + */ + complete: boolean; +} + +export type Options = Array>; + +export interface Option { + /** Text for rendering */ + label?: string; + /** Value for searching */ + value?: TValue; + /** + * Allow this option to be cleared + * @default true + */ + clearableValue?: boolean; + /** + * Do not allow this option to be selected + * @default false + */ + disabled?: boolean; + /** + * In the event that a custom menuRenderer is provided, Option should be able + * to accept arbitrary key-value pairs. See react-virtualized-select. + */ + [property: string]: any; +} + +export type OptionValues = string | number | boolean; + +export interface MenuRendererProps { + /** + * The currently focused option; should be visible in the menu by default. + * default {} + */ + focusedOption: Option; + + /** + * Callback to focus a new option; receives the option as a parameter. + */ + focusOption: FocusOptionHandler; + + /** + * Option labels are accessible with this string key. + */ + labelKey: string; + + /** + * Ordered array of options to render. + */ + options: Options; + + /** + * Callback to select a new option; receives the option as a parameter. + */ + selectValue: SelectValueHandler; + + /** + * Array of currently selected options. + */ + valueArray: Options; + + /** + * Callback to remove selection from option; receives the option as a parameter. + */ + removeValue: SelectValueHandler; + + /** + * function which returns a custom way to render the options in the menu + */ + optionRenderer: OptionRendererHandler; +} + +export interface OptionComponentProps { + /** + * Classname(s) to apply to the option component. + */ + className?: string; + + /** + * Currently focused option. + */ + focusOption?: Option; + + inputValue?: string; + instancePrefix?: string; + + /** + * True if this option is disabled. + */ + isDisabled?: boolean; + + /** + * True if this option is focused. + */ + isFocused?: boolean; + + /** + * True if this option is selected. + */ + isSelected?: boolean; + + /** + * Callback to be invoked when this option is focused. + */ + onFocus?: (option: Option, event: any) => void; + + /** + * Callback to be invoked when this option is selected. + */ + onSelect?: (option: Option, event: any) => void; + + /** + * Option to be rendered by this component. + */ + option: Option; + + /** + * Index of the option being rendered in the list + */ + optionIndex?: number; + + /** + * Callback to invoke when removing an option from a multi-selection. (Not necessarily the one + * being rendered) + */ + removeValue?: (value: TValue | TValue[]) => void; + + /** + * Callback to invoke to select an option. (Not necessarily the one being rendered) + */ + selectValue?: (value: TValue | TValue[]) => void; +} + +export interface ArrowRendererProps { + /** + * Arrow mouse down event handler. + */ + onMouseDown: React.MouseEventHandler; + + /** + * whether the Select is open or not. + */ + isOpen: boolean; +} + +export interface ValueComponentProps { + disabled: ReactSelectProps['disabled']; + id: string; + instancePrefix: string; + onClick: OnValueClickHandler | null; + onRemove?: SelectValueHandler; + placeholder: ReactSelectProps['placeholder']; + value: Option; + values?: Array>; +} + +export interface ReactSelectProps extends React.Props> { + /** + * text to display when `allowCreate` is true. + * @default 'Add "{label}"?' + */ + addLabelText?: string; + /** + * renders a custom drop-down arrow to be shown in the right-hand side of the select. + * @default undefined + */ + arrowRenderer?: ArrowRendererHandler | null; + /** + * blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices. + * @default false + */ + autoBlur?: boolean; + /** + * autofocus the component on mount + * @deprecated. Use autoFocus instead + * @default false + */ + autofocus?: boolean; + /** + * autofocus the component on mount + * @default false + */ + autoFocus?: boolean; + /** + * If enabled, the input will expand as the length of its value increases + */ + autosize?: boolean; + /** + * whether pressing backspace removes the last item when there is no input value + * @default true + */ + backspaceRemoves?: boolean; + /** + * Message to use for screenreaders to press backspace to remove the current item + * {label} is replaced with the item label + * @default "Press backspace to remove..." + */ + backspaceToRemoveMessage?: string; + /** + * CSS className for the outer element + */ + className?: string; + /** + * Prefix prepended to element default className if no className is defined + */ + classNamePrefix?: string; + /** + * title for the "clear" control when `multi` is true + * @default "Clear all" + */ + clearAllText?: string; + /** + * Renders a custom clear to be shown in the right-hand side of the select when clearable true + * @default undefined + */ + clearRenderer?: ClearRendererHandler; + /** + * title for the "clear" control + * @default "Clear value" + */ + clearValueText?: string; + /** + * whether to close the menu when a value is selected + * @default true + */ + closeOnSelect?: boolean; + /** + * whether it is possible to reset value. if enabled, an X button will appear at the right side. + * @default true + */ + clearable?: boolean; + /** + * whether backspace removes an item if there is no text input + * @default true + */ + deleteRemoves?: boolean; + /** + * delimiter to use to join multiple values + * @default "," + */ + delimiter?: string; + /** + * whether the Select is disabled or not + * @default false + */ + disabled?: boolean; + /** + * whether escape clears the value when the menu is closed + * @default true + */ + escapeClearsValue?: boolean; + /** + * method to filter a single option + */ + filterOption?: FilterOptionHandler; + /** + * method to filter the options array + */ + filterOptions?: FilterOptionsHandler; + /** + * id for the underlying HTML input element + * @default undefined + */ + id?: string; + /** + * whether to strip diacritics when filtering + * @default true + */ + ignoreAccents?: boolean; + /** + * whether to perform case-insensitive filtering + * @default true + */ + ignoreCase?: boolean; + /** + * custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'} + * @default {} + */ + inputProps?: { [key: string]: any }; + /** + * renders a custom input + */ + inputRenderer?: InputRendererHandler; + /** + * allows for synchronization of component id's on server and client. + * @see https://github.com/JedWatson/react-select/pull/1105 + */ + instanceId?: string; + /** + * whether the Select is loading externally or not (such as options being loaded). + * if true, a loading spinner will be shown at the right side. + * @default false + */ + isLoading?: boolean; + /** + * (legacy mode) joins multiple values into a single form field with the delimiter + * @default false + */ + joinValues?: boolean; + /** + * the option property to use for the label + * @default "label" + */ + labelKey?: string; + /** + * (any, start) match the start or entire string when filtering + * @default "any" + */ + matchPos?: string; + /** + * (any, label, value) which option property to filter on + * @default "any" + */ + matchProp?: string; + /** + * buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport + * @default 0 + */ + menuBuffer?: number; + /** + * optional style to apply to the menu container + */ + menuContainerStyle?: React.CSSProperties; + /** + * renders a custom menu with options + */ + menuRenderer?: MenuRendererHandler; + /** + * optional style to apply to the menu + */ + menuStyle?: React.CSSProperties; + /** + * multi-value input + * @default false + */ + multi?: boolean; + /** + * field name, for hidden `` tag + */ + name?: string; + /** + * placeholder displayed when there are no matching search results or a falsy value to hide it + * @default "No results found" + */ + noResultsText?: string | JSX.Element; + /** + * onBlur handler: function (event) {} + */ + onBlur?: OnBlurHandler; + /** + * whether to clear input on blur or not + * @default true + */ + onBlurResetsInput?: boolean; + /** + * whether the input value should be reset when options are selected. + * Also input value will be set to empty if 'onSelectResetsInput=true' and + * Select will get new value that not equal previous value. + * @default true + */ + onSelectResetsInput?: boolean; + /** + * whether to clear input when closing the menu through the arrow + * @default true + */ + onCloseResetsInput?: boolean; + /** + * onChange handler: function (newValue) {} + */ + onChange?: OnChangeHandler; + /** + * fires when the menu is closed + */ + onClose?: OnCloseHandler; + /** + * onFocus handler: function (event) {} + */ + onFocus?: OnFocusHandler; + /** + * onInputChange handler: function (inputValue) {} + */ + onInputChange?: OnInputChangeHandler; + /** + * onInputKeyDown handler: function (keyboardEvent) {} + */ + onInputKeyDown?: OnInputKeyDownHandler; + /** + * fires when the menu is scrolled to the bottom; can be used to paginate options + */ + onMenuScrollToBottom?: OnMenuScrollToBottomHandler; + /** + * fires when the menu is opened + */ + onOpen?: OnOpenHandler; + /** + * boolean to enable opening dropdown when focused + * @default false + */ + openOnClick?: boolean; + /** + * open the options menu when the input gets focus (requires searchable = true) + * @default true + */ + openOnFocus?: boolean; + /** + * className to add to each option component + */ + optionClassName?: string; + /** + * option component to render in dropdown + */ + optionComponent?: OptionComponentType; + /** + * function which returns a custom way to render the options in the menu + */ + optionRenderer?: OptionRendererHandler; + /** + * array of Select options + * @default false + */ + options?: Options; + /** + * number of options to jump when using page up/down keys + * @default 5 + */ + pageSize?: number; + /** + * field placeholder, displayed when there's no value + * @default "Select..." + */ + placeholder?: string | JSX.Element; + /** + * whether the selected option is removed from the dropdown on multi selects + * @default true + */ + removeSelected?: boolean; + /** + * applies HTML5 required attribute when needed + * @default false + */ + required?: boolean; + /** + * value to use when you clear the control + */ + resetValue?: any; + /** + * use react-select in right-to-left direction + * @default false + */ + rtl?: boolean; + /** + * whether the viewport will shift to display the entire menu when engaged + * @default true + */ + scrollMenuIntoView?: boolean; + /** + * whether to enable searching feature or not + * @default true; + */ + searchable?: boolean; + /** + * whether to select the currently focused value when the [tab] key is pressed + */ + tabSelectsValue?: boolean; + /** + * initial field value + */ + value?: Option | Options | string | string[] | number | number[] | boolean; + /** + * the option property to use for the value + * @default "value" + */ + valueKey?: string; + /** + * function which returns a custom way to render the value selected + * @default false + */ + valueRenderer?: ValueRendererHandler; + /** + * optional style to apply to the control + */ + style?: React.CSSProperties; + + /** + * optional tab index of the control + */ + tabIndex?: string | number; + + /** + * value component to render + */ + valueComponent?: ValueComponentType; + + /** + * optional style to apply to the component wrapper + */ + wrapperStyle?: React.CSSProperties; + + /** + * onClick handler for value labels: function (value, event) {} + */ + onValueClick?: OnValueClickHandler; + + /** + * pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false + */ + simpleValue?: boolean; +} + +export interface ReactCreatableSelectProps extends ReactSelectProps { + /** + * Searches for any matching option within the set of options. This function prevents + * duplicate options from being created. + */ + isOptionUnique?: IsOptionUniqueHandler; + + /** + * Determines if the current input text represents a valid option. + */ + isValidNewOption?: IsValidNewOptionHandler; + + /** + * factory to create new options + */ + newOptionCreator?: NewOptionCreatorHandler; + + /** + * Creates prompt/placeholder for option text. + */ + promptTextCreator?: PromptTextCreatorHandler; + + /** + * Decides if a keyDown event (eg its 'keyCode') should result in the creation of a new option. + */ + shouldKeyDownEventCreateNewOption?: ShouldKeyDownEventCreateNewOptionHandler; + + /** + * new option click handler: function (option) {} + */ + onNewOptionClick?: OnNewOptionClickHandler; + + /** + * true: Show new option at top of list + * false: Show new option at bottom of list + * @default true + */ + showNewOptionAtTop?: boolean; +} + +export interface ReactAsyncSelectProps extends ReactSelectProps { + /** + * Whether to auto-load the default async options set. + */ + autoload?: boolean; + + /** + * object to use to cache results; can be null to disable cache + */ + cache?: { [key: string]: any } | boolean; + + /** + * function to call to load options asynchronously + */ + loadOptions: LoadOptionsHandler; + + /** + * replaces the placeholder while options are loading + */ + loadingPlaceholder?: string | JSX.Element; + /** + * displayed in the drop down list when the user did not type anything yet + */ + searchPromptText?: string; +} + +export type ReactAsyncCreatableSelectProps = ReactAsyncSelectProps & ReactCreatableSelectProps; diff --git a/types/react-select/lib/Option/index.d.ts b/types/react-select/v1/lib/Option/index.d.ts similarity index 100% rename from types/react-select/lib/Option/index.d.ts rename to types/react-select/v1/lib/Option/index.d.ts diff --git a/types/react-select/lib/utils/defaultMenuRenderer/index.d.ts b/types/react-select/v1/lib/utils/defaultMenuRenderer/index.d.ts similarity index 100% rename from types/react-select/lib/utils/defaultMenuRenderer/index.d.ts rename to types/react-select/v1/lib/utils/defaultMenuRenderer/index.d.ts diff --git a/types/react-select/react-select-tests.tsx b/types/react-select/v1/react-select-tests.tsx similarity index 100% rename from types/react-select/react-select-tests.tsx rename to types/react-select/v1/react-select-tests.tsx diff --git a/types/react-select/v1/tsconfig.json b/types/react-select/v1/tsconfig.json new file mode 100644 index 0000000000..e01d55ae8a --- /dev/null +++ b/types/react-select/v1/tsconfig.json @@ -0,0 +1,35 @@ +{ + "files": [ + "index.d.ts", + "lib/Option/index.d.ts", + "lib/utils/defaultMenuRenderer/index.d.ts", + "react-select-tests.tsx" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "jsx": "react", + "typeRoots": [ + "../../" + ], + "paths": { + "react-select": [ + "react-select/v1" + ], + "react-select/*": [ + "react-select/v1/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/react-select/v1/tslint.json b/types/react-select/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-select/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-toggle/v2/index.d.ts b/types/react-toggle/v2/index.d.ts index 2b0774de2d..e2d2d5f0b2 100644 --- a/types/react-toggle/v2/index.d.ts +++ b/types/react-toggle/v2/index.d.ts @@ -1,20 +1,24 @@ // Type definitions for react-toggle 2.2 // Project: https://github.com/aaronshaf/react-toggle // Definitions by: Karol Janyst +// Jason Unger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.7 -import { Component, HTMLAttributes, ReactNode } from "react"; +import { ComponentClass, InputHTMLAttributes, ReactNode } from "react"; -export interface ToggleIcons { - checked?: ReactNode; - unchecked?: ReactNode; +declare namespace Toggle { + interface ToggleIcons { + checked?: ReactNode; + unchecked?: ReactNode; + } + + interface ToggleProps extends InputHTMLAttributes { + icons?: boolean | ToggleIcons; + defaultChecked?: boolean; + } } -export interface ToggleProps extends HTMLAttributes { - "aria-labelledby"?: string; - "aria-label"?: string; - icons?: boolean | ToggleIcons; -} +declare const Toggle: ComponentClass; -export default class Toggle extends Component {} +export = Toggle; diff --git a/types/react-toggle/v2/react-toggle-tests.tsx b/types/react-toggle/v2/react-toggle-tests.tsx index f02cf447e4..ac86a3ea7e 100644 --- a/types/react-toggle/v2/react-toggle-tests.tsx +++ b/types/react-toggle/v2/react-toggle-tests.tsx @@ -8,3 +8,15 @@ class Test extends React.Component { ); } } + +class TestControlled extends React.Component<{}, {checked: boolean}> { + state = { + checked: false + }; + + render() { + return ( + this.setState({ checked: e.target.checked })} /> + ); + } +} diff --git a/types/react-toggle/v2/tsconfig.json b/types/react-toggle/v2/tsconfig.json index 996290fe7b..122fd7a4b3 100644 --- a/types/react-toggle/v2/tsconfig.json +++ b/types/react-toggle/v2/tsconfig.json @@ -21,10 +21,11 @@ }, "noEmit": true, "forceConsistentCasingInFileNames": true, - "jsx": "react" + "jsx": "react", + "esModuleInterop": true }, "files": [ "index.d.ts", "react-toggle-tests.tsx" ] -} \ No newline at end of file +} diff --git a/types/react-transition-group/Transition.d.ts b/types/react-transition-group/Transition.d.ts index 66ab782d1e..123f8b1622 100644 --- a/types/react-transition-group/Transition.d.ts +++ b/types/react-transition-group/Transition.d.ts @@ -16,6 +16,7 @@ export interface TransitionActions { exit?: boolean; } +export type TransitionChildren = React.ReactNode | ((status: string) => React.ReactNode); export interface TransitionProps extends TransitionActions { in?: boolean; mountOnEnter?: boolean; @@ -29,6 +30,7 @@ export interface TransitionProps extends TransitionActions { onExiting?: ExitHandler; onExited?: ExitHandler; [prop: string]: any; + children?: TransitionChildren; } /** diff --git a/types/react-transition-group/react-transition-group-tests.tsx b/types/react-transition-group/react-transition-group-tests.tsx index 1441027481..ce096f3dc7 100644 --- a/types/react-transition-group/react-transition-group-tests.tsx +++ b/types/react-transition-group/react-transition-group-tests.tsx @@ -51,6 +51,9 @@ const Test: React.StatelessComponent = () => { >
{ "test" }
+ + {(status) =>
{status}
} +
// Jamie Saunders // Paul Melnikow +// Harry Cruse // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -25,7 +26,7 @@ export type TooltipFormatter = (value: string | number | Array, entry: TooltipPayload, index: number) => React.ReactNode; export type ItemSorter = (a: T, b: T) => number; export type ContentRenderer

= (props: P) => React.ReactNode; -export type DataKey = string | number | ((dataObject: any) => number | [number, number]); +export type DataKey = string | number | ((dataObject: any) => number | [number, number] | null); export type IconType = 'plainline' | 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'plainline'; export type LegendType = IconType | 'none'; @@ -406,6 +407,7 @@ export interface LineProps extends EventAttributes, Partial | ContentRenderer; points?: Point[]; @@ -518,7 +520,7 @@ export interface PolarRadiusAxisProps extends EventAttributes, Partial | ContentRenderer; stroke?: string; tickFormatter: TickFormatterFunction; - domain?: PolarRadiusAxisDomain[]; + domain?: [PolarRadiusAxisDomain, PolarRadiusAxisDomain]; scale?: ScaleType | RechartsFunction; allowDataOverflow?: boolean; } @@ -882,7 +884,7 @@ export interface XAxisProps extends EventAttributes { unit?: string | number; // The unique id of x-axis xAxisId?: string | number; - domain?: AxisDomain[]; + domain?: [AxisDomain, AxisDomain]; // The key of data displayed in the axis dataKey?: DataKey; // The width of axis which is usually calculated internally @@ -914,6 +916,7 @@ export interface XAxisProps extends EventAttributes { reversed?: boolean; // see label section at http://recharts.org/#/en-US/api/XAxis label?: string | number | Label | LabelProps; + allowDuplicatedCategory?: boolean; } export class XAxis extends React.Component { } @@ -933,7 +936,7 @@ export interface YAxisProps extends EventAttributes { unit?: string | number; // The unique id of y-axis yAxisId?: string | number; - domain?: AxisDomain[]; + domain?: [AxisDomain, AxisDomain]; // The key of data displayed in the axis dataKey?: DataKey; // Ticks can be any type when the axis is the type of category diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index 0c893486c3..e202e85d44 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -661,39 +661,24 @@ declare module 'recompose/hoistStatics' { // https://github.com/acdlite/recompose/blob/master/docs/API.md#componentfromstream declare module 'recompose/componentFromStream' { import { componentFromStream } from 'recompose'; + export { componentFromStreamWithConfig } from 'recompose'; export default componentFromStream; } -// https://github.com/acdlite/recompose/blob/master/docs/API.md#componentfromstreamwithconfig -declare module 'recompose/componentFromStreamWithConfig' { - import { componentFromStreamWithConfig } from 'recompose'; - export default componentFromStreamWithConfig; -} - // https://github.com/acdlite/recompose/blob/master/docs/API.md#mappropsstream declare module 'recompose/mapPropsStream' { import { mapPropsStream } from 'recompose'; + export { mapPropsStreamWithConfig } from 'recompose'; export default mapPropsStream; } -// https://github.com/acdlite/recompose/blob/master/docs/API.md#mappropsstreamwithconfig -declare module 'recompose/mapPropsStreamWithConfig' { - import { mapPropsStreamWithConfig } from 'recompose'; - export default mapPropsStreamWithConfig; -} - // https://github.com/acdlite/recompose/blob/master/docs/API.md#createeventhandler declare module 'recompose/createEventHandler' { import { createEventHandler } from 'recompose'; + export { createEventHandlerWithConfig } from 'recompose'; export default createEventHandler; } -// https://github.com/acdlite/recompose/blob/master/docs/API.md#createeventhandlerwithconfig -declare module 'recompose/createEventHandlerWithConfig' { - import { createEventHandlerWithConfig } from 'recompose'; - export default createEventHandlerWithConfig; -} - // https://github.com/acdlite/recompose/blob/master/docs/API.md#setobservableconfig declare module 'recompose/setObservableConfig' { import { setObservableConfig } from 'recompose'; diff --git a/types/recompose/recompose-tests.tsx b/types/recompose/recompose-tests.tsx index c30f5fb8f9..b89bd5e2c9 100644 --- a/types/recompose/recompose-tests.tsx +++ b/types/recompose/recompose-tests.tsx @@ -62,12 +62,9 @@ import createSinkStandalone from "recompose/createSink"; import componentFromPropStandalone from "recompose/componentFromProp"; import nestStandalone from "recompose/nest"; import hoistStaticsStandalone from "recompose/hoistStatics"; -import componentFromStreamStandalone from "recompose/componentFromStream"; -import componentFromStreamWithConfigStandalone from "recompose/componentFromStreamWithConfig"; -import mapPropsStreamStandalone from "recompose/mapPropsStream"; -import mapPropsStreamWithConfigStandalone from "recompose/mapPropsStreamWithConfig"; -import createEventHandlerStandalone from "recompose/createEventHandler"; -import createEventHandlerWithConfigStandalone from "recompose/createEventHandlerWithConfig"; +import componentFromStreamStandalone, { componentFromStreamWithConfig as componentFromStreamWithConfigStandalone } from "recompose/componentFromStream"; +import mapPropsStreamStandalone, { mapPropsStreamWithConfig as mapPropsStreamWithConfigStandalone } from "recompose/mapPropsStream"; +import createEventHandlerStandalone, { createEventHandlerWithConfig as createEventHandlerWithConfigStandalone } from "recompose/createEventHandler"; import setObservableConfigStandalone from "recompose/setObservableConfig"; function testMapProps() { diff --git a/types/redom/redom-tests.ts b/types/redom/redom-tests.ts index 0ec18f6a59..83eb899c65 100644 --- a/types/redom/redom-tests.ts +++ b/types/redom/redom-tests.ts @@ -4,13 +4,13 @@ const el1: HTMLElement = redom.el(''); const el2: HTMLElement = redom.el('p', 'Hello, World!', (el: HTMLElement) => { el.setAttribute('ok', '!'); }); const el3: HTMLElement = redom.html('p', 2, { color: 'red' }); -redom.mount(document.body, el1); -redom.mount(document.body, el2, el1); -redom.unmount(document.body, el1); +redom.mount(document.body!, el1); +redom.mount(document.body!, el2, el1); +redom.unmount(document.body!, el1); redom.setAttr(el3, 'ok', '!'); redom.setAttr(el3, { ok: '!' }); redom.setStyle(el3, { color: 'blue' }); redom.setChildren(el1, [el2, el3]); -redom.mount(document.body, redom.text('Hello, World!')); +redom.mount(document.body!, redom.text('Hello, World!')); diff --git a/types/redux-form/lib/Field.d.ts b/types/redux-form/lib/Field.d.ts index d27a10ce47..c303f0d5c3 100644 --- a/types/redux-form/lib/Field.d.ts +++ b/types/redux-form/lib/Field.d.ts @@ -37,7 +37,6 @@ export interface CommonFieldProps extends CommonFieldInputProps { export interface BaseFieldProps

extends Partial { name: string; - label?: string; component?: ComponentType | "input" | "select" | "textarea"; format?: Formatter | null; normalize?: Normalizer; @@ -73,7 +72,6 @@ export class Field

extends Comp export interface WrappedFieldProps { input: WrappedFieldInputProps; meta: WrappedFieldMetaProps; - label?: string; } export interface WrappedFieldInputProps extends CommonFieldInputProps { diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index 06344b54c5..ea13a9618f 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -110,7 +110,6 @@ interface MyFieldCustomProps { type MyFieldProps = MyFieldCustomProps & WrappedFieldProps; const MyField: React.StatelessComponent = ({ children, - label, input, meta, foo diff --git a/types/req-cwd/index.d.ts b/types/req-cwd/index.d.ts new file mode 100644 index 0000000000..56ca4f0786 --- /dev/null +++ b/types/req-cwd/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for req-cwd 2.0 +// Project: https://github.com/sindresorhus/req-cwd +// Definitions by: Arturas Molcanovas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/** Like require(), throws when the module can't be found. */ +declare function reqCwd(moduleId: string): any; + +declare namespace reqCwd { + /** Returns null instead of throwing when the module can't be found. */ + function silent(moduleId: string): any; +} + +export = reqCwd; diff --git a/types/req-cwd/req-cwd-tests.ts b/types/req-cwd/req-cwd-tests.ts new file mode 100644 index 0000000000..df95f8161f --- /dev/null +++ b/types/req-cwd/req-cwd-tests.ts @@ -0,0 +1,9 @@ +import * as reqCwd from 'req-cwd'; + +const r1: string = reqCwd('./foo'); +const r2: number = reqCwd('./foo'); +const r3: {foo: string} = reqCwd('./foo'); + +const s1: string | null = reqCwd.silent('./foo'); +const s2: number | null = reqCwd.silent('./foo'); +const s3: {foo: string} | null = reqCwd.silent('./foo'); diff --git a/types/req-cwd/tsconfig.json b/types/req-cwd/tsconfig.json new file mode 100644 index 0000000000..648ca4cf75 --- /dev/null +++ b/types/req-cwd/tsconfig.json @@ -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", + "req-cwd-tests.ts" + ] +} diff --git a/types/req-cwd/tslint.json b/types/req-cwd/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/req-cwd/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sane-email-validation/index.d.ts b/types/sane-email-validation/index.d.ts new file mode 100644 index 0000000000..92e285c1ca --- /dev/null +++ b/types/sane-email-validation/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for sane-email-validation 1.1 +// Project: https://github.com/scottgonzalez/sane-email-validation +// Definitions by: Forbes Lindesay +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function isEmail(email: string): boolean; + +declare namespace isEmail { + function isNotEmail(email: string): boolean; +} + +export = isEmail; diff --git a/types/sane-email-validation/sane-email-validation-tests.ts b/types/sane-email-validation/sane-email-validation-tests.ts new file mode 100644 index 0000000000..7b8ad88603 --- /dev/null +++ b/types/sane-email-validation/sane-email-validation-tests.ts @@ -0,0 +1,9 @@ +import isEmail = require('sane-email-validation'); + +const is: boolean = isEmail('foo@bar.com'); +const isNot: boolean = isEmail.isNotEmail('foo@bar.com'); + +// $ExpectError +isEmail(10); +// $ExpectError +isEmail.isNotEmail(10); diff --git a/types/sane-email-validation/tsconfig.json b/types/sane-email-validation/tsconfig.json new file mode 100644 index 0000000000..3b9b568d67 --- /dev/null +++ b/types/sane-email-validation/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "sane-email-validation-tests.ts" + ] +} diff --git a/types/sane-email-validation/tslint.json b/types/sane-email-validation/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sane-email-validation/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sanitize-html/index.d.ts b/types/sanitize-html/index.d.ts index bdd70f956a..2e7527e3fc 100644 --- a/types/sanitize-html/index.d.ts +++ b/types/sanitize-html/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for sanitize-html 1.14.1 +// Type definitions for sanitize-html 1.18.2 // Project: https://github.com/punkave/sanitize-html // Definitions by: Rogier Schouten // Afshin Darian // BehindTheMath +// Rinze de Laat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = sanitize; @@ -38,9 +39,12 @@ declare namespace sanitize { interface IOptions { allowedAttributes?: { [index: string]: string[] } | boolean; + allowedStyles?: { [index: string]: { [index: string]: RegExp[] } }; allowedClasses?: { [index: string]: string[] } | boolean; + allowedIframeHostnames?: string[]; allowedSchemes?: string[] | boolean; allowedSchemesByTag?: { [index: string]: string[] } | boolean; + allowedSchemesAppliedToAttributes?: string[]; allowProtocolRelative?: boolean; allowedTags?: string[] | boolean; exclusiveFilter?: (frame: IFrame) => boolean; diff --git a/types/sanitize-html/sanitize-html-tests.ts b/types/sanitize-html/sanitize-html-tests.ts index cc43d64fcb..b02a5a6653 100644 --- a/types/sanitize-html/sanitize-html-tests.ts +++ b/types/sanitize-html/sanitize-html-tests.ts @@ -4,8 +4,17 @@ let options: sanitize.IOptions = { allowedTags: sanitize.defaults.allowedTags.concat('h1', 'h2', 'img'), allowedAttributes: { 'a': sanitize.defaults.allowedAttributes['a'].concat('rel'), - 'img': ['src', 'height', 'width', 'alt'] + 'img': ['src', 'height', 'width', 'alt', 'style'] }, + allowedStyles: { + '*': { + color: [/^red$/], + background: [/^green$/], + 'background-color': [/^#0000FF$/] + } + }, + allowedIframeHostnames: ['www.youtube.com'], + allowedSchemesAppliedToAttributes: [ 'href', 'src', 'cite' ], transformTags: { 'a': sanitize.simpleTransform('a', { 'rel': 'nofollow' }), 'img': (tagName: string, attribs: sanitize.Attributes) => { diff --git a/types/sat/index.d.ts b/types/sat/index.d.ts index 538228049c..901c0814f2 100644 --- a/types/sat/index.d.ts +++ b/types/sat/index.d.ts @@ -59,10 +59,10 @@ declare namespace SAT { setPoints(points: Vector[]): Polygon; setAngle(angle: number): Polygon; setOffset(offset: Vector): Polygon; - recalc(): Polygon; rotate(angle: number): Polygon; translate(x: number, y: number): Polygon; getAABB(): Polygon; + getCentroid(): Vector; } export class Box { diff --git a/types/select2/v3/index.d.ts b/types/select2/v3/index.d.ts index 21bb2611c7..771d997384 100644 --- a/types/select2/v3/index.d.ts +++ b/types/select2/v3/index.d.ts @@ -75,6 +75,7 @@ interface Select2Options { dropdownCss?: any; dropdownCssClass?: any; escapeMarkup?: (markup: string) => string; + nextSearchTerm?: (selectedObject: object, currentSearchTerm: string) => string; } interface Select2JQueryEventObject extends JQueryEventObject { diff --git a/types/select2/v3/select2-tests.ts b/types/select2/v3/select2-tests.ts index 3b331cec3b..2d5a400352 100644 --- a/types/select2/v3/select2-tests.ts +++ b/types/select2/v3/select2-tests.ts @@ -210,6 +210,9 @@ $("#e17_2").select2({ }); $("#e18,#e18_2").select2(); alert("Selected value is: " + $("#e8").select2("val")); $("#e8").select2("val", { id: "CA", text: "Califoria" }); +$("#e19").select2({nextSearchTerm: function(selectedObject: object, currentSearchTerm: string) { + return currentSearchTerm; +}}); $("#e8").select2("val"); $("#e8").select2("val", "CA"); diff --git a/types/simple-oauth2/index.d.ts b/types/simple-oauth2/index.d.ts index 21718c0722..19a1ff2698 100644 --- a/types/simple-oauth2/index.d.ts +++ b/types/simple-oauth2/index.d.ts @@ -1,11 +1,10 @@ -// Type definitions for simple-oauth2 1.1 +// Type definitions for simple-oauth2 2.2 // Project: https://github.com/lelylan/simple-oauth2 // Definitions by: Michael Müller , // Troy Lamerton +// Martín Rodriguez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import Bluebird = require("bluebird"); +// TypeScript Version: 2.9 /** Creates a new simple-oauth2 client with the passed configuration */ export function create(options: ModuleOptions): OAuthClient; @@ -33,13 +32,21 @@ export interface ModuleOptions { /** String path to request an authorization code. Default to /oauth/authorize. */ authorizePath?: string }; - /** optional object used to set global options to the internal http library (request-js). */ + /** + * Used to set global options to the internal http library (wreck). + * All options except baseUrl are allowed + * Defaults to header.Accept = "application/json" + */ http?: {}; options?: { - /** Whether or not the client.id/client.secret params are sent in the request body. Defaults to true. */ - useBodyAuth?: boolean, - /** Whether or not the Basic Authorization header should be sent at the token request. */ - useBasicAuthorizationHeader?: boolean + /** Format of data sent in the request body. Defaults to form. */ + bodyFormat?: "json" | "form", + /** + * Indicates the method used to send the client.id/client.secret authorization params at the token request. + * If set to body, the bodyFormat option will be used to format the credentials. + * Defaults to header + */ + authorizationMethod?: "header" | "body" }; } @@ -55,17 +62,19 @@ export interface AccessToken { /** Check if the access token is expired or not */ expired(): boolean; /** Refresh the access token */ - refresh(params: {}, callback: (error: any, result: AccessToken) => void): Bluebird; - refresh(callback?: (error: any, result: AccessToken) => void): Bluebird; + refresh(params?: {}): Promise; /** Revoke access or refresh token */ - revoke(tokenType: TokenType, callback?: (error: any) => void): Bluebird; + revoke(tokenType: TokenType): Promise; + /** Revoke both the existing access and refresh tokens */ + revokeAll(): Promise; } export type AuthorizationCode = string; export interface AuthorizationTokenConfig { + /** Authorization code (from previous step) */ code: AuthorizationCode; + /** A string that represents the callback uri */ redirect_uri: string; - scope?: string | string[]; } export interface PasswordTokenConfig { @@ -88,27 +97,32 @@ export interface OAuthClient { * Redirect the user to the autorization page * @return the absolute authorization url */ - authorizeURL(params?: { - /** A string that represents the registered application URI where the user is redirected after authentication */ - redirect_uri?: string, - /** A string or array of strings that represents the application privileges */ - scope?: string | string[], - /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ - state?: string - }): string, + authorizeURL( + params?: { + /** A key-value pair where key is ModuleOptions#client.idParamName and the value represents the Client-ID */ + [ idParamName: string ]: string | undefined + } & { + /** A string that represents the registered application URI where the user is redirected after authentication */ + redirect_uri?: string, + /** A string or array of strings that represents the application privileges */ + scope?: string | string[], + /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ + state?: string + } + ): string, /** Returns the Access Token object */ - getToken(params: AuthorizationTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: AuthorizationTokenConfig): Promise; }; ownerPassword: { /** Returns the Access Token Object */ - getToken(params: PasswordTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: PasswordTokenConfig): Promise; }; clientCredentials: { /** Returns the Access Token Object */ - getToken(params: ClientCredentialTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: ClientCredentialTokenConfig): Promise; }; accessToken: { diff --git a/types/simple-oauth2/simple-oauth2-tests.ts b/types/simple-oauth2/simple-oauth2-tests.ts index f83a616681..e066ad41c0 100644 --- a/types/simple-oauth2/simple-oauth2-tests.ts +++ b/types/simple-oauth2/simple-oauth2-tests.ts @@ -1,8 +1,11 @@ // off https://github.com/lelylan/simple-oauth2/blob/master/README.md // slightly changed to remove external dependencies +// Initialize the OAuth2 Library +import * as oauth2lib from "simple-oauth2"; + // Set the configuration settings -const credentials = { +const credentials: oauth2lib.ModuleOptions = { client: { id: '', secret: '' @@ -12,13 +15,10 @@ const credentials = { } }; -// Initialize the OAuth2 Library -// const oauth2 = require('simple-oauth2').create(credentials); -import oauth2lib = require("simple-oauth2"); const oauth2 = oauth2lib.create(credentials); // #Authorization Code flow -(() => { +(async () => { // Authorization oauth2 URI const authorizationUri = oauth2.authorizationCode.authorizeURL({ redirect_uri: 'http://localhost:3000/callback', @@ -36,57 +36,47 @@ const oauth2 = oauth2lib.create(credentials); scope: ['', ''] }; - // Callbacks // Save the access token - oauth2.authorizationCode.getToken(tokenConfig, (error, result) => { - if (error) { - console.log('Access Token Error', error.message); - return; - } + try { + const result = await oauth2.authorizationCode.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token Error', error.message); + } +})(); - const token = oauth2.accessToken.create(result); - }); +// #Password Credentials Flow +(async () => { + const tokenConfig = { + username: 'username', + password: 'password', + scope: [ '', '' ], + }; - // Promises // Save the access token - oauth2.authorizationCode.getToken(tokenConfig) - .then((result) => { - const token = oauth2.accessToken.create(result); - }) - .catch((error) => { - console.log('Access Token Error', error.message); - }); + try { + const result = await oauth2.ownerPassword.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token Error', error.message); + } })(); // #Client Credentials Flow -(() => { +(async () => { const tokenConfig = {}; - // Callbacks // Get the access token object for the client - oauth2.clientCredentials.getToken(tokenConfig, (error, result) => { - if (error) { - console.log('Access Token Error', error.message); - return; - } - - const token = oauth2.accessToken.create(result); - }); - - // Promises - // Get the access token object for the client - oauth2.clientCredentials - .getToken(tokenConfig) - .then((result) => { - const token = oauth2.accessToken.create(result); - }) - .catch((error) => { - console.log('Access Token error', error.message); - }); + try { + const result = await oauth2.clientCredentials.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token error', error.message); + } })(); // #Access Token object -(() => { +(async () => { // Sample of a JSON access token (you got it through previous steps) const tokenObject = { access_token: '', @@ -95,62 +85,46 @@ const oauth2 = oauth2lib.create(credentials); }; // Create the access token wrapper - let token = oauth2.accessToken.create(tokenObject); + let accessToken = oauth2.accessToken.create(tokenObject); // Check if the token is expired. If expired it is refreshed. - if (token.expired()) { - // Callbacks - token.refresh((error, result) => { - token = result; - }); - - // Promises - token.refresh() - .then((result) => { - token = result; - }); + if (accessToken.expired()) { + try { + accessToken = await accessToken.refresh(); + } catch (error) { + console.log('Error refreshing access token: ', error.message); + } } - // Callbacks - // Revoke only the access token - token.revoke('access_token', (error) => { + // Revoke both access and refresh tokens + try { + // Revoke only the access token + await accessToken.revoke('access_token'); + // Session ended. But the refresh_token is still valid. + // Revoke the refresh token + await accessToken.revoke('refresh_token'); - // Revoke the refresh_token - token.revoke('refresh_token', (error) => { - console.log('token revoked.'); - }); - }); + console.log('Token revoked'); + } catch (error) { + console.log('Error revoking token: ', error.message); + } - // Promises - // Revoke only the access token - token.revoke('access_token') - .then(() => { - // Revoke the refresh token - return token.revoke('refresh_token'); - }) - .then(() => { - console.log('Token revoked'); - }) - .catch((error) => { - console.log('Error revoking token.', error.message); - }); + // or... + + try { + // Revokes both tokens, refresh token is only revoked if the access_token is properly revoked + await accessToken.revokeAll(); + } catch (error) { + console.log('Error revoking token: ', error.message); + } })(); // #Errors // not applicable, as those errors about missing authentication codes are already found by the typescript compiler // (function () { -// // Callbacks -// oauth2.authorizationCode.getToken({}, (error, token) => { -// if (error) { -// return console.log(error.message); -// } -// }); - -// // Promises -// oauth2.authorizationCode -// .getToken({}) +// oauth2.authorizationCode.getToken({}) // .catch((error) => { // console.log(error.message); // }); diff --git a/types/simple-oauth2/v1/index.d.ts b/types/simple-oauth2/v1/index.d.ts new file mode 100644 index 0000000000..30b1a72d98 --- /dev/null +++ b/types/simple-oauth2/v1/index.d.ts @@ -0,0 +1,133 @@ +// Type definitions for simple-oauth2 1.6 +// Project: https://github.com/lelylan/simple-oauth2 +// Definitions by: Michael Müller , +// Troy Lamerton +// Martín Rodriguez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import Bluebird = require("bluebird"); + +/** Creates a new simple-oauth2 client with the passed configuration */ +export function create(options: ModuleOptions): OAuthClient; + +export interface ModuleOptions { + client: { + /** Service registered client id. Required. */ + id: string, + /** Service registered client secret. Required. */ + secret: string, + /** Parameter name used to send the client secret. Default to client_secret. */ + secretParamName?: string, + /** Parameter name used to send the client id. Default to client_id. */ + idParamName?: string + }; + auth: { + /** String used to set the host to request the tokens to. Required. */ + tokenHost: string, + /** String path to request an access token. Default to /oauth/token. */ + tokenPath?: string, + /** String path to revoke an access token. Default to /oauth/revoke. */ + revokePath?: string, + /** String used to set the host to request an "authorization code". Default to the value set on auth.tokenHost. */ + authorizeHost?: string, + /** String path to request an authorization code. Default to /oauth/authorize. */ + authorizePath?: string + }; + /** + * Used to set global options to the internal http library (wreck). + * All options except baseUrl are allowed + * Defaults to header.Accept = "application/json" + */ + http?: {}; + options?: { + /** Format of data sent in the request body. Defaults to form. */ + bodyFormat?: "json" | "form", + /** + * Indicates the method used to send the client.id/client.secret authorization params at the token request. + * If set to body, the bodyFormat option will be used to format the credentials. + * Defaults to header. + */ + authorizationMethod?: "header" | "body" + }; +} + +export type TokenType = "access_token" | "refresh_token"; + +export interface Token { + [x: string]: any; +} + +export interface AccessToken { + token: Token; + + /** Check if the access token is expired or not */ + expired(): boolean; + /** Refresh the access token */ + refresh(params: {}, callback: (error: any, result: AccessToken) => void): Bluebird; + refresh(callback?: (error: any, result: AccessToken) => void): Bluebird; + /** Revoke access or refresh token */ + revoke(tokenType: TokenType, callback?: (error: any) => void): Bluebird; +} + +export type AuthorizationCode = string; +export interface AuthorizationTokenConfig { + /** Authorization code (from previous step) */ + code: AuthorizationCode; + /** A string that represents the callback uri */ + redirect_uri: string; +} + +export interface PasswordTokenConfig { + /** A string that represents the registered username */ + username: string; + /** A string that represents the registered password. */ + password: string; + /** A string or array of strings that represents the application privileges */ + scope: string | string[]; +} + +export interface ClientCredentialTokenConfig { + /** A string that represents the application privileges */ + scope?: string | string[]; +} + +export interface OAuthClient { + authorizationCode: { + /** + * Redirect the user to the autorization page + * @return the absolute authorization url + */ + authorizeURL( + params?: { + /** A key-value pair where key is ModuleOptions#client.idParamName and the value represents the Client-ID */ + [ idParamName: string ]: string | undefined + } & { + /** A string that represents the registered application URI where the user is redirected after authentication */ + redirect_uri?: string, + /** A string or array of strings that represents the application privileges */ + scope?: string | string[], + /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ + state?: string + } + ): string, + + /** Returns the Access Token object */ + getToken(params: AuthorizationTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + ownerPassword: { + /** Returns the Access Token Object */ + getToken(params: PasswordTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + clientCredentials: { + /** Returns the Access Token Object */ + getToken(params: ClientCredentialTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + accessToken: { + /** Creates an OAuth2.AccessToken instance */ + create(tokenToUse: Token): AccessToken; + }; +} diff --git a/types/simple-oauth2/v1/simple-oauth2-tests.ts b/types/simple-oauth2/v1/simple-oauth2-tests.ts new file mode 100644 index 0000000000..b3a8b2f952 --- /dev/null +++ b/types/simple-oauth2/v1/simple-oauth2-tests.ts @@ -0,0 +1,188 @@ +// off https://github.com/lelylan/simple-oauth2/blob/master/README.md +// slightly changed to remove external dependencies + +// Initialize the OAuth2 Library +import * as oauth2lib from "simple-oauth2"; + +// Set the configuration settings +const credentials: oauth2lib.ModuleOptions = { + client: { + id: '', + secret: '' + }, + auth: { + tokenHost: 'https://api.oauth.com' + } +}; + +const oauth2 = oauth2lib.create(credentials); + +// #Authorization Code flow +(() => { + // Authorization oauth2 URI + const authorizationUri = oauth2.authorizationCode.authorizeURL({ + redirect_uri: 'http://localhost:3000/callback', + scope: '', + state: '' + }); + + // Redirect example using Express (see http://expressjs.com/api.html#res.redirect) + // res.redirect(authorizationUri); + + // Get the access token object (the authorization code is given from the previous step). + const tokenConfig = { + code: '', + redirect_uri: 'http://localhost:3000/callback', + scope: ['', ''] + }; + + // Callbacks + // Save the access token + oauth2.authorizationCode.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Save the access token + oauth2.authorizationCode.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token Error', error.message); + }); +})(); + +// #Password Credentials Flow +(() => { + const tokenConfig = { + username: 'username', + password: 'password', + scope: [ '', '' ], + }; + + // Callbacks + // Save the access token + oauth2.ownerPassword.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Save the access token + oauth2.ownerPassword.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token Error', error.message); + }); +})(); + +// #Client Credentials Flow +(() => { + const tokenConfig = {}; + + // Callbacks + // Get the access token object for the client + oauth2.clientCredentials.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Get the access token object for the client + oauth2.clientCredentials.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token error', error.message); + }); +})(); + +// #Access Token object +(() => { + // Sample of a JSON access token (you got it through previous steps) + const tokenObject = { + access_token: '', + refresh_token: '', + expires_in: '7200' + }; + + // Create the access token wrapper + let accessToken = oauth2.accessToken.create(tokenObject); + + // Check if the token is expired. If expired it is refreshed. + if (accessToken.expired()) { + // Callbacks + accessToken.refresh((error, result) => { + accessToken = result; + }); + + // Promises + accessToken.refresh() + .then((result) => { + accessToken = result; + }); + } + + // Callbacks + // Revoke only the access token + accessToken.revoke('access_token', (error) => { + // Session ended. But the refresh_token is still valid. + + // Revoke the refresh_token + accessToken.revoke('refresh_token', (error) => { + console.log('token revoked.'); + }); + }); + + // Promises + // Revoke only the access token + accessToken.revoke('access_token') + .then(() => { + // Revoke the refresh token + return accessToken.revoke('refresh_token'); + }) + .then(() => { + console.log('Token revoked'); + }) + .catch((error) => { + console.log('Error revoking token.', error.message); + }); +})(); + +// #Errors +// not applicable, as those errors about missing authentication codes are already found by the typescript compiler + +// (function () { +// // Callbacks +// oauth2.authorizationCode.getToken({}, (error, token) => { +// if (error) { +// return console.log(error.message); +// } +// }); + +// // Promises +// oauth2.authorizationCode +// .getToken({}) +// .catch((error) => { +// console.log(error.message); +// }); + +// // => { "status": "401", "message": "Unauthorized" } +// })(); diff --git a/types/simple-oauth2/v1/tsconfig.json b/types/simple-oauth2/v1/tsconfig.json new file mode 100644 index 0000000000..f19c003707 --- /dev/null +++ b/types/simple-oauth2/v1/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "simple-oauth2": [ + "simple-oauth2/v1" + ], + "simple-oauth2/*": [ + "simple-oauth2/v1/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "simple-oauth2-tests.ts" + ] +} diff --git a/types/simple-oauth2/v1/tslint.json b/types/simple-oauth2/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/simple-oauth2/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/single-spa-react/index.d.ts b/types/single-spa-react/index.d.ts new file mode 100644 index 0000000000..67721695ec --- /dev/null +++ b/types/single-spa-react/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for single-spa-react 2.8 +// Project: https://github.com/CanopyTax/single-spa-react +// Definitions by: Garrett Smith +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; + +export = SingleSpaReact; +declare function SingleSpaReact(opts: SingleSpaReact.Options): SingleSpaReact.Lifecycles; + +declare namespace SingleSpaReact { + interface Options { + React: typeof React; + ReactDOM: typeof ReactDOM; + rootComponent?: React.ComponentClass; + loadRootComponent?: () => Promise; + domElementGetter?: () => Element; + suppressComponentDidCatchWarning?: boolean; + parcelCanUpdate?: boolean; + } + + interface Lifecycles { + bootstrap: (opts: Options, props: any) => Promise; + mount: (opts: Options, props: any) => Promise; + unmount: (opts: Options, props: any) => Promise; + } +} diff --git a/types/single-spa-react/single-spa-react-tests.ts b/types/single-spa-react/single-spa-react-tests.ts new file mode 100644 index 0000000000..7efed91489 --- /dev/null +++ b/types/single-spa-react/single-spa-react-tests.ts @@ -0,0 +1,10 @@ +import singleSpaReact = require('single-spa-react'); +import { Lifecycles } from 'single-spa-react'; +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; + +// $ExpectType Lifecycles +singleSpaReact({ + React, + ReactDOM, +}); diff --git a/types/single-spa-react/tsconfig.json b/types/single-spa-react/tsconfig.json new file mode 100644 index 0000000000..3ccb45cf0c --- /dev/null +++ b/types/single-spa-react/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "single-spa-react-tests.ts" + ] +} diff --git a/types/single-spa-react/tslint.json b/types/single-spa-react/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/single-spa-react/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/slack-mock/index.d.ts b/types/slack-mock/index.d.ts new file mode 100644 index 0000000000..2289e554b4 --- /dev/null +++ b/types/slack-mock/index.d.ts @@ -0,0 +1,200 @@ +// Type definitions for slack-mock 1.1 +// Project: https://github.com/Skellington-Closet/slack-mock +// Definitions by: Kris Kalavantavanich +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { IncomingHttpHeaders } from "http"; +import * as nock from "nock"; +import { Url } from "url"; +import * as WebSocket from "ws"; + +export = SlackMock; + +declare function SlackMock(config?: SlackMock.ConfigOptions): SlackMock.Instance; + +declare namespace SlackMock { + let instance: Instance; + + interface Instance { + events: Events; + incomingWebhooks: IncomingWebhooks; + interactiveButtons: InteractiveButtons; + outgoingWebhooks: OutgoingWebhooks; + rtm: Rtm; + slashCommands: SlashCommands; + web: Web; + + reset: () => void; + } + + interface ConfigOptions { + rtmPort?: number; + logLevel?: string; + } + + // Events + + type EventUrl = string | Url; + type EventHttpHeaders = IncomingHttpHeaders; + + interface Events { + send: (targetUrl: EventUrl, body: T) => Promise; + reset: () => void; + calls: Array>; + } + + interface EventCall { + url: EventUrl; + params: T; + headers: EventHttpHeaders; + statusCode: number; + } + + // Incoming Webhooks + + type IncomingWebhookUrl = string; + type IncomingWebhookHttpHeaders = nock.HttpHeaders; + + interface IncomingWebhooks { + addResponse: (opts: IncomingWebhookOptions) => void; + reset: () => void; + calls: Array>; + } + + interface IncomingWebhookOptions { + url?: IncomingWebhookUrl; + statusCode ?: number; + body ?: T; + headers ?: IncomingWebhookHttpHeaders; + } + + interface IncomingWebhookCall { + url: IncomingWebhookUrl; + params: T; + headers: IncomingWebhookHttpHeaders; + } + + // Interactive Buttons + + type InteractiveButtonUrl = string | Url; + type InteractiveButtonHttpHeaders = nock.HttpHeaders; + + interface InteractiveButtons { + send: (targetUrl: InteractiveButtonUrl, body: T) => Promise; + addResponse: (opts: InteractiveButtonOptions) => void; + reset: () => void; + calls: Array>; + } + + interface InteractiveButtonOptions { + url?: InteractiveButtonUrl; + statusCode ?: number; + body ?: T; + headers ?: InteractiveButtonHttpHeaders; + } + + interface InteractiveButtonCall { + url: InteractiveButtonUrl; + params: T; + headers: InteractiveButtonHttpHeaders; + statusCode: number; + type: InteractiveButtonCallType; + } + + enum InteractiveButtonCallType { + response = 'response', + response_url = 'response_url' + } + + // Outgoing Webhooks + + type OutgoingWebhookUrl = string | Url; + type OutgoingWebhookHttpHeaders = IncomingHttpHeaders; + + interface OutgoingWebhooks { + send: (targetUrl: OutgoingWebhookUrl, body: T) => Promise; + reset: () => void; + calls: Array>; + } + + interface OutgoingWebhookCall { + url: OutgoingWebhookUrl; + params: T; + headers: OutgoingWebhookHttpHeaders; + statusCode: number; + } + + // RTM + + interface Rtm { + clients: WebSocket[]; + send: (token: string, message: T) => Promise; + reset: () => void; + calls: Array>; + startServer: (token: string) => void; + stopServer: (token: string) => void; + } + + interface RtmCall { + message: T; + token: string; + rawMessage: WebSocket.Data; + } + + // Slash Commands + + type SlashCommandUrl = string | Url; + type SlashCommandHttpHeaders = IncomingHttpHeaders; + + interface SlashCommands { + send: (targetUrl: SlashCommandUrl, body: T) => Promise; + addResponse: (opts: SlashCommandOptions) => void; + reset: () => void; + calls: Array>; + } + + interface SlashCommandOptions { + url?: SlashCommandUrl; + statusCode ?: number; + body ?: T; + headers ?: SlashCommandHttpHeaders; + } + + interface SlashCommandCall { + url: SlashCommandUrl; + params: T; + headers: SlashCommandHttpHeaders; + statusCode: number; + type: SlashCommandCallType; + } + + enum SlashCommandCallType { + response = 'response', + response_url = 'response_url' + } + + // Web + + type WebUrl = string; + type WebHttpHeaders = nock.HttpHeaders; + + interface Web { + addResponse: (opts: WebOptions) => void; + reset: () => void; + calls: Array>; + } + + interface WebOptions { + url?: WebUrl; + statusCode ?: number; + body ?: T; + headers ?: WebHttpHeaders; + } + + interface WebCall { + url: WebUrl; + params: T; + headers: WebHttpHeaders; + } +} diff --git a/types/slack-mock/slack-mock-tests.ts b/types/slack-mock/slack-mock-tests.ts new file mode 100644 index 0000000000..5b5dabb9c1 --- /dev/null +++ b/types/slack-mock/slack-mock-tests.ts @@ -0,0 +1,103 @@ +import SlackMock = require("slack-mock"); + +// Initialization + +const slackMock = SlackMock.instance; +SlackMock({ + logLevel: "error", + rtmPort: 9090 +}); +SlackMock(); + +// Events +const eventPayload = { }; +slackMock.events.send('http://localhost:9000/event', eventPayload) + .then(() => { + slackMock.events.calls.length; + slackMock.events.calls[0].statusCode; + slackMock.events.calls[0].headers; + slackMock.events.calls[0].params; + slackMock.events.calls[0].url; + }); + +slackMock.events.reset(); + +// Incoming Webhooks +slackMock.incomingWebhooks.calls.length; +slackMock.incomingWebhooks.calls[0].params.text; + +// Interactive Buttons +slackMock.interactiveButtons.addResponse({ + statusCode: 201 +}); + +const interactiveButtonPayload = {text: 'abc'}; +slackMock.interactiveButtons.send('http://localhost:9000/button', interactiveButtonPayload) + .then(() => { + slackMock.interactiveButtons.calls.length; + slackMock.interactiveButtons.calls[0].params.text; + }); + +// Outgoing Webhooks +const outgoingWebhookPayload = {text: 'abc'}; +slackMock.outgoingWebhooks.send('http://localhost:9000/outgoing', outgoingWebhookPayload) + .then(() => { + slackMock.outgoingWebhooks.calls.length; + slackMock.outgoingWebhooks.calls[0].params.text; + }); + +// RTM +slackMock.rtm.send('1234', { + type: 'message', + channel: 'mockChannel', + user: 'usr', + text: 'hello'}) + .then(() => { + slackMock.rtm.calls.length; + slackMock.rtm.calls[0].message.text; + }); +slackMock.rtm.startServer('1234'); +slackMock.rtm.stopServer('1234'); + +// Slash Commands +const slashCommandPayload = { }; +slackMock.slashCommands.send('http://localhost:9000/slash', slashCommandPayload) + .then(() => { + slackMock.slashCommands.calls.length; + slackMock.slashCommands.calls[0].params.text; + slackMock.slashCommands.calls[0].params.response_type; + }); + +// Web (OAuth Example) + +const botToken = 'xoxb-XXXXXXXXXXXX-TTTTTTTTTTTTTT'; +slackMock.web.addResponse({ + url: 'https://slack.com/api/oauth.access', + statusCode: 200, + body: { + access_token: 'xoxp-XXXXXXXX-XXXXXXXX-XXXXX', + scope: 'incoming-webhook,commands,bot', + team_name: 'mockTeam', + team_id: 'Tmock', + bot: { + bot_user_id: 'Bmock', + bot_access_token: botToken + } + } +}); + +slackMock.web.addResponse({ + url: 'https://slack.com/api/rtm.start', + statusCode: 200, + body: { + ok: true, + self: { + name: 'mockSelf', + id: 'Bmock' + }, + team: { + name: 'mockTeam', + id: 'Tmock' + } + } +}); diff --git a/types/slack-mock/tsconfig.json b/types/slack-mock/tsconfig.json new file mode 100644 index 0000000000..e012cc79b1 --- /dev/null +++ b/types/slack-mock/tsconfig.json @@ -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", + "slack-mock-tests.ts" + ] +} \ No newline at end of file diff --git a/types/slack-mock/tslint.json b/types/slack-mock/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/slack-mock/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/snapsvg/test/2.ts b/types/snapsvg/test/2.ts index 5afcf36460..708dc6f2bf 100644 --- a/types/snapsvg/test/2.ts +++ b/types/snapsvg/test/2.ts @@ -102,12 +102,12 @@ function tester5() { } Snap.animate(sideLength, sideLength + 100, updater, 1500 /*ms*/); - setTimeout(500, () => { Snap.animate(sideLength + 100, + setTimeout(() => { Snap.animate(sideLength + 100, 0, updater, 100 /*ms*/, easer, - square.remove); }); + square.remove); }, 500); } function tester6() { diff --git a/types/spectrum/index.d.ts b/types/spectrum/index.d.ts index bc94644a92..86b3077c04 100644 --- a/types/spectrum/index.d.ts +++ b/types/spectrum/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for spectrum 1.5.1 // Project: https://github.com/bgrins/spectrum/ // Definitions by: Mordechai Zuber +// Junyoung Clare Jang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -30,7 +31,7 @@ interface JQuery { /** * Gets the current value from the colorpicker. */ - spectrum(methodName: "get"): tinycolorInstance; + spectrum(methodName: "get"): tinycolor.Instance; /** * Sets the colorpickers value to update the original input. @@ -101,12 +102,12 @@ interface JQuery { /** * Called at the beginning of a drag event on either hue slider, alpha slider, or main color picker areas. */ - on(events: "dragstart.spectrum", handler: (eventObject: JQueryEventObject, color: tinycolorInstance) => any): JQuery; + on(events: "dragstart.spectrum", handler: (eventObject: JQueryEventObject, color: tinycolor.Instance) => any): JQuery; /** * Called at the end of a drag event on either hue slider, alpha slider, or main color picker areas. */ - on(events: "dragstop.spectrum", handler: (eventObject: JQueryEventObject, color: tinycolorInstance) => any): JQuery; + on(events: "dragstop.spectrum", handler: (eventObject: JQueryEventObject, color: tinycolor.Instance) => any): JQuery; } declare namespace Spectrum { @@ -263,18 +264,18 @@ declare namespace Spectrum { /** * Called as the original input changes. Only happens when the input is closed or the 'Choose' button is clicked. */ - change?: (color: tinycolorInstance) => void; + change?: (color: tinycolor.Instance) => void; /** * Called as the user moves around within the colorpicker. */ - move?: (color: tinycolorInstance) => void; + move?: (color: tinycolor.Instance) => void; /** * Called after the colorpicker is opened. This is ignored on a flat colorpicker. * Note, when any colorpicker on the page is shown it will hide any that are already open. */ - show?: (color: tinycolorInstance) => void; + show?: (color: tinycolor.Instance) => void; /** * Called after the colorpicker is hidden. @@ -282,12 +283,12 @@ declare namespace Spectrum { * Note, when any colorpicker on the page is shown it will hide any that are already open. * This event is ignored on a flat colorpicker. */ - hide?: (color: tinycolorInstance) => void; + hide?: (color: tinycolor.Instance) => void; /** * You can prevent the colorpicker from showing up if you return false in the beforeShow event. * This event is ignored on a flat colorpicker. */ - beforeShow?: (color: tinycolorInstance) => void; + beforeShow?: (color: tinycolor.Instance) => void; } } diff --git a/types/ssh2-sftp-client/index.d.ts b/types/ssh2-sftp-client/index.d.ts index a0133961d8..0e1555abaf 100644 --- a/types/ssh2-sftp-client/index.d.ts +++ b/types/ssh2-sftp-client/index.d.ts @@ -1,17 +1,19 @@ -// Type definitions for ssh2-sftp-client 2.0 +// Type definitions for ssh2-sftp-client 2.3 // Project: https://www.npmjs.com/package/ssh2-sftp-client -// Definitions by: igrayson , Ascari Andrea +// Definitions by: igrayson , Ascari Andrea , Kartik Malik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as ssh2 from 'ssh2'; - +import * as ssh2Stream from 'ssh2-streams'; export = sftp; declare class sftp { connect(options: ssh2.ConnectConfig): Promise; list(remoteFilePath: string): Promise; get(remoteFilePath: string, useCompression?: boolean, encoding?: string | null): Promise; + fastGet(remoteFilePath: string, localPath: string, options?: ssh2Stream.TransferOptions): Promise; put(input: string | Buffer | NodeJS.ReadableStream, remoteFilePath: string, useCompression?: boolean, encoding?: string): Promise; + fastPut(localPath: string, emoteFilePath: string, options?: ssh2Stream.TransferOptions): Promise; mkdir(remoteFilePath: string, recursive?: boolean): Promise; rmdir(remoteFilePath: string, recursive?: boolean): Promise; delete(remoteFilePath: string): Promise; diff --git a/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts b/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts index 67d2d35826..0b9c1a940c 100644 --- a/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts +++ b/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts @@ -15,10 +15,14 @@ client.get('/remote/path').then(stream => stream.read(0)); client.get('/remote/path', true, 'utf8').then(stream => stream.read(0)); client.get('/remote/path', true, null).then(stream => stream.read(0)); +client.fastGet('/remote/path', 'local/path').then(() => null); + client.put('/local/path', '/remote/path').then(() => null); client.put(new Buffer('content'), '/remote/path').then(() => null); client.put(fs.createReadStream('Hello World'), '/remote/path').then(() => null); +client.fastPut('/remote/path', 'local/path').then(() => null); + client.mkdir('/remote/path/dir', true).then(() => null); client.rmdir('/remote/path/dir', true).then(() => null); diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index d07309eae5..3f963ab18d 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -825,6 +825,7 @@ export class Transaction { fee: number; source: string; memo: Memo; + signatures: xdr.DecoratedSignature[]; } export class TransactionBuilder { @@ -862,9 +863,11 @@ export class Keypair { publicKey(): string; secret(): string; + rawPublicKey(): Buffer; rawSecretKey(): Buffer; canSign(): boolean; sign(data: Buffer): Buffer; + signatureHint(): xdr.SignatureHint; verify(data: Buffer, signature: Buffer): boolean; } @@ -876,4 +879,9 @@ export namespace xdr { class Asset extends XDRStruct { } class Memo extends XDRStruct { } class TransactionEnvelope extends XDRStruct { } + class DecoratedSignature extends XDRStruct { + constructor(keys: { hint: SignatureHint, signature: Signature }) + } + class SignatureHint { } + class Signature { } } diff --git a/types/storybook__addon-info/index.d.ts b/types/storybook__addon-info/index.d.ts index c616933b8f..ebef2fed73 100644 --- a/types/storybook__addon-info/index.d.ts +++ b/types/storybook__addon-info/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @storybook/addon-info 3.2 +// Type definitions for @storybook/addon-info 3.4 // Project: https://github.com/storybooks/storybook // Definitions by: Mark Kornblum // Mattias Wikstrom @@ -29,6 +29,6 @@ export interface Options { maxPropStringLength?: number; } -export function withInfo(textOrOptions: string | Options): (storyFn: RenderFunction) => (context?: object) => React.ReactElement; +export function withInfo(textOrOptions?: string | Options): (storyFn: RenderFunction) => (context?: object) => React.ReactElement; export function setDefaults(newDefaults: Options): Options; diff --git a/types/storybook__addon-info/storybook__addon-info-tests.tsx b/types/storybook__addon-info/storybook__addon-info-tests.tsx index b51a48c4cc..46fd799314 100644 --- a/types/storybook__addon-info/storybook__addon-info-tests.tsx +++ b/types/storybook__addon-info/storybook__addon-info-tests.tsx @@ -12,6 +12,11 @@ setDefaults({ }); storiesOf('Component', module) + .add('no info', + withInfo()(() => + Click the "?" mark at top-right to view the info. + ) + ) .add('simple info', withInfo('doc string about my component')(() => Click the "?" mark at top-right to view the info. diff --git a/types/stylelint/index.d.ts b/types/stylelint/index.d.ts index 67316843a9..2068aff709 100644 --- a/types/stylelint/index.d.ts +++ b/types/stylelint/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for stylelint 7.11 +// Type definitions for stylelint 9.4 // Project: https://github.com/stylelint/stylelint // Definitions by: Alan Agius // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export type FormatterType = "json" | "string" | "verbose"; +export type FormatterType = "json" | "string" | "verbose" | "compact"; export type SyntaxType = "scss" | "sass" | "less" | "sugarss"; @@ -45,6 +45,7 @@ export interface LintResult { export namespace formatters { function json(results: LintResult[]): string; function string(results: LintResult[]): string; + function compact(results: LintResult[]): string; function verbose(results: LintResult[]): string; } diff --git a/types/stylelint/tslint.json b/types/stylelint/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/stylelint/tslint.json +++ b/types/stylelint/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/stylelint/v7/index.d.ts b/types/stylelint/v7/index.d.ts new file mode 100644 index 0000000000..67316843a9 --- /dev/null +++ b/types/stylelint/v7/index.d.ts @@ -0,0 +1,51 @@ +// Type definitions for stylelint 7.11 +// Project: https://github.com/stylelint/stylelint +// Definitions by: Alan Agius +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type FormatterType = "json" | "string" | "verbose"; + +export type SyntaxType = "scss" | "sass" | "less" | "sugarss"; + +export interface LinterOptions { + code?: string; + codeFilename?: string; + config?: JSON; + configBasedir?: string; + configFile?: string; + configOverrides?: JSON; + cache?: boolean; + cacheLocation?: string; + files?: string | string[]; + fix?: boolean; + formatter?: FormatterType; + ignoreDisables?: boolean; + reportNeedlessDisables?: boolean; + ignorePath?: boolean; + syntax?: SyntaxType; + customSyntax?: string; +} + +export interface LinterResult { + errored: boolean; + output: string; + postcssResults: any[]; + results: LintResult[]; +} + +export interface LintResult { + source: string; + errored: boolean | undefined; + ignored: boolean | undefined; + warnings: string[]; + deprecations: string[]; + invalidOptionWarnings: any[]; +} + +export namespace formatters { + function json(results: LintResult[]): string; + function string(results: LintResult[]): string; + function verbose(results: LintResult[]): string; +} + +export function lint(options?: LinterOptions): Promise; diff --git a/types/stylelint/v7/stylelint-tests.ts b/types/stylelint/v7/stylelint-tests.ts new file mode 100644 index 0000000000..785eb2e425 --- /dev/null +++ b/types/stylelint/v7/stylelint-tests.ts @@ -0,0 +1,24 @@ +import { LinterOptions, FormatterType, SyntaxType, lint, LintResult, LinterResult } from "stylelint"; + +const options: LinterOptions = { + code: "div { color: red }", + files: ["**/**.scss"], + formatter: "json", + cache: true, + cacheLocation: "./stylelint.cache.json", + ignoreDisables: true, + reportNeedlessDisables: true, + ignorePath: true, + syntax: "scss" +}; + +lint(options).then((x: LinterResult) => { + const err: boolean = x.errored; + const output: string = x.output; + const postcssResults: any[] = x.postcssResults; + const results: LintResult[] = x.results; +}); + +const formatter: FormatterType = "json"; + +const syntax: SyntaxType = "scss"; diff --git a/types/stylelint/v7/tsconfig.json b/types/stylelint/v7/tsconfig.json new file mode 100644 index 0000000000..b6f6796252 --- /dev/null +++ b/types/stylelint/v7/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "stylelint": [ + "stylelint/v7" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "stylelint-tests.ts" + ] +} diff --git a/types/stylelint/v7/tslint.json b/types/stylelint/v7/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/stylelint/v7/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/thepiratebay/index.d.ts b/types/thepiratebay/index.d.ts new file mode 100644 index 0000000000..20a1cc8945 --- /dev/null +++ b/types/thepiratebay/index.d.ts @@ -0,0 +1,69 @@ +// Type definitions for thepiratebay 1.4 +// Project: http://github.com/t3chnoboy/thepiratebay +// Definitions by: Jack Sorrell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function search(query?: string, options?: SearchOptions): Promise; +export function getTorrent(id: string | number | { link: string; [propName: string]: any; }): Promise; +export function getComments(id: string | number): Promise; +export function topTorrents(category?: number): Promise; +export function recentTorrents(): Promise; +export function userTorrents(user: string, options?: SearchOptions): Promise; +export function getTvShow(id: string | number): Promise; +export function getCategories(): Promise; + +export interface SearchOptions { + category?: string | number; + filter?: { verified?: boolean }; + page?: number; + orderBy?: string; + sortBy?: string; +} + +export interface Category { + id: string; + name: string; +} + +export interface CategoryGroup extends Category { + subcategories: Category[]; +} + +export interface Torrent { + id: string; + name: string; + size: string; + link: string; + seeders: string; + leechers: string; + uploadDate: string; + magnetLink: string; + uploader: string; + uploaderLink: string; +} + +export interface TorrentDetails extends Torrent { + description: string; +} + +export interface TorrentSearchResult extends Torrent { + category: Category; + subcategory: Category; + verified: boolean; +} + +export interface Comment { + user: string; + comment: string; +} + +export interface TVTorrent { + id: string; + title: string; + link: string; +} + +export interface TVSeason { + title: string; + torrents: TVTorrent[]; +} diff --git a/types/thepiratebay/thepiratebay-tests.ts b/types/thepiratebay/thepiratebay-tests.ts new file mode 100644 index 0000000000..76c56eb269 --- /dev/null +++ b/types/thepiratebay/thepiratebay-tests.ts @@ -0,0 +1,104 @@ +import * as PirateBay from 'thepiratebay'; + +// $ExpectType Promise +const searchResultPromise = PirateBay.search('Game of Thrones', { + category: 'all', + filter: { + verified: false + }, + page: 0, + orderBy: 'leeches', + sortBy: 'desc' +}); +searchResultPromise.then((res: PirateBay.TorrentSearchResult[]) => { + res[0].id; // $ExpectType string + res[0].name; // $ExpectType string + res[0].size; // $ExpectType string + res[0].link; // $ExpectType string + res[0].seeders; // $ExpectType string + res[0].leechers; // $ExpectType string + res[0].uploadDate; // $ExpectType string + res[0].magnetLink; // $ExpectType string + res[0].uploader; // $ExpectType string + res[0].uploaderLink; // $ExpectType string + + const category = res[0].category; // $ExpectType Category + category.id; // $ExpectType string + category.name; // $ExpectType string + + res[0].subcategory; // $ExpectType Category + res[0].verified; // $ExpectType boolean +}); +// $ExpectError +PirateBay.search(15); + +// $ExpectType Promise +const torrentPromise = PirateBay.getTorrent('15496322'); +torrentPromise.then((torrent: PirateBay.TorrentDetails) => { + torrent.id; // $ExpectType string + torrent.name; // $ExpectType string + torrent.size; // $ExpectType string + torrent.link; // $ExpectType string + torrent.seeders; // $ExpectType string + torrent.leechers; // $ExpectType string + torrent.uploadDate; // $ExpectType string + torrent.magnetLink; // $ExpectType string + torrent.uploader; // $ExpectType string + torrent.uploaderLink; // $ExpectType string + torrent.description; // $ExpectType string +}); +// $ExpectType Promise +PirateBay.getTorrent(15496322); +// $ExpectError +PirateBay.getTorrent(false); +// $ExpectType Promise +PirateBay.getTorrent('https://thepiratebay.org/torrent/15496322/Ubuntu_16.04.1_LTS_Desktop_64-bit'); +// $ExpectType Promise +PirateBay.getTorrent({ name: "ubuntu", link: 'https://thepiratebay.org/torrent/15496322/Ubuntu_16.04.1_LTS_Desktop_64-bit' }); + +// $ExpectType Promise +PirateBay.topTorrents(); +// $ExpectError +PirateBay.topTorrents(true); +// $ExpectType Promise +PirateBay.topTorrents(400); + +// $ExpectType Promise +PirateBay.recentTorrents(); +// $ExpectError +PirateBay.recentTorrents(10); + +// $ExpectError +PirateBay.userTorrents(); +// $ExpectType Promise +PirateBay.userTorrents('alice', { + page: 3, + orderBy: 'name', + sortBy: 'asc' +}); +// $ExpectType Promise +PirateBay.userTorrents('bob'); + +// $ExpectType Promise +const categoryGroup = PirateBay.getCategories(); +categoryGroup.then((groups: PirateBay.CategoryGroup[]) => { + groups[0].id; // $ExpectType string + groups[0].name; // $ExpectType string + groups[0].subcategories; // $ExpectType Category[] +}); +// $ExpectError +PirateBay.getCategories(154); + +// $ExpectError +PirateBay.getTvShow(); +// $ExpectType Promise +const tvShow = PirateBay.getTvShow(15); +tvShow.then((seasons: PirateBay.TVSeason[]) => { + seasons[0].title; // $ExpectType string + const torrents = seasons[0].torrents; // $ExpectType TVTorrent[] + torrents[0].id; // $ExpectType string + torrents[0].title; // $ExpectType string + torrents[0].link; // $ExpectType string +}); +// $ExpectType Promise +PirateBay.getTvShow('15'); diff --git a/types/thepiratebay/tsconfig.json b/types/thepiratebay/tsconfig.json new file mode 100644 index 0000000000..1d491e4d75 --- /dev/null +++ b/types/thepiratebay/tsconfig.json @@ -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", + "thepiratebay-tests.ts" + ] +} diff --git a/types/thepiratebay/tslint.json b/types/thepiratebay/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/thepiratebay/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/tinajs__tina-redux/index.d.ts b/types/tinajs__tina-redux/index.d.ts new file mode 100644 index 0000000000..e48665e696 --- /dev/null +++ b/types/tinajs__tina-redux/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for @tinajs/tina-redux 1.4 +// Project: https://github.com/tinajs/tina-redux +// Definitions by: Jiayu Liu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tinajs__tina-redux +// TypeScript Version: 2.3 + +import { Store, Dispatch } from "redux"; + +type MapStateToProps = (state: any) => any; +type mapDispatchToProps = (dispatch: Dispatch) => any; + +interface HOC { + onLoad: () => void; + onUnload: () => void; + methods: object; +} + +declare class TinaRedux { + constructor(reduxStore: Store); + connect(mapState?: MapStateToProps, mapDispatch?: mapDispatchToProps): HOC; +} + +export = TinaRedux; diff --git a/types/tinajs__tina-redux/package.json b/types/tinajs__tina-redux/package.json new file mode 100644 index 0000000000..7f5b19d45b --- /dev/null +++ b/types/tinajs__tina-redux/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "redux": "^4.0.0" + } +} diff --git a/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts b/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts new file mode 100644 index 0000000000..d4a7c2225f --- /dev/null +++ b/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts @@ -0,0 +1,51 @@ +import { createStore, combineReducers, Action } from "redux"; +import TinaRedux from "@tinajs/tina-redux"; + +interface Todo { + id: number; + text: string; + completed: boolean; +} + +interface TodoAction extends Action, Todo {} + +const intialState: Todo[] = [ + { id: 1, text: "Star Tina.js", completed: false }, + { id: 2, text: "Star Tina-Redux", completed: true }, + { id: 3, text: "Build a mini-program with Tina.js", completed: false }, + { id: 4, text: "Add to Showcase of Tina.js", completed: false } +]; + +const todos = (state = intialState, action: TodoAction) => { + switch (action.type) { + case "ADD_TODO": + return [ + ...state, + { + id: action.id, + text: action.text, + completed: false + } + ]; + case "TOGGLE_TODO": + return state.map( + todo => + todo.id === action.id + ? { ...todo, completed: !todo.completed } + : todo + ); + case "CLEAR_COMPLETED_TODOS": + return state.filter(todo => !todo.completed); + default: + return state; + } +}; + +const todoApp = combineReducers({ + todos +}); + +const reduxStore = createStore(todoApp); +const store = new TinaRedux(reduxStore); + +export default store; diff --git a/types/tinajs__tina-redux/tsconfig.json b/types/tinajs__tina-redux/tsconfig.json new file mode 100644 index 0000000000..c3b4905b15 --- /dev/null +++ b/types/tinajs__tina-redux/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "allowSyntheticDefaultImports": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@tinajs/tina": ["tinajs__tina"], + "@tinajs/tina-redux": ["tinajs__tina-redux"] + } + }, + "files": ["index.d.ts", "tinajs__tina-redux-tests.ts"] +} diff --git a/types/tinajs__tina-redux/tslint.json b/types/tinajs__tina-redux/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/tinajs__tina-redux/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/tinycolor2/index.d.ts b/types/tinycolor2/index.d.ts index 921d8a4f08..4d28d623ac 100644 --- a/types/tinycolor2/index.d.ts +++ b/types/tinycolor2/index.d.ts @@ -1,393 +1,673 @@ -// Type definitions for tinycolor v1.4.1 +// Type definitions for tinycolor 1.4 // Project: https://github.com/bgrins/TinyColor -// Definitions by: Mordechai Zuber , Geert Jansen , Niels van Hoorn +// Definitions by: Mordechai Zuber , +// Geert Jansen , +// Niels van Hoorn , +// Junyoung Clare Jang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -declare var tinycolor: tinycolor; +declare namespace tinycolor { + type ColorInputWithoutInstance = + | string + | ColorFormats.PRGB + | ColorFormats.PRGBA + | ColorFormats.RGB + | ColorFormats.RGBA + | ColorFormats.HSL + | ColorFormats.HSLA + | ColorFormats.HSV + | ColorFormats.HSVA + ; + type ColorInput = ColorInputWithoutInstance | Instance; -interface tinycolor { + namespace ColorFormats { + interface Alpha { + a: number; + } - /** - * Create a tinycolor instance of the color named. - * - * @param color - the color as a string to create an instance for. - */ - (color: string): tinycolorInstance; + interface PRGB { + r: string; + g: string; + b: string; + } - /** - * Create a tinycolor instance with the given RGB values. - * - * @param color - the rgb values to apply to the new instance. - */ - (color: ColorFormats.RGB): tinycolorInstance; + interface PRGBA extends PRGB, Alpha {} - /** - * Create a tinycolor instance with the given RGBA values. - * - * @param color - the rgba values to apply to the new instance. - */ - (color: ColorFormats.RGBA): tinycolorInstance; + interface RGB { + r: number; + g: number; + b: number; + } - /** - * Create a tinycolor instance with the given HSL values. - * - * @param color - the hsl values to apply to the new instance. - */ - (color: ColorFormats.HSL): tinycolorInstance; + interface RGBA extends RGB, Alpha {} - /** - * Create a tinycolor instance with the given HSLA values. - * - * @param color - the hsla values to apply to the new instance. - */ - (color: ColorFormats.HSLA): tinycolorInstance; + interface HSL { + h: number; + s: number; + l: number; + } - /** - * Create a tinycolor instance with the given HSV values. - * - * @param color - the hsv values to apply to the new instance. - */ - (color: ColorFormats.HSV): tinycolorInstance; + interface HSLA extends HSL, Alpha {} - /** - * Create a tinycolor instance with the given HSVA values. - * - * @param color - the hsva values to apply to the new instance. - */ - (color: ColorFormats.HSVA): tinycolorInstance; + interface HSV { + h: number; + s: number; + v: number; + } - /** - * Create a tinycolor instance based off the relative values. - * Works with any color formats - * - * @param ratio - the relative color/hue values to apply to the new instance. - */ - fromRatio(ratio: any): tinycolorInstance; // any of the interfaces defined in the ColorFormats module. + interface HSVA extends HSV { + a: number; + } + } - /** - * Compares the two colors and returns the difference between their brightness and color/hue - * - * @param firstColor - the first color to be used in the comparison. - * @param secondColor - the second color to be used in the comparison. - */ - readability(firstColor: ColorInput, secondColor: ColorInput): Readable.Readable; + interface ConstructorOptions { + format?: string; + gradientType?: boolean; + } - /** - * Ensure that foreground and background color combinations meet WCAG2 guidelines. - * - * @param foreColor - the fore color wanted. - * @param backColor - the back color wanted. - * @param wcag2 - The 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA'; the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'. If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}. - */ - isReadable(foreColor: ColorInput, backColor: ColorInput, wcag2?: {level?: string, size?: string}): boolean; + interface WCAG2Options { + level?: "AA" | "AAA"; + size?: "large" | "small"; + } - /** - * Given a base color and a list of possible foreground or background colors for that base, - * returns the most readable color. Optionally returns Black or White if the most readable color is unreadable. - * - * @param color - the base color. - * @param colorsToCompare - array of colors to pick the most readable one from. - * @param args - and object with extra arguments - */ - mostReadable(color: ColorInput, colorsToCompare: ColorInput[], args?: {includeFallbackColors?: boolean, level?: string, size?: string}): tinycolorInstance; + interface MostReadableArgs extends WCAG2Options { + includeFallbackColors?: boolean; + } - /**/ - mix(color1: ColorInput, color2: ColorInput, amount?: number): tinycolorInstance; + interface Constructor { + /** + * Create a tinycolor instance of the color named. + * + * @param color - the color as one of the valid color input format. + */ + new (color?: ColorInput, opts?: ConstructorOptions): Instance; + (color?: ColorInput, opts?: ConstructorOptions): Instance; - /** - * Can be called with any tinycolor input - */ - equals(color1: ColorInput, color2: ColorInput): boolean; + /** + * Create a tinycolor instance based off the relative values. + * Works with any color formats + * + * @param ratio - the relative color/hue values to apply to the new instance. + */ + fromRatio(ratio?: ColorInputWithoutInstance): Instance; - /** - * Returns a random color - */ - random(): tinycolorInstance; + /** + * Compares two colors. Each colors can be any color inputs. + */ + equals(color1?: ColorInput, color2?: ColorInput): boolean; - /** - * key: hex value - * value: string name ex. hexnames["f00"] --> "red" - */ - hexNames: { [key: string]: string }; + /** + * Returns a random color + */ + random(): Instance; - /** - * key: 'real' color name - * value: hex value ex. names["red"] --> "f00" - */ - names: { [key: string]: string }; -} + mix(color1: ColorInput, color2: ColorInput, amount?: number): Instance; -interface tinycolorInstance { + /** + * Compares the two colors and returns the constrast between two colors as a number. + * + * @param color1 - the first color to be used in the comparison. + * @param color2 - the second color to be used in the comparison. + */ + readability(color1: ColorInput, color2: ColorInput): number; - /** - * Return an indication whether the color was successfully parsed. - */ - isValid(): boolean; + /** + * Ensure that foreground and background color combinations meet WCAG2 guidelines. + * + * @param color1 - the fore color wanted. + * @param color2 - the back color wanted. + * @param wcag2 - WCAG option. If the entire object is absent, function use the default of {level:"AA",size:"small"}. + * @param wcag2.level - The 'level' property states 'AA' or 'AAA' + * if missing or invalid, it defaults to 'AA' + * @param wcag2.size - The 'size' property states 'large' or 'small' + * if missing or invalid, it defaults to 'small'. + */ + isReadable(color1: ColorInput, color2: ColorInput, wcag2?: WCAG2Options): boolean; - /** - * Return an indication whether the color's perceived brightness is light. - */ - isLight(): boolean; + /** + * Given a base color and a list of possible foreground or background colors for that base, + * returns the most readable color. Optionally returns Black or White if the most readable color is unreadable. + * + * @param color - the base color. + * @param colorsToCompare - array of colors to pick the most readable one from. + * @param args - and object with extra arguments + */ + mostReadable(baseColor: ColorInput, colorList: ColorInput[], args?: MostReadableArgs): Instance; - /** - * Return an indication whether the color's perceived brightness is dark. - */ - isDark(): boolean; + /** + * key: 'real' color name + * value: hex value ex. names["red"] --> "f00" + */ + names: { + aliceblue: "f0f8ff"; + antiquewhite: "faebd7"; + aqua: "0ff"; + aquamarine: "7fffd4"; + azure: "f0ffff"; + beige: "f5f5dc"; + bisque: "ffe4c4"; + black: "000"; + blanchedalmond: "ffebcd"; + blue: "00f"; + blueviolet: "8a2be2"; + brown: "a52a2a"; + burlywood: "deb887"; + burntsienna: "ea7e5d"; + cadetblue: "5f9ea0"; + chartreuse: "7fff00"; + chocolate: "d2691e"; + coral: "ff7f50"; + cornflowerblue: "6495ed"; + cornsilk: "fff8dc"; + crimson: "dc143c"; + cyan: "0ff"; + darkblue: "00008b"; + darkcyan: "008b8b"; + darkgoldenrod: "b8860b"; + darkgray: "a9a9a9"; + darkgreen: "006400"; + darkgrey: "a9a9a9"; + darkkhaki: "bdb76b"; + darkmagenta: "8b008b"; + darkolivegreen: "556b2f"; + darkorange: "ff8c00"; + darkorchid: "9932cc"; + darkred: "8b0000"; + darksalmon: "e9967a"; + darkseagreen: "8fbc8f"; + darkslateblue: "483d8b"; + darkslategray: "2f4f4f"; + darkslategrey: "2f4f4f"; + darkturquoise: "00ced1"; + darkviolet: "9400d3"; + deeppink: "ff1493"; + deepskyblue: "00bfff"; + dimgray: "696969"; + dimgrey: "696969"; + dodgerblue: "1e90ff"; + firebrick: "b22222"; + floralwhite: "fffaf0"; + forestgreen: "228b22"; + fuchsia: "f0f"; + gainsboro: "dcdcdc"; + ghostwhite: "f8f8ff"; + gold: "ffd700"; + goldenrod: "daa520"; + gray: "808080"; + green: "008000"; + greenyellow: "adff2f"; + grey: "808080"; + honeydew: "f0fff0"; + hotpink: "ff69b4"; + indianred: "cd5c5c"; + indigo: "4b0082"; + ivory: "fffff0"; + khaki: "f0e68c"; + lavender: "e6e6fa"; + lavenderblush: "fff0f5"; + lawngreen: "7cfc00"; + lemonchiffon: "fffacd"; + lightblue: "add8e6"; + lightcoral: "f08080"; + lightcyan: "e0ffff"; + lightgoldenrodyellow: "fafad2"; + lightgray: "d3d3d3"; + lightgreen: "90ee90"; + lightgrey: "d3d3d3"; + lightpink: "ffb6c1"; + lightsalmon: "ffa07a"; + lightseagreen: "20b2aa"; + lightskyblue: "87cefa"; + lightslategray: "789"; + lightslategrey: "789"; + lightsteelblue: "b0c4de"; + lightyellow: "ffffe0"; + lime: "0f0"; + limegreen: "32cd32"; + linen: "faf0e6"; + magenta: "f0f"; + maroon: "800000"; + mediumaquamarine: "66cdaa"; + mediumblue: "0000cd"; + mediumorchid: "ba55d3"; + mediumpurple: "9370db"; + mediumseagreen: "3cb371"; + mediumslateblue: "7b68ee"; + mediumspringgreen: "00fa9a"; + mediumturquoise: "48d1cc"; + mediumvioletred: "c71585"; + midnightblue: "191970"; + mintcream: "f5fffa"; + mistyrose: "ffe4e1"; + moccasin: "ffe4b5"; + navajowhite: "ffdead"; + navy: "000080"; + oldlace: "fdf5e6"; + olive: "808000"; + olivedrab: "6b8e23"; + orange: "ffa500"; + orangered: "ff4500"; + orchid: "da70d6"; + palegoldenrod: "eee8aa"; + palegreen: "98fb98"; + paleturquoise: "afeeee"; + palevioletred: "db7093"; + papayawhip: "ffefd5"; + peachpuff: "ffdab9"; + peru: "cd853f"; + pink: "ffc0cb"; + plum: "dda0dd"; + powderblue: "b0e0e6"; + purple: "800080"; + rebeccapurple: "663399"; + red: "f00"; + rosybrown: "bc8f8f"; + royalblue: "4169e1"; + saddlebrown: "8b4513"; + salmon: "fa8072"; + sandybrown: "f4a460"; + seagreen: "2e8b57"; + seashell: "fff5ee"; + sienna: "a0522d"; + silver: "c0c0c0"; + skyblue: "87ceeb"; + slateblue: "6a5acd"; + slategray: "708090"; + slategrey: "708090"; + snow: "fffafa"; + springgreen: "00ff7f"; + steelblue: "4682b4"; + tan: "d2b48c"; + teal: "008080"; + thistle: "d8bfd8"; + tomato: "ff6347"; + turquoise: "40e0d0"; + violet: "ee82ee"; + wheat: "f5deb3"; + white: "fff"; + whitesmoke: "f5f5f5"; + yellow: "ff0"; + yellowgreen: "9acd32"; + }; - /** - * Returns the format used to create the tinycolor instance. - */ - getFormat(): string; + /** + * key: hex value + * value: string name ex. hexnames["f00"] --> "red" + */ + hexNames: { + "f0f8ff": "aliceblue"; + "faebd7": "antiquewhite"; + "0ff": "aqua" | "cyan"; + "7fffd4": "aquamarine"; + "f0ffff": "azure"; + "f5f5dc": "beige"; + "ffe4c4": "bisque"; + "000": "black"; + "ffebcd": "blanchedalmond"; + "00f": "blue"; + "8a2be2": "blueviolet"; + "a52a2a": "brown"; + "deb887": "burlywood"; + "ea7e5d": "burntsienna"; + "5f9ea0": "cadetblue"; + "7fff00": "chartreuse"; + "d2691e": "chocolate"; + "ff7f50": "coral"; + "6495ed": "cornflowerblue"; + "fff8dc": "cornsilk"; + "dc143c": "crimson"; + "00008b": "darkblue"; + "008b8b": "darkcyan"; + "b8860b": "darkgoldenrod"; + "a9a9a9": "darkgray" | "darkgrey"; + "006400": "darkgreen"; + "bdb76b": "darkkhaki"; + "8b008b": "darkmagenta"; + "556b2f": "darkolivegreen"; + "ff8c00": "darkorange"; + "9932cc": "darkorchid"; + "8b0000": "darkred"; + "e9967a": "darksalmon"; + "8fbc8f": "darkseagreen"; + "483d8b": "darkslateblue"; + "2f4f4f": "darkslategray" | "darkslategrey"; + "00ced1": "darkturquoise"; + "9400d3": "darkviolet"; + "ff1493": "deeppink"; + "00bfff": "deepskyblue"; + "696969": "dimgray" | "dimgrey"; + "1e90ff": "dodgerblue"; + "b22222": "firebrick"; + "fffaf0": "floralwhite"; + "228b22": "forestgreen"; + "f0f": "fuchsia" | "magenta"; + "dcdcdc": "gainsboro"; + "f8f8ff": "ghostwhite"; + "ffd700": "gold"; + "daa520": "goldenrod"; + "808080": "gray" | "grey"; + "008000": "green"; + "adff2f": "greenyellow"; + "f0fff0": "honeydew"; + "ff69b4": "hotpink"; + "cd5c5c": "indianred"; + "4b0082": "indigo"; + "fffff0": "ivory"; + "f0e68c": "khaki"; + "e6e6fa": "lavender"; + "fff0f5": "lavenderblush"; + "7cfc00": "lawngreen"; + "fffacd": "lemonchiffon"; + "add8e6": "lightblue"; + "f08080": "lightcoral"; + "e0ffff": "lightcyan"; + "fafad2": "lightgoldenrodyellow"; + "d3d3d3": "lightgray" | "lightgrey"; + "90ee90": "lightgreen"; + "ffb6c1": "lightpink"; + "ffa07a": "lightsalmon"; + "20b2aa": "lightseagreen"; + "87cefa": "lightskyblue"; + "789": "lightslategray" | "lightslategrey"; + "b0c4de": "lightsteelblue"; + "ffffe0": "lightyellow"; + "0f0": "lime"; + "32cd32": "limegreen"; + "faf0e6": "linen"; + "800000": "maroon"; + "66cdaa": "mediumaquamarine"; + "0000cd": "mediumblue"; + "ba55d3": "mediumorchid"; + "9370db": "mediumpurple"; + "3cb371": "mediumseagreen"; + "7b68ee": "mediumslateblue"; + "00fa9a": "mediumspringgreen"; + "48d1cc": "mediumturquoise"; + "c71585": "mediumvioletred"; + "191970": "midnightblue"; + "f5fffa": "mintcream"; + "ffe4e1": "mistyrose"; + "ffe4b5": "moccasin"; + "ffdead": "navajowhite"; + "000080": "navy"; + "fdf5e6": "oldlace"; + "808000": "olive"; + "6b8e23": "olivedrab"; + "ffa500": "orange"; + "ff4500": "orangered"; + "da70d6": "orchid"; + "eee8aa": "palegoldenrod"; + "98fb98": "palegreen"; + "afeeee": "paleturquoise"; + "db7093": "palevioletred"; + "ffefd5": "papayawhip"; + "ffdab9": "peachpuff"; + "cd853f": "peru"; + "ffc0cb": "pink"; + "dda0dd": "plum"; + "b0e0e6": "powderblue"; + "800080": "purple"; + "663399": "rebeccapurple"; + "f00": "red"; + "bc8f8f": "rosybrown"; + "4169e1": "royalblue"; + "8b4513": "saddlebrown"; + "fa8072": "salmon"; + "f4a460": "sandybrown"; + "2e8b57": "seagreen"; + "fff5ee": "seashell"; + "a0522d": "sienna"; + "c0c0c0": "silver"; + "87ceeb": "skyblue"; + "6a5acd": "slateblue"; + "708090": "slategray" | "slategrey"; + "fffafa": "snow"; + "00ff7f": "springgreen"; + "4682b4": "steelblue"; + "d2b48c": "tan"; + "008080": "teal"; + "d8bfd8": "thistle"; + "ff6347": "tomato"; + "40e0d0": "turquoise"; + "ee82ee": "violet"; + "f5deb3": "wheat"; + "fff": "white"; + "f5f5f5": "whitesmoke"; + "ff0": "yellow"; + "9acd32": "yellowgreen"; + }; + } - /** - * Returns the input passed into the constructer used to create the tinycolor instance. - */ - getOriginalInput(): any; // any of the interfaces in ColorFormats or a string + interface Instance { + /** + * Return an indication whether the color's perceived brightness is dark. + */ + isDark(): boolean; - /** - * Returns the alpha value of the color - */ - getAlpha(): number; + /** + * Return an indication whether the color's perceived brightness is light. + */ + isLight(): boolean; - /** - * Returns the perceived brightness of the color, from 0-255. - */ - getBrightness(): number; + /** + * Return an indication whether the color was successfully parsed. + */ + isValid(): boolean; - /** - * Returns the perceived luminance of a color, from 0-1. - */ - getLuminance(): number; + /** + * Returns the input passed into the constructer used to create the tinycolor instance. + */ + getOriginalInput(): ColorInput; - /** - * Sets the alpha value on the current color. - * - * @param alpha - The new alpha value. The accepted range is 0-1. - */ - setAlpha(alpha: number): tinycolorInstance; + /** + * Returns the format used to create the tinycolor instance. + */ + getFormat(): string; - /** - * Returns the object as a HSVA object. - */ - toHsv(): ColorFormats.HSVA; + /** + * Returns the alpha value of the color + */ + getAlpha(): number; - /** - * Returns the hsva values interpolated into a string with the following format: - * "hsva(xxx, xxx, xxx, xx)". - */ - toHsvString(): string; + /** + * Returns the perceived brightness of the color, from 0-255. + */ + getBrightness(): number; - /** - * Returns the object as a HSLA object. - */ - toHsl(): ColorFormats.HSLA; + /** + * Returns the perceived luminance of a color, from 0-1. + */ + getLuminance(): number; - /** - * Returns the hsla values interpolated into a string with the following format: - * "hsla(xxx, xxx, xxx, xx)". - */ - toHslString(): string; + /** + * Sets the alpha value on the current color. + * + * @param alpha - The new alpha value. The accepted range is 0-1. + */ + setAlpha(alpha: number): Instance; - /** - * Returns the hex value of the color. - */ - toHex(): string; + /** + * Returns the object as a HSVA object. + */ + toHsv(): ColorFormats.HSVA; - /** - * Returns the hex value of the color -with a # appened. - */ - toHexString(): string; + /** + * Returns the hsva values interpolated into a string with the following format: + * "hsva(xxx, xxx, xxx, xx)". + */ + toHsvString(): string; - /** - * Returns the hex 8 value of the color. - */ - toHex8(): string; + /** + * Returns the object as a HSLA object. + */ + toHsl(): ColorFormats.HSLA; - /** - * Returns the hex 8 value of the color -with a # appened. - */ - toHex8String(): string; + /** + * Returns the hsla values interpolated into a string with the following format: + * "hsla(xxx, xxx, xxx, xx)". + */ + toHslString(): string; - /** - * Returns the object as a RGBA object. - */ - toRgb(): ColorFormats.RGBA; + /** + * Returns the hex value of the color. + */ + toHex(): string; - /** - * Returns the RGBA values interpolated into a string with the following format: - * "RGBA(xxx, xxx, xxx, xx)". - */ - toRgbString(): string; + /** + * Returns the hex value of the color -with a # appened. + */ + toHexString(): string; - /** - * Returns the object as a RGBA object. - */ - toPercentageRgb(): ColorFormats.RGBA; + /** + * Returns the hex 8 value of the color. + */ + toHex8(): string; - /** - * Returns the RGBA relative values interpolated into a string with the following format: - * "RGBA(xxx, xxx, xxx, xx)". - */ - toPercentageRgbString(): string; + /** + * Returns the hex 8 value of the color -with a # appened. + */ + toHex8String(): string; - /** - * The 'real' name of the color -if there is one. - */ - toName(): string; + /** + * Returns the object as a RGBA object. + */ + toRgb(): ColorFormats.RGBA; - /** - * Returns the color represented as a Microsoft filter for use in old versions of IE. - */ - toFilter(): string; + /** + * Returns the RGBA values interpolated into a string with the following format: + * "RGBA(xxx, xxx, xxx, xx)". + */ + toRgbString(): string; - /** - * String representation of the color. - * - * @param format - The format to be used when displaying the string representation. - * The accepted values are: "rgb", "prgb", "hex6", "hex3", "hex8", "name", "hsl", "hsv". - */ - toString(format?: string): string; + /** + * Returns the object as a RGBA object. + */ + toPercentageRgb(): ColorFormats.PRGBA; - /** - * Lighten the color a given amount. Providing 100 will always return white. - * - * @param amount - The amount to lighten by. The valid range is 0 to 100. - * Default value: 10. - */ - lighten(amount?: number): tinycolorInstance; + /** + * Returns the RGBA relative values interpolated into a string with the following format: + * "RGBA(xxx, xxx, xxx, xx)". + */ + toPercentageRgbString(): string; - /** - * Brighten the color a given amount. - * - * @param amount - The amount to brighten by. The valid range is 0 to 100. - * Default value: 10. - */ - brighten(amount?: number): tinycolorInstance; + /** + * The 'real' name of the color -if there is one. + */ + toName(): string | false; - /** - * Darken the color a given amount. - * Providing 100 will always return black. - * - * @param amount - The amount to darken by. The valid range is 0 to 100. - * Default value: 10. - */ - darken(amount?: number): tinycolorInstance; - /** - * Desaturate the color a given amount. - * Providing 100 will is the same as calling greyscale. - * - * @param amount - The amount to desaturate by. The valid range is 0 to 100. - * Default value: 10. - */ - desaturate(amount?: number): tinycolorInstance; + /** + * Returns the color represented as a Microsoft filter for use in old versions of IE. + */ + toFilter(): string; - /** - * Saturate the color a given amount. - * - * @param amount - The amount to saturate by. The valid range is 0 to 100. - * Default value: 10. - */ - saturate(amount?: number): tinycolorInstance; + /** + * String representation of the color. + * + * @param format - The format to be used when displaying the string representation. + * The accepted values are: "rgb", "prgb", "hex6", "hex3", "hex8", "name", "hsl", "hsv". + */ + toString(format?: "rgb" | "prgb" | "hex" | "hex6" | "hex3" | "hex4" | "hex8" | "name" | "hsl" | "hsv"): string; - /** - * Completely desaturates a color into greyscale. - * Same as calling desaturate(100). - */ - greyscale(): tinycolorInstance; + /** + * Gets a new instance with the current color + */ + clone(): Instance; - /** - * Spin the hue a given amount. Calling with 0, 360, or -360 will do nothing. - * - * @param amount - The amount to spin by. The valid range is -360 to 360. - * Default value: 0. - */ - spin(amount?: number): tinycolorInstance; + /** + * Lighten the color a given amount. Providing 100 will always return white. + * + * @param amount - The amount to lighten by. The valid range is 0 to 100. + * Default value: 10. + */ + lighten(amount?: number): Instance; - /** - * Gets an analogous color scheme based off of the current color. - * - * @param results - The amount of results to return. - * Default value: 6. - * @param slices - The amount to slice the input color by. - * Default value: 30. - */ - analogous(results?: number, slices?: number): tinycolorInstance[]; + /** + * Brighten the color a given amount. + * + * @param amount - The amount to brighten by. The valid range is 0 to 100. + * Default value: 10. + */ + brighten(amount?: number): Instance; - /** - * Gets a monochromatic color scheme based off of the current color. - * - * @param results - The amount of results to return. - * Default value: 6. - */ - monochromatic(results?: number): tinycolorInstance[]; + /** + * Darken the color a given amount. + * Providing 100 will always return black. + * + * @param amount - The amount to darken by. The valid range is 0 to 100. + * Default value: 10. + */ + darken(amount?: number): Instance; + /** + * Desaturate the color a given amount. + * Providing 100 will is the same as calling greyscale. + * + * @param amount - The amount to desaturate by. The valid range is 0 to 100. + * Default value: 10. + */ + desaturate(amount?: number): Instance; - /** - * Gets a split complement color scheme based off of the current color. - */ - splitcomplement(): tinycolorInstance[]; + /** + * Saturate the color a given amount. + * + * @param amount - The amount to saturate by. The valid range is 0 to 100. + * Default value: 10. + */ + saturate(amount?: number): Instance; - /** - * Gets a triad based off of the current color. - */ - triad(): tinycolorInstance[]; + /** + * Completely desaturates a color into greyscale. + * Same as calling desaturate(100). + */ + greyscale(): Instance; - /** - * Gets a tetrad based off of the current color. - */ - tetrad(): tinycolorInstance[]; + /** + * Spin the hue a given amount. Calling with 0, 360, or -360 will do nothing. + * + * @param amount - The amount to spin by. The valid range is -360 to 360. + */ + spin(amount: number): Instance; - /** - * Gets the complement of the current color - */ - complement(): tinycolorInstance; + /** + * Gets an analogous color scheme based off of the current color. + * + * @param results - The amount of results to return. + * Default value: 6. + * @param slices - The amount to slice the input color by. + * Default value: 30. + */ + analogous(results?: number, slices?: number): Instance[]; - /** - * Gets a new instance with the current color - */ - clone(): tinycolorInstance; -} + /** + * Gets the complement of the current color + */ + complement(): Instance; -declare namespace Readable { - interface Readable { - brightness: number; - color: number; + /** + * Gets a monochromatic color scheme based off of the current color. + * + * @param results - The amount of results to return. + * Default value: 6. + */ + monochromatic(results?: number): Instance[]; + + /** + * Gets a split complement color scheme based off of the current color. + */ + splitcomplement(): [Instance, Instance, Instance]; + + /** + * Gets a triad based off of the current color. + */ + triad(): [Instance, Instance, Instance]; + + /** + * Gets a tetrad based off of the current color. + */ + tetrad(): [Instance, Instance, Instance, Instance]; } } -declare namespace ColorFormats { - interface RGB { - r: number; - g: number; - b: number; - } - - interface RGBA extends RGB { - a: number - } - - interface HSL { - h: number; - s: number; - l: number; - } - - interface HSLA extends HSL { - a: number; - } - - interface HSV { - h: number; - s: number; - v: number; - } - - interface HSVA extends HSV { - a: number; - } -} - -type ColorInput = string | ColorFormats.RGB | ColorFormats.RGBA | ColorFormats.HSL | ColorFormats.HSLA | ColorFormats.HSV | ColorFormats.HSVA | tinycolorInstance - -declare module 'tinycolor2' { - export = tinycolor; -} \ No newline at end of file +declare const tinycolor: tinycolor.Constructor; +export = tinycolor; +export as namespace tinycolor; diff --git a/types/tinycolor2/tinycolor2-tests.ts b/types/tinycolor2/tinycolor2-tests.ts index f6a6634f5f..96eb31ed23 100644 --- a/types/tinycolor2/tinycolor2-tests.ts +++ b/types/tinycolor2/tinycolor2-tests.ts @@ -1,126 +1,200 @@ - - /* * Not all possible formats for construction are displayed. * To see a complete list please view: https://github.com/bgrins/TinyColor */ -var tester: tinycolorInstance = tinycolor("red"); +const testColor: tinycolor.Instance = tinycolor("red"); /* Constructor Tests*/ // string -tester = tinycolor("#ffffff"); +// $ExpectType Instance +tinycolor("#ffffff"); -//rgb && rgba -tester = tinycolor({ r: 40, g: 30, b: 20 }); -tester = tinycolor({ r: 255, g: 20, b: 10, a: 0 }); -tester = tinycolor.fromRatio({ r: 0.5, g: 0.2, b: 1, a: 0 }); -tester = tinycolor.fromRatio({ r: 1, g: 0, b: 0.7, a: 0 }); +// rgb && rgba +// $ExpectType Instance +tinycolor({ r: 40, g: 30, b: 20 }); +// $ExpectType Instance +tinycolor({ r: 255, g: 20, b: 10, a: 0 }); +// $ExpectType Instance +tinycolor.fromRatio({ r: 0.5, g: 0.2, b: 1, a: 0 }); +// $ExpectType Instance +tinycolor.fromRatio({ r: 1, g: 0, b: 0.7, a: 0 }); -//hsl && hsla -tester = tinycolor({ h: 0, s: 0, l: 0 }); -tester = tinycolor({ h: 0, s: 0, l: 0, a: 0 }); -tester = tinycolor.fromRatio({ h: 0.5, s: 0.2, l: 1, a: 0 }); +// hsl && hsla +// $ExpectType Instance +tinycolor({ h: 0, s: 0, l: 0 }); +// $ExpectType Instance +tinycolor({ h: 0, s: 0, l: 0, a: 0 }); +// $ExpectType Instance +tinycolor.fromRatio({ h: 0.5, s: 0.2, l: 1, a: 0 }); -//hsv && hsva -tester = tinycolor({ h: 0, s: 0, v: 0 }); -tester = tinycolor({ h: 0, s: 0, v: 0, a: 0 }); +// hsv && hsva +// $ExpectType Instance +tinycolor({ h: 0, s: 0, v: 0 }); +// $ExpectType Instance +tinycolor({ h: 0, s: 0, v: 0, a: 0 }); -//tinycolor static methods -tester = tinycolor.mix(tester, tester); -tester = tinycolor.mix("#ff0000", "#00ff00"); -tester = tinycolor.mix(tester, tester, 50); -tester = tinycolor.random(); -var isEqual = tinycolor.equals(tester, tester); +// tinycolor static methods +// $ExpectType Instance +tinycolor.mix(testColor, testColor); +// $ExpectType Instance +tinycolor.mix("#ff0000", "#00ff00"); +// $ExpectType Instance +tinycolor.mix(testColor, testColor, 50); +// $ExpectType Instance +tinycolor.random(); -/*Tinycolor object properties*/ +// $ExpectType boolean +tinycolor.equals(testColor, testColor); -var readable: Readable.Readable = tinycolor.readability(tester, tester); -var isReadable: boolean = tinycolor.isReadable(tester, tester); -var isReadable: boolean = tinycolor.isReadable(tester, tester, {size: "small"}); -tester = tinycolor.mostReadable(tester, [tester, tester, tester]); -tester = tinycolor.mostReadable(tester, [tester, tester, tester], {size: "large", level:"AA"}); +// $ExpectType number +tinycolor.readability(testColor, testColor); +// $ExpectType boolean +tinycolor.isReadable(testColor, testColor); +// $ExpectType boolean +tinycolor.isReadable(testColor, testColor, {size: "small"}); +// $ExpectType Instance +tinycolor.mostReadable(testColor, [testColor, testColor, testColor]); +// $ExpectType Instance +tinycolor.mostReadable(testColor, [testColor, testColor, testColor], {size: "large", level: "AA"}); -var hexNames: { [key: string]: string } = tinycolor.hexNames; -var names: { [key: string]: string } = tinycolor.names; +const hexNames: { [key: string]: string } = tinycolor.hexNames; +const names: { [key: string]: string } = tinycolor.names; +// $ExpectType "linen" +tinycolor.hexNames["faf0e6"]; +// $ExpectType "yellow" +tinycolor.hexNames["ff0"]; +// $ExpectType "f0f8ff" +tinycolor.names["aliceblue"]; +// $ExpectType "808080" +tinycolor.names["gray"]; -/*Instance Methods*/ +/* Instance Methods */ -//check properties -var isValid: boolean = tester.isValid(); -var isLight: boolean = tester.isLight(); -var isDark: boolean = tester.isDark(); +// check properties +// $ExpectType boolean +testColor.isValid(); +// $ExpectType boolean +testColor.isLight(); +// $ExpectType boolean +testColor.isDark(); -//get properties -var alpha: number = tester.getAlpha(); -var brightness: number = tester.getBrightness(); -var format: string = tester.getFormat(); -var originalInput: any = tester.getOriginalInput(); +// get properties +const alpha: number = testColor.getAlpha(); +// $ExpectType number +testColor.getBrightness(); +// $ExpectType string +testColor.getFormat(); +// $ExpectType ColorInput +testColor.getOriginalInput(); -//set properties -tester = tester.setAlpha(alpha); +// set properties +// $ExpectType Instance +testColor.setAlpha(alpha); -//representations -var hsva: ColorFormats.HSVA = tester.toHsv(); -var hsvString: string = tester.toHsvString(); +// representations +// $ExpectType HSVA +testColor.toHsv(); +// $ExpectType string +testColor.toHsvString(); -var hsl: ColorFormats.HSLA = tester.toHsl(); -var hslString: string = tester.toHslString(); +// $ExpectType HSLA +testColor.toHsl(); +// $ExpectType string +testColor.toHslString(); -var hex: string = tester.toHex(); -var hexString: string = tester.toHexString(); +// $ExpectType string +testColor.toHex(); +// $ExpectType string +testColor.toHexString(); -var hex8: string = tester.toHex8(); -var hex8String: string = tester.toHex8String(); +// $ExpectType string +testColor.toHex8(); +// $ExpectType string +testColor.toHex8String(); -var rgba: ColorFormats.RGBA = tester.toRgb(); -var rgbString: string = tester.toString(); +// $ExpectType RGBA +testColor.toRgb(); +// $ExpectType string +testColor.toString(); -var percentageRGBA: ColorFormats.RGBA = tester.toPercentageRgb(); -var percentageRGBString: string = tester.toPercentageRgbString(); +// $ExpectType PRGBA +testColor.toPercentageRgb(); +// $ExpectType string +testColor.toPercentageRgbString(); -var name_: string = tester.toName(); -var filter: string = tester.toFilter(); -var sString: string = tester.toString(); -sString = tester.toString("rgb"); -sString = tester.toString("prgb"); -sString = tester.toString("hex6"); -sString = tester.toString("hex3"); -sString = tester.toString("hex8"); -sString = tester.toString("name"); -sString = tester.toString("hsl"); -sString = tester.toString("hsv"); +// $ExpectType string | false +testColor.toName(); +// $ExpectType string +testColor.toFilter(); +// $ExpectType string +testColor.toString(); +// $ExpectType string +testColor.toString("rgb"); +// $ExpectType string +testColor.toString("prgb"); +// $ExpectType string +testColor.toString("hex6"); +// $ExpectType string +testColor.toString("hex3"); +// $ExpectType string +testColor.toString("hex8"); +// $ExpectType string +testColor.toString("name"); +// $ExpectType string +testColor.toString("hsl"); +// $ExpectType string +testColor.toString("hsv"); -//color modifications -tester = tester.lighten(); -tester = tester.lighten(20); +// color modifications +// $ExpectType Instance +testColor.lighten(); +// $ExpectType Instance +testColor.lighten(20); -tester = tester.brighten(); -tester = tester.brighten(20); +// $ExpectType Instance +testColor.brighten(); +// $ExpectType Instance +testColor.brighten(20); -tester = tester.darken(); -tester = tester.darken(20); +// $ExpectType Instance +testColor.darken(); +// $ExpectType Instance +testColor.darken(20); -tester = tester.desaturate(); -tester = tester.desaturate(20); +// $ExpectType Instance +testColor.desaturate(); +// $ExpectType Instance +testColor.desaturate(20); -tester = tester.saturate(); -tester = tester.saturate(20); +// $ExpectType Instance +testColor.saturate(); +// $ExpectType Instance +testColor.saturate(20); -tester = tester.spin(); -tester = tester.spin(20); +// $ExpectType Instance +testColor.spin(20); -tester = tester.greyscale(); +// $ExpectType Instance +testColor.greyscale(); -//color combinations -var colors: tinycolorInstance[] = tester.analogous(); -colors = tester.analogous(6, 30); +// color combinations +// $ExpectType Instance[] +testColor.analogous(); +// $ExpectType Instance[] +testColor.analogous(6, 30); -colors = tester.monochromatic(); -colors = tester.monochromatic(10); +// $ExpectType Instance[] +testColor.monochromatic(); +// $ExpectType Instance[] +testColor.monochromatic(10); -colors = tester.splitcomplement(); -colors = tester.triad(); -colors = tester.tetrad(); +// $ExpectType [Instance, Instance, Instance] +testColor.splitcomplement(); +// $ExpectType [Instance, Instance, Instance] +testColor.triad(); +// $ExpectType [Instance, Instance, Instance, Instance] +testColor.tetrad(); -tester = tester.complement(); \ No newline at end of file +// $ExpectType Instance +testColor.complement(); diff --git a/types/tinycolor2/tslint.json b/types/tinycolor2/tslint.json index a41bf5d19a..64aace11d6 100644 --- a/types/tinycolor2/tslint.json +++ b/types/tinycolor2/tslint.json @@ -1,79 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "max-line-length": false } } diff --git a/types/twit/index.d.ts b/types/twit/index.d.ts index 9918d58470..ce8484bbe1 100644 --- a/types/twit/index.d.ts +++ b/types/twit/index.d.ts @@ -4,6 +4,7 @@ // sapphiredev // abraham // siwalik +// plhery // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -271,6 +272,8 @@ declare module 'twit' { include_rts?: boolean, skip_status?: boolean, url?: string, + include_user_entities?: boolean, + stringify_ids?: boolean, } export interface PromiseResponse { data: Response, diff --git a/types/umzug/index.d.ts b/types/umzug/index.d.ts index f74c5933be..a163ea01d9 100644 --- a/types/umzug/index.d.ts +++ b/types/umzug/index.d.ts @@ -1,13 +1,15 @@ -// Type definitions for Umzug v2.1.0 +// Type definitions for Umzug v2.2.0 // Project: https://github.com/sequelize/umzug // Definitions by: Ivan Drinchev // Margus Lamp // Troy McKinnon +// Emmanuel Gautier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { EventEmitter } from 'events'; import Sequelize = require("sequelize"); +import MongoDB = require("mongodb"); declare namespace umzug { @@ -116,6 +118,27 @@ declare namespace umzug { } + interface MongoDBStorageOptions extends Storage { + + /** + * The MongoDB database connection instance. + */ + connection?: MongoDB.Db; + + /** + * The to be used Mongo collection cursor. + * Defaults to collection created from collectionName attribute. + */ + collection?: MongoDB.Collection; + + /** + * The name of the collection used by the connection. + * Defaults to 'migrations' + */ + collectionName?: string; + + } + interface ExecuteOptions { migrations?: Array; method?: string; @@ -125,12 +148,12 @@ declare namespace umzug { /** * The storage. */ - storage?: "json" | "sequelize" | Storage; + storage?: "json" | "sequelize" | "mongodb" | Storage; /** * The options for the storage. */ - storageOptions?: JSONStorageOptions | SequelizeStorageOptions | Object; + storageOptions?: JSONStorageOptions | SequelizeStorageOptions | MongoDBStorageOptions | Object; /** * The logging function. diff --git a/types/umzug/umzug-tests.ts b/types/umzug/umzug-tests.ts index 95ccf15665..730f350315 100644 --- a/types/umzug/umzug-tests.ts +++ b/types/umzug/umzug-tests.ts @@ -1,5 +1,6 @@ import Umzug = require('umzug'); import Sequelize = require('sequelize'); +import MongoDB = require('mongodb'); let someVar: Umzug.Umzug; const umzug = new Umzug({}); @@ -44,7 +45,7 @@ umzug.on('reverted', (name: string, migration: Umzug.Migration) => null); new Umzug({ // The storage. - // Possible values: 'json', 'sequelize', an object + // Possible values: 'json', 'sequelize', 'mongodb' an object storage: 'json', // The options for the storage. @@ -80,7 +81,7 @@ new Umzug({ new Umzug({ // The storage. - // Possible values: 'json', 'sequelize', an object + // Possible values: 'json', 'sequelize', 'mongodb' an object storage: 'json', storageOptions: { path: '/db/sequelize-meta.json', @@ -121,3 +122,30 @@ new Umzug({ }, }); + +const mongodb = new MongoDB.Db('database', new MongoDB.Server('host', 21017)); + +new Umzug({ + // The storage. + // Possible values: 'json', 'sequelize', 'mongodb' an object + storage: 'mongodb', + storageOptions: { + /** + * The MongoDB database connection instance. + */ + connection: mongodb, + + /** + * The to be used Mongo collection cursor. + * Defaults to collection created from collectionName attribute. + */ + collection: mongodb.collection, + + /** + * The name of the collection used by the connection. + * Defaults to 'migrations' + */ + collectionName: 'migrations' + }, + +}); diff --git a/types/uri-templates/index.d.ts b/types/uri-templates/index.d.ts index ad8cead946..d378de8a4f 100644 --- a/types/uri-templates/index.d.ts +++ b/types/uri-templates/index.d.ts @@ -1,16 +1,19 @@ -// Type definitions for uri-templates 0.1.2 +// Type definitions for uri-templates 0.1.9 // Project: https://github.com/geraintluff/uri-templates // Definitions by: Bart van der Schoor +// Bartek Szczepański // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare function utpl(template: string): utpl.URITemplate; declare namespace utpl { export interface URITemplate { - fillFromObject(vars: Object): string; + fillFromObject(vars: { [key: string]: string }): string; fill(callback: (varName: string) => string): string; - fromUri(uri: string): Object; + fill(vars: { [key: string]: string }): string; + fromUri(uri: string): { [key: string]: string }; + varNames: string[]; + template: string; } } diff --git a/types/uri-templates/uri-templates-tests.ts b/types/uri-templates/uri-templates-tests.ts index 0aeb5e0bfe..d29b801de1 100644 --- a/types/uri-templates/uri-templates-tests.ts +++ b/types/uri-templates/uri-templates-tests.ts @@ -1,15 +1,23 @@ - import utmpl = require('uri-templates'); import URITemplate = utmpl.URITemplate; -var str: string; -var u: URITemplate; -var obj: Object; +let str: string; +let u: URITemplate; +const obj = { test: 'test1' }; u = utmpl(str); str = u.fillFromObject(obj); -str = u.fill((key) => { - return str; +str = u.fill(key => { + return str; }); -obj = u.fromUri(str); +str = u.fill(obj); +const newObj = u.fromUri(str); + +let varNames: string[]; + +varNames = u.varNames; + +let template: string; + +template = u.template; diff --git a/types/url-regex/index.d.ts b/types/url-regex/index.d.ts index ed51c6e34d..58f3793baa 100644 --- a/types/url-regex/index.d.ts +++ b/types/url-regex/index.d.ts @@ -1,12 +1,15 @@ -// Type definitions for url-regex 4.0 +// Type definitions for url-regex 4.1 // Project: https://github.com/kevva/url-regex // Definitions by: Daniel Perez Alvarez +// sosukesuzuki // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** Regular expression for matching URLs. */ declare function urlRegex(options?: { /** Only match an exact string. Useful with RegExp#test to check if a string is a URL. */ exact?: boolean; + /** Force URLs to start with a valid protocol or www. If set to false it'll match the TLD against a list of valid TLDs(https://github.com/stephenmathieson/node-tlds). */ + strict?: boolean; }): RegExp; export = urlRegex; diff --git a/types/url-regex/url-regex-tests.ts b/types/url-regex/url-regex-tests.ts index 2a2db45a28..de62d9a796 100644 --- a/types/url-regex/url-regex-tests.ts +++ b/types/url-regex/url-regex-tests.ts @@ -8,4 +8,6 @@ urlRegex({exact: true}).test('https://github.com foo bar'); urlRegex({exact: true}).test('https://github.com'); +urlRegex({exact: true, strict: false}).test('github.com'); + 'foo https://github.com bar //google.com'.match(urlRegex()); diff --git a/types/vexflow/index.d.ts b/types/vexflow/index.d.ts index 714cfe5c0a..c25ac00958 100644 --- a/types/vexflow/index.d.ts +++ b/types/vexflow/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for VexFlow v1.2.84 +// Type definitions for VexFlow v1.2.85 // Project: http://vexflow.com // Definitions by: Roman Quiring // Sebastian Haas // Basti Hoffmann +// Simon Schmid // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped //inconsistent namespace: this is a helper funtion from tables.js and should not pollute the global namespace! @@ -553,6 +554,7 @@ declare namespace Vex { setYShift(y : number) : Modifier; setXShift(x : number) : void; //inconsistent type: void -> Modifier draw() : void; + alignSubNotesWithNote(subNotes : Note[], note : Note) : void; } namespace Modifier { @@ -690,6 +692,11 @@ declare namespace Vex { draw() : void; } + class NoteSubGroup extends Modifier { + constructor(subnotes : Note[]); + preFormat() : void; + } + class Ornament extends Modifier { constructor(type : string); static DEBUG : boolean; @@ -1295,6 +1302,10 @@ declare namespace Vex { getWidth() : number; getX() : number; setX(x : number) : TickContext; + getXBase() : number; + setXBase(xBase : number) : void; + getXOffset() : number; + setXOffset(xOffset : number) : void; getPixelsUsed() : number; setPixelsUsed(pixelsUsed : number) : TickContext; setPadding(padding : number) : TickContext; diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index f18ff8890e..3d432fb9b3 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Video.js 6.2 +// Type definitions for Video.js 7.0 // Project: https://github.com/videojs/video.js // Definitions by: Vincent Bortone // Simon Clériot @@ -15,285 +15,6629 @@ // Javascript, whether the browser is playing the video through HTML5 // video, Flash, or any other supported playback technologies. -declare function videojs( - id: any, - options?: videojs.PlayerOptions, - ready?: () => void -): videojs.Player; -export default videojs; +/** + * Doubles as the main function for users to create a inplayer instance and also + * the main library object. + * The `videojs` function can be used to initialize or retrieve a player. + * + * @param id + * Video element or video element ID + * + * @param [options] + * Optional options object for config/settings + * + * @param [ready] + * Optional ready callback + * + * @return A player instance + */ +declare function videojs(id: any, options?: videojs.PlayerOptions, ready?: () => void): videojs.Player; +export = videojs; export as namespace videojs; declare namespace videojs { - const getComponent: typeof Component.getComponent; - const registerComponent: typeof Component.registerComponent; - const getPlugin: typeof Plugin.getPlugin; - function registerPlugin( - pluginName: string, - pluginFn: (this: Player, ...parameters: any[]) => void - ): void; - function addLanguage(lang: string, data: { [key: string]: string }): void; - function mergeOptions( - option: A, - option2?: B, - option3?: C, - option4?: D, - option5?: E, - option6?: F - ): A & B & C & D & E & F; + /** + * Adding languages so that they're available to all players. + * Example: `addLanguage('es', { 'Hello': 'Hola' });` + * + * @param code + * The language code or dictionary property + * + * @param data + * The data values to be translated + * + * @return The resulting language dictionary object + */ + function addLanguage(code: string, data: LanguageTranslations): LanguageTranslations; - interface PlayerOptions { - aspectRatio?: string; - autoplay?: boolean; - autoSetup?: boolean; - children?: string[]; - controlBar?: { - volumePanel?: { - inline?: boolean; - vertical?: boolean; - }; - }; - controls?: boolean; - defaultVolume?: number; - fluid?: boolean; - height?: number; - html5?: any; - inactivityTimeout?: number; - language?: string; - languages?: { [key: string]: string }; - loop?: boolean; - muted?: boolean; - nativeControlsForTouch?: boolean; - notSupportedMessage?: string; - playbackRates?: number[]; - plugins?: any; - poster?: string; - preload?: string; - sourceOrder?: boolean; - sources?: Source[]; - src?: string; - techCanOverridePoster?: boolean; - techOrder?: string[]; - width?: number; - } + /** + * Bind (a.k.a proxy or Context). A simple method for changing the context of a function + * It also stores a unique id on the function so it can be easily removed from events. + * + * @param context + * The object to bind as scope. + * + * @param fn + * The function to be bound to a scope. + * + * @param [uid] + * An optional unique ID for the function to be set + * + * @return The new function that will be bound into the context given + */ + function bind any)>(context: any, fn: F, uid?: number): F; - interface Source { - type: string; - src: string; - } + /** + * Should create a fake `TimeRange` object which mimics an HTML5 time range instance. + * + * @param start + * The start of a single range or an array of ranges + * + * @param end + * The end of a single range. + */ + function createTimeRanges(start?: number | TimeRange[], end?: number): TimeRange; - interface Dimensions { - width: number; - height: number; - } + /** + * A suite of browser and device tests from {@link browser}. + * + */ + const browser: Browser; - class EventTarget { - addEventListener( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - dispatchEvent(event: string | Event | { [key: string]: any }): void; - off( - type?: string | string[], - callback?: (eventObject: Event) => void - ): void; - on( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - one( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - removeEventListener( - type?: string | string[], - callback?: (eventObject: Event) => void - ): void; - trigger(event: string | Event | { [key: string]: any }): void; - } + const dom: Dom; - class Component extends EventTarget { - constructor(player: Player, options: any); + /** + * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in seconds) + * will force a number of leading zeros to cover the length of the guide. + * + * @param seconds + * Number of seconds to be turned into a string + * + * @param guide + * Number (in seconds) to model the string after + * + * @return Time formatted as H:MM:SS or M:SS + */ + function formatTime(seconds: number, guide: number): string; - static getComponent(name: "Player" | "player"): typeof Player; - static getComponent(name: "Button" | "button"): typeof Button; - static getComponent( - name: "ClickableComponent" | "clickablecomponent" - ): typeof ClickableComponent; - static getComponent( - name: "ModalDialog" | "modaldialog" - ): typeof ModalDialog; - static getComponent( - name: "ControlBar" | "controlbar" - ): typeof ControlBar; - static getComponent( - name: "Component" | "component" | string - ): typeof Component; - static registerComponent( - name: string, - ComponentToRegister: typeof Component - ): typeof Component; + /** + * Returns an array of all current players. + * + * @return An array of all players. The array will be in the order that + * `Object.keys` provides, which could potentially vary between + * JavaScript engines. + * + */ + function getAllPlayers(): Player[]; - $(selector: string, context?: string | Element): Element; - $$(selector: string, context?: string | Element): NodeList; - addChild( - component: string, - optionsopt?: any, - indexopt?: number - ): Component; - addChild( - component: Element, - optionsopt?: any, - indexopt?: number - ): Element; - addChild( - component: T, - optionsopt?: any, - indexopt?: number - ): T; - addClass(classToAdd: string): void; - blur(): void; - buildCSSClass(): string; - cancelAnimationFrame(id: number): number; - children(): Component[]; - controlText(key: string): string; - clearInterval(intervalId: number): number; - clearTimeout(timeoutId: number): number; - contentEl(): Element; - createEl( - tagNameopt?: string, - properties?: any, - attributes?: any - ): Element; - currentDimension(widthOrHeight: "width" | "height"): number; - currentDimensions(): Dimensions; - currentHeight(): number; - currentWidth(): number; - dimension(widthOrHeight: "width" | "height"): number; - dimension( - widthOrHeight: "width" | "height", - num: string | number, - skipListenersopt?: boolean - ): void; - dimensions(width: string | number, height: string | number): void; - dispose(): void; - el(): Element; - enableTouchActivity(): void; - focus(): void; - getAttribute(attribute: string): string | null; - getChild(name: string): Component | undefined; - getChildById(id: string): Component | undefined; - hasClass(classToCheck: string): boolean; - height(): number | string; - height(num: number | string, skipListeners?: boolean): void; - hide(): void; - id(): string; - initChildren(): void; - localize(key: string, tokens?: string[], defaultValue?: string): string; - name(): string; - options(obj: any): any; - played(): TimeRanges; - player(): Player; - ready(callback: (this: this) => void): this; - removeAttribute(attribute: string): void; - removeChild(component: Component): void; - removeClass(classToRemove: string): void; - requestAnimationFrame(fn: () => void): number; - setAttribute(attribute: string, value: string): void; - setInterval(fn: () => void, interval: number): number; - setTimeout(fn: () => void, timeout: number): number; - show(): void; - toggleClass( - classToToggle: string, - predicate?: - | boolean - | ((element: Element, classToToggle: string) => boolean) - ): void; - trigger(eventName: string, ...parameters: any[]): void; - triggerReady(): void; - width(): string | number; - width(num: number, skipListeners?: number): void; - } + /** + * Get a component class object by name + * + * @borrows Component.getComponent as getComponent + */ + const getComponent: typeof Component.getComponent; - class ControlBar extends Component {} + /** + * Get a single player based on an ID or DOM element. + * + * This is useful if you want to check if an element or ID has an associated + * Video.js player, but not create one if it doesn't. + * + * @param id + * An HTML element - `

  • ` + */ + interface MenuItem extends ClickableComponent { + options_: MenuItemOptions; + + /** + * Create the `MenuItem's DOM element + * + * @param [type=li] + * Element's node type, not actually used, always set to `li`. + * + * @param [props={}] + * An object of properties that should be set on the element + * + * @param [attrs={}] + * An object of attributes that should be set on the element + * + * @return The element that gets created. + */ + createEl(type: string, props?: any, attrs?: any): HTMLLIElement; + + /** + * Any click on a `MenuItem` puts it into the selected state. + * See {@link ClickableComponent#handleClick} for instances where this is called. + * + * @param event + * The `keydown`, `tap`, or `click` event that caused this function to be + * called. + * + * @listens tap + * @listens click + */ + handleClick(event: EventTarget.Event): void; + + /** + * Set the state for this menu item as selected or not. + * + * @param selected + * if the menu item is selected or not + */ + selected(selected: boolean): void; + } + + const MenuItem: { + prototype: MenuItem; + + /** + * Creates an instance of the this class. + * + * @param player + * The `Player` that this class should be attached to. + * + * @param [options={}] + * The key/value store of player options. + * + */ + new (player: Player, options?: MenuItemOptions): MenuItem; + }; + + interface MenuItemOptions extends ComponentOptions { + label?: string; + multiSelectable?: boolean; + selectable?: boolean; + selected?: boolean; + } + + interface Middleware { + /** + * + * @param src + * @param next + */ + setSource: (src: Tech.SourceObject, next: (err: any, next: (src: Tech.SourceObject) => void) => void) => void; + } + + /** + * The `ModalDialog` displays over the video and its controls, which blocks + * interaction with the player until it is closed. + * + * Modal dialogs include a "Close" button and will close when that button + * is activated - or when ESC is pressed anywhere. + */ + interface ModalDialog extends Component { + options_: ModalDialogOptions; + + closeable_: boolean; + + /** + * Builds the default DOM `className`. + * + * @return The DOM `className` for this object. + */ + buildCSSClass(): string; + + /** + * Closes the modal, does nothing if the `ModalDialog` is + * not open. + * + * @fires ModalDialog#beforemodalclose + * @fires ModalDialog#modalclose + */ + close(): void; + + /** + * Check to see if the `ModalDialog` is closeable via the UI. + * + * @param [value] + * If given as a boolean, it will set the `closeable` option. + * + * @return Returns the final value of the closable option. + */ + closeable(value: boolean): boolean; + + /** + * Gets or sets the modal content, which gets normalized before being + * rendered into the DOM. + * + * This does not update the DOM or fill the modal, but it is called during + * that process. + * + * @param [value] + * If defined, sets the internal content value to be used on the + * next call(s) to `fill`. This value is normalized before being + * inserted. To "clear" the internal content value, pass `null`. + * + * @return The current content of the modal dialog + */ + content(value: Content): any; + + /** + * Create the `ModalDialog`'s DOM element + * + * @return The DOM element that gets created. + */ + createEl(): HTMLDivElement; + + /** + * Returns the description string for this modal. Primarily used for + * accessibility. + * + * @return The localized or raw description of this modal. + */ + description(): string; + + dispose(): void; + + /** + * Empties the content element. This happens anytime the modal is filled. + * + * @fires ModalDialog#beforemodalempty + * @fires ModalDialog#modalempty + */ + empty(): void; + + /** + * Fill the modal's content element with the modal's "content" option. + * The content element will be emptied before this change takes place. + */ + fill(): void; + + /** + * Fill the modal's content element with arbitrary content. + * The content element will be emptied before this change takes place. + * + * @fires ModalDialog#beforemodalfill + * @fires ModalDialog#modalfill + * + * @param [content] + * The same rules apply to this as apply to the `content` option. + */ + fillWith(content: Content): void; + + /** + * Keydown handler. Attached when modal is focused. + * + * @listens keydown + */ + handleKeyDown(): void; + + /** + * Handles `keydown` events on the document, looking for ESC, which closes + * the modal. + * + * @param e + * The keypress that triggered this event. + * + * @listens keydown + */ + handleKeyPress(e: EventTarget.Event): void; + + /** + * Returns the label string for this modal. Primarily used for accessibility. + * + * @return the localized or raw label of this modal. + */ + label(): string; + + /** + * Opens the modal. + * + * @fires ModalDialog#beforemodalopen + * @fires ModalDialog#modalopen + */ + open(): void; + + /** + * If the `ModalDialog` is currently open or closed. + * + * @param [value] + * If given, it will open (`true`) or close (`false`) the modal. + * + * @return the current open state of the modaldialog + */ + opened(value?: boolean): boolean; + } + + const ModalDialog: { + prototype: ModalDialog; + + /** + * Create an instance of this class. + * + * @param player + * The `Player` that this class should be attached to. + * + * @param [options] + * The key/value store of player options. + */ + new (player: Player, options?: ModalDialogOptions): ModalDialog; + }; + + /** + * Options for this class + * + * @param [content=undefined] + * Provide customized content for this modal. + * + * @param [description] + * A text description for the modal, primarily for accessibility. + * + * @param [fillAlways=false] + * Normally, modals are automatically filled only the first time + * they open. This tells the modal to refresh its content + * every time it opens. + * + * @param [label] + * A text label for the modal, primarily for accessibility. + * + * @param [temporary=true] + * If `true`, the modal can only be opened once; it will be + * disposed as soon as it's closed. + * + * @param [uncloseable=false] + * If `true`, the user will not be able to close the modal + * through the UI in the normal ways. Programmatic closing is + * still possible. + */ + interface ModalDialogOptions extends ComponentOptions { + content?: any; + description?: string; + fillAlways?: boolean; + label?: string; + temporary?: boolean; + uncloseable?: boolean; + } + + /** + * The {@link MouseTimeDisplay} component tracks mouse movement over the + * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip} + * indicating the time which is represented by a given point in the + * {@link ProgressControl}. + */ + interface MouseTimeDisplay extends Component { + /** + * Create the DOM element for this class. + * + * @return The element that was created. + */ + createEl(): HTMLDivElement; + + /** + * Enqueues updates to its own DOM as well as the DOM of its + * {@link TimeTooltip} child. + * + * @param seekBarRect + * The `ClientRect` for the {@link SeekBar} element. + * + * @param seekBarPoint + * A number from 0 to 1, representing a horizontal reference point + * from the left edge of the {@link SeekBar} + */ + update(seekBarRect: ClientRect, seekBarPoint: number): void; + } + + const MouseTimeDisplay: { + prototype: MouseTimeDisplay; + + /** + * Creates an instance of this class. + * + * @param player + * The {@link Player} that this class should be attached to. + * + * @param [options] + * The key/value store of player options. + */ + new (player: Player, options?: ComponentOptions): MouseTimeDisplay + }; + + /** + * An instance of the `Player` class is created when any of the Video.js setup methods + * are used to initialize a video. + * + * After an instance has been created it can be accessed globally in two ways: + * 1. By calling `videojs('example_video_1');` + * 2. By using it directly via `videojs.players.example_video_1;` + */ + interface Player extends Component { + bigPlayButton: Button; + + controlBar: ControlBar; + + errorDisplay: ModalDialog; + + loadingSpinner: Component; + + options_: PlayerOptions; + + userActivity_: boolean; + + userActive_: boolean; + + /** + * A getter/setter for the `Player`'s aspect ratio. + * + * @param [ratio] + * The value to set the `Player's aspect ratio to. + * + * @return - The current aspect ratio of the `Player` when getting. + * - undefined when setting + */ + aspectRatio(ratio: string): void; + + aspectRatio(): string; + + /** + * Get or set the autoplay option. When this is a boolean it will + * modify the attribute on the tech. When this is a string the attribute on + * the tech will be removed and `Player` will handle autoplay on loadstarts. + * + * @param [value] + * - true: autoplay using the browser behavior + * - false: do not autoplay + * - 'play': call play() on every loadstart + * - 'muted': call muted() then play() on every loadstart + * - 'any': call play() on every loadstart. if that fails call muted() then play(). + * - *: values other than those listed here will be set `autoplay` to true + * + * @return The current value of autoplay when getting + */ + autoplay(value?: boolean): void; + + autoplay(): boolean; + + /** + * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}. It will + * automatically removed from the video element whenever the source changes, unless + * manualCleanup is set to false. + * + * @param options + * Options to pass to {@link HTMLTrackElement} during creation. See + * {@link HTMLTrackElement} for object properties that you should use. + * + * @param [manualCleanup=true] if set to false, the TextTrack will be + * + * @return the HTMLTrackElement that was created and added + * to the HtmlTrackElementList and the remote + * TextTrackList + */ + addRemoteTextTrack(options: TextTrackOptions, manualCleanup: boolean): HTMLTrackElement; + + /** + * A helper method for adding a {@link TextTrack} to our + * {@link TextTrackList}. + * + * In addition to the W3C settings we allow adding additional info through options. + * + * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack + * + * @param [kind] + * the kind of TextTrack you are adding + * + * @param [label] + * the label to give the TextTrack label + * + * @param [language] + * the language to set on the TextTrack + * + * @return the TextTrack that was added or undefined + * if there is no tech + */ + addTextTrack(kind?: string, label?: string, language?: string): void; + + /** + * Get a TimeRange object with an array of the times of the video + * that have been downloaded. If you just want the percent of the + * video that's been downloaded, use bufferedPercent. + * + * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered} + * + * @return A mock TimeRange object (following HTML spec) + */ + buffered(): TimeRange; + + /** + * Get the ending time of the last buffered time range + * This is used in the progress bar to encapsulate all time ranges. + * + * @return The end of the last buffered time range + */ + bufferedEnd(): number; + + /** + * Get the percent (as a decimal) of the video that's been downloaded. + * This method is not a part of the native HTML video API. + * + * @return A decimal between 0 and 1 representing the percent + * that is buffered 0 being 0% and 1 being 100% + */ + bufferedPercent(): number; + + /** + * Check whether the player can play a given mimetype + * + * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype + * + * @param type + * The mimetype to check + * + * @return 'probably', 'maybe', or '' (empty string) + */ + canPlayType(type: string): 'probably' | 'maybe' | ''; + + cancelFullScreen(): Player; + + /** + * Get or set whether or not the controls are showing. + * + * @fires Player#controlsenabled + * + * @param [bool] + * - true to turn controls on + * - false to turn controls off + * + * @return The current value of controls when getting + */ + controls(bool?: boolean): void; + + controls(): boolean; + + /** + * Create the `Player`'s DOM element. + * + * @return The DOM element that gets created. + */ + createEl(): Element; + + /** + * Creates a simple modal dialog (an instance of the {@link ModalDialog} + * component) that immediately overlays the player with arbitrary + * content and removes itself when closed. + * + * @param content + * Same as {@link ModalDialog#content}'s param of the same name. + * The most straight-forward usage is to provide a string or DOM + * element. + * + * @param [options] + * Extra options which will be passed on to the {@link ModalDialog}. + * @check + * @return the {@link ModalDialog} that was created + */ + createModal(content: string | (() => any) | Element | any[], options: any): ModalDialog; + + /** + * Returns the current source object. + * + * @return The current source object + */ + currentSource(): Tech.SourceObject; + + /** + * Returns all of the current source objects. + * + * @return The current source objects + */ + currentSources(): Tech.SourceObject[]; + + /** + * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 + * Can be used in conjunction with `currentType` to assist in rebuilding the current source object. + * + * @return The current source + */ + currentSrc(): string; + + /** + * Get or set the current time (in seconds) + * + * @param [seconds] + * The time to seek to in seconds + * + * @return - the current time in seconds when getting + */ + currentTime(seconds: number): void; + + currentTime(): number; + + /** + * Get the current source type e.g. video/mp4 + * This can allow you rebuild the current source object so that you could load the same + * source and tech later + * + * @return The source MIME type + */ + currentType(): string; + + /** + * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted + * indicates the state of muted on initial playback. + * + * ```js + * var myPlayer = videojs('some-player-id'); + * + * myPlayer.src("http://www.example.com/path/to/video.mp4"); + * + * // get, should be false + * console.log(myPlayer.defaultMuted()); + * // set to true + * myPlayer.defaultMuted(true); + * // get should be true + * console.log(myPlayer.defaultMuted()); + * ``` + * + * @param [defaultMuted] + * - true to mute + * - false to unmute + * + * @return - true if defaultMuted is on and getting + * - false if defaultMuted is off and getting + * - A reference to the current player when setting + */ + defaultMuted(defaultMuted: boolean): void; + + defaultMuted(): boolean; + + /** + * Gets or sets the current default playback rate. A default playback rate of + * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance. + * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not + * not the current playbackRate. + * + * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate + * + * @param [rate] + * New default playback rate to set. + * + * @return - The default playback rate when getting or 1.0 + * - the player when setting + */ + defaultPlaybackRate(rate: number): Player; + + defaultPlaybackRate(): boolean; + + /** + * A getter/setter for the `Player`'s width & height. + * + * @param dimension + * This string can be: + * - 'width' + * - 'height' + * + * @param [value] + * Value for dimension specified in the first argument. + * + * @return The dimension arguments value when getting (width/height). + */ + dimension(dimension: 'width' | 'height', value: number): void; + + dimension(dimension: 'width' | 'height'): number; + + /** + * An instance of the `Player` class is created when any of the Video.js setup methods + * are used to initialize a video. + * + * After an instance has been created it can be accessed globally in two ways: + * 1. By calling `videojs('example_video_1');` + * 2. By using it directly via `videojs.players.example_video_1;` + */ + dispose(): void; + + /** + * Normally gets the length in time of the video in seconds; + * in all but the rarest use cases an argument will NOT be passed to the method + * + * > **NOTE**: The video must have started loading before the duration can be + * known, and in the case of Flash, may not be known until the video starts + * playing. + * + * + * @fires Player#durationchange + * + * @param [seconds] + * The duration of the video to set in seconds + * + * @return - The duration of the video in seconds when getting + */ + duration(seconds: number): void; + + duration(): number; + + /** + * A getter/setter/toggler for the vjs-fluid `className` on the `Player`. + * + * @param [bool] + * - A value of true adds the class. + * - A value of false removes the class. + * - No value will toggle the fluid class. + * + * @return - The value of fluid when getting. + * - `undefined` when setting. + */ + fluid(bool: boolean): void; + + fluid(): boolean; + + /** + * Get object for cached values. + * + * @return get the current object cache + */ + getCache(): any; + + /** + * Gets available media playback quality metrics as specified by the W3C's Media + * Playback Quality API. + * + * @see [Spec]{@link https://wicg.github.io/media-playback-quality} + * + * @return An object with supported media playback quality metrics or undefined if there + * is no tech or the tech does not support it. + */ + getVideoPlaybackQuality(): any; + + /** + * When fullscreen isn't supported we can stretch the + * video container to as wide as the browser will let us. + * + * @fires Player#enterFullWindow + */ + enterFullWindow(): void; + + /** + * Set or get the current MediaError + * + * @fires Player#error + * + * @param [err] + * A MediaError or a string/number to be turned + * into a MediaError + * + * @return The current MediaError when getting (or null) + */ + error(err: MediaError | string | number): void; + + error(): MediaError | null; + + /** + * Return the video to its normal size after having been in full screen mode + * + * @fires Player#fullscreenchange //noinspection JSUnresolvedVariable + */ + exitFullscreen(): Player; + + /** + * Exit full window + * + * @fires Player#exitFullWindow + */ + exitFullWindow(): void; + + /** + * Reports whether or not a player has a plugin available. + * + * This does not report whether or not the plugin has ever been initialized + * on this player. For that, [usingPlugin]{@link Player#usingPlugin}. + * + * @param name + * The name of a plugin. + * + * @return Whether or not this player has the requested plugin available. + */ + hasPlugin(name: string): boolean; + + /** + * Add/remove the vjs-has-started class + * + * @fires Player#firstplay + * + * @param request + * - true: adds the class + * - false: remove the class + * + * @return the boolean value of hasStarted_ + */ + hasStarted(request: boolean): void; + + hasStarted(): boolean; + + /** + * A getter/setter for the `Player`'s height. Returns the player's configured value. + * To get the current height use `currentheight()`. + * + * @param [value] + * The value to set the `Player`'s heigth to. + * + * @return The current height of the `Player` when getting. + */ + height(value: number): void; + + height(): number; + + /** + * Gets or sets the audio flag + * + * @param bool + * - true signals that this is an audio player + * - false signals that this is not an audio player + * + * @return The current value of isAudio when getting + */ + isAudio(bool: boolean): void; + + isAudio(): boolean; + + /** + * Check if the player is in fullscreen mode or tell the player that it + * is or is not in fullscreen mode. + * + * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official + * property and instead document.fullscreenElement is used. But isFullscreen is + * still a valuable property for internal player workings. + * + * @param [isFS] + * Set the players current fullscreen state + * + * @return - true if fullscreen is on and getting + * - false if fullscreen is off and getting + */ + isFullscreen(isFS: boolean): void; + + isFullscreen(): boolean; + + /** + * The player's language code + * NOTE: The language should be set in the player options if you want the + * the controls to be built with a specific language. Changing the language + * later will not update controls text. + * + * @param [code] + * the language code to set the player to + * + * @return The current language code when getting + */ + language(code: string): void; + + language(): string; + + /** + * Get the player's language dictionary + * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time + * Languages specified directly in the player options have precedence + * + * @return An array of of supported languages + */ + languages(): string[]; + + languageSwitch(options: any): void; + + /** + * Begin loading the src data. + */ + load(): void; + + /** + * Get or set the loop attribute on the video element. + * + * @param [value] + * - true means that we should loop the video + * - false means that we should not loop the video + * + * @return The current value of loop when getting + */ + loop(value?: boolean): void; + + loop(): string; + + /** + * Get the current muted state, or turn mute on or off + * + * @param [muted] + * - true to mute + * - false to unmute + * + * @return - true if mute is on and getting + * - false if mute is off and getting + */ + muted(muted: boolean): void; + + muted(): boolean; + + /** + * Pause the video playback + * @check + * @return A reference to the player object this function was called on + */ + pause(): Player; + + /** + * Check if the player is paused or has yet to play + * + * @return - false: if the media is currently playing + * - true: if media is not currently playing + */ + paused(): boolean; + + /** + * Attempt to begin playback at the first opportunity. + * @check + * @return Returns a `Promise` only if the browser returns one and the player + * is ready to begin playback. For some browsers and all non-ready + * situations, this will return `undefined`. + */ + play(): Player; + + /** + * Gets or sets the current playback rate. A playback rate of + * 1.0 represents normal speed and 0.5 would indicate half-speed + * playback, for instance. + * + * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate + * + * @param [rate] + * New playback rate to set. + * + * @return The current playback rate when getting or 1.0 + */ + playbackRate(rate?: number): void; + + playbackRate(): number; + + /** + * Get a TimeRange object representing the current ranges of time that the user + * has played. + * @check + * @return A time range object that represents all the increments of time that have + * been played. + */ + played(): any; + + /** + * Set or unset the playsinline attribute. + * Playsinline tells the browser that non-fullscreen playback is preferred. + * + * @param [value] + * - true means that we should try to play inline by default + * - false means that we should use the browser's default playback mode, + * which in most cases is inline. iOS Safari is a notable exception + * and plays fullscreen by default. + * + * @return - the current value of playsinline + * - the player when setting + * + * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline} + */ + playsinline(value: boolean): Player; + + playsinline(): string; + + /** + * Get or set the poster image source url + * + * @fires Player#posterchange + * + * @param [src] + * Poster image source URL + * + * @return The current value of poster when getting + */ + poster(src: string): void; + + poster(): string; + + /** + * Get or set the preload attribute + * + * @param [value] + * - true means that we should preload + * - false means that we should not preload + * + * @return The preload attribute value when getting + */ + preload(value?: boolean): string; + + /** + * Calculates how much time is left in the video. Not part + * of the native video API. + * + * @return The time remaining in seconds + */ + remainingTime(): number; + + /** + * A remaining time function that is intented to be used when + * the time is to be displayed directly to the user. + * + * @return The rounded time remaining in seconds + */ + remainingTimeDisplay(): number; + + /** + * Remove a remote {@link TextTrack} from the respective + * {@link TextTrackList} and {@link HtmlTrackElementList}. + * + * @param track + * Remote {@link TextTrack} to remove + * + * @return does not return anything + */ + removeRemoteTextTrack(track: HTMLTrackElement): void; + + /** + * Increase the size of the video to full screen + * In some browsers, full screen is not supported natively, so it enters + * "full window mode", where the video fills the browser window. + * In browsers and devices that support native full screen, sometimes the + * browser's default controls will be shown, and not the Video.js custom skin. + * This includes most mobile devices (iOS, Android) and older versions of + * Safari. + * + * @fires Player#fullscreenchange + */ + requestFullScreen(): Player; + + /** + * Report user activity + * + * @param event + * Event object + */ + reportUserActivity(event: any): void; + + /** + * Reset the player. Loads the first tech in the techOrder, + * and calls `reset` on the tech`. + */ + reset(): void; + + /** + * Select source based on tech-order or source-order + * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise, + * defaults to tech-order selection + * + * @param sources + * The sources for a media asset + * + * @return Object of source and tech order or false + */ + selectSource(sources: any[]): any; + + /** + * Returns whether or not the user is "scrubbing". Scrubbing is + * when the user has clicked the progress bar handle and is + * dragging it along the progress bar. + * + * @param [isScrubbing] + * whether the user is or is not scrubbing + * + * @return The value of scrubbing when getting + */ + scrubbing(isScrubbing: boolean): void; + + scrubbing(): boolean; + + /** + * Get or set the video source. + * + * @param [source] + * A SourceObject, an array of SourceObjects, or a string referencing + * a URL to a media source. It is _highly recommended_ that an object + * or array of objects is used here, so that source selection + * algorithms can take the `type` into account. + * + * If not provided, this method acts as a getter. + * + * @return If the `source` argument is missing, returns the current source + * URL. Otherwise, returns nothing/undefined. + */ + src(source: string | Tech.SourceObject | Tech.SourceObject[]): void; + + src(): string; + + /** + * Check if current tech can support native fullscreen + * (e.g. with built in controls like iOS, so not our flash swf) + * + * @return if native fullscreen is supported + */ + supportsFullScreen(): boolean; + + /** + * Return a reference to the current {@link Tech}. + * It will print a warning by default about the danger of using the tech directly + * but any argument that is passed in will silence the warning. + * + * @param [safety] + * Anything passed in to silence the warning + * + * @return The Tech + */ + tech(safety?: any): Tech; + + /** + * returns a JavaScript object reperesenting the current track + * information. **DOES not return it as JSON** + * + * @return Object representing the current of track info + */ + toJSON(): any; + + /** + * Get/set if user is active + * + * @fires Player#useractive + * @fires Player#userinactive + * + * @param [bool] + * - true if the user is active + * - false if the user is inactive + * + * @return The current value of userActive when getting + */ + userActive(bool: boolean): void; + + userActive(): boolean; + + /** + * Toggle native controls on/off. Native controls are the controls built into + * devices (e.g. default iPhone controls), Flash, or other techs + * (e.g. Vimeo Controls) + * **This should only be set by the current tech, because only the tech knows + * if it can support native controls** + * + * @fires Player#usingnativecontrols + * @fires Player#usingcustomcontrols + * + * @param [bool] + * - true to turn native controls on + * - false to turn native controls off + * + * @return The current value of native controls when getting + */ + usingNativeControls(bool: boolean): void; + + usingNativeControls(): boolean; + + /** + * Reports whether or not a player is using a plugin by name. + * + * For basic plugins, this only reports whether the plugin has _ever_ been + * initialized on this player. + * + * @param name + * The name of a plugin. + * + * @return Whether or not this player is using the requested plugin. + */ + usingPlugin(name: string): boolean; + + /** + * Get video height + * + * @return current video height + */ + videoHeight(): number; + + /** + * Get video width + * + * @return current video width + */ + videoWidth(): number; + + /** + * Get or set the current volume of the media + * + * @param [percentAsDecimal] + * The new volume as a decimal percent: + * - 0 is muted/0%/off + * - 1.0 is 100%/full + * - 0.5 is half volume or 50% + * + * @return The current volume as a percent when getting + */ + volume(percentAsDecimal: number): TimeRange; + + volume(): number; + + /** + * A getter/setter for the `Player`'s width. Returns the player's configured value. + * To get the current width use `currentWidth()`. + * + * @param [value] + * The value to set the `Player`'s width to. + * + * @return The current width of the `Player` when getting. + */ + width(value: number): void; + + width(): number; + } + + const Player: { + prototype: Player; + + /** + * An instance of the `Player` class is created when any of the Video.js setup methods + * are used to initialize a video. + * + * After an instance has been created it can be accessed globally in two ways: + * 1. By calling `videojs('example_video_1');` + * 2. By using it directly via `videojs.players.example_video_1;` + */ + new(player: Player, options?: PlayerOptions): Player; + + /** + * Gets tag settings + * + * @param tag + * The player tag + * @check + * @return An object containing all of the settings + * for a player tag + */ + getTagSettings(tag: Element): any; + }; + + interface PlayerOptions extends ComponentOptions { + aspectRatio?: string; + autoplay?: boolean; + controlBar?: ControlBarOptions | false; + textTrackSettings?: TextTrackSettingsOptions; + controls?: boolean; + defaultVolume?: number; + fluid?: boolean; + height?: number; + html5?: any; + language?: string; + languages?: { [code: string]: LanguageTranslations }; + loop?: boolean; + muted?: boolean; + notSupportedMessage?: string; + playbackRates?: number[]; + plugins?: any; + poster?: string; + preload?: string; + sourceOrder?: boolean; + sources?: Tech.SourceObject[]; + src?: string; + techOrder?: string[]; + tracks?: TextTrackOptions[]; + width?: number; + } + + /** + * Parent class for all advanced plugins. + * + * @fires Player#beforepluginsetup + * @fires Player#beforepluginsetup:$name + * @fires Player#pluginsetup + * @fires Player#pluginsetup:$name + * @listens Player#dispose + * @throws {Error} + * If attempting to instantiate the base {@link Plugin} class + * directly instead of via a sub-class. + */ + interface Plugin extends EventedMixin { + player: Player; + + /** + * Disposes a plugin. + * + * Subclasses can override this if they want, but for the sake of safety, + * it's probably best to subscribe the "dispose" event. + * + * @fires Plugin#dispose + */ + dispose(): void; + + /** + * Each event triggered by plugins includes a hash of additional data with + * conventional properties. + * + * This returns that object or mutates an existing hash. + * + * @param [hash={}] + * An object to be used as event an event hash. + * + * @return An event hash object with provided properties mixed-in. + */ + getEventHash(hash?: any): Plugin.PluginEventHash; + + /** + * Handles "statechanged" events on the plugin. No-op by default, override by + * subclassing. + * + * @param e + * An event object provided by a "statechanged" event. + * + * @param e.changes + * An object describing changes that occurred with the "statechanged" + * event. + */ + handleStateChanged(e: Event): void; + + /** + * Get the version of the plugin that was set on .VERSION + */ + version(): string; + + /** + * Triggers an event on the plugin object and overrides + * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}. + * + * @param event + * An event type or an object with a type property. + * + * @param [hash={}] + * Additional data hash to merge with a + * {@link Plugin~PluginEventHash|PluginEventHash}. + * + * @return Whether or not default was prevented. + */ + trigger(event: any, hash?: any): boolean; + } + + const Plugin: { + prototype: Plugin; + + /** + * The name of the base plugin class as it is registered. + * + */ + BASE_PLUGIN_NAME: string; + + /** + * Creates an instance of this class. + * + * Sub-classes should call `super` to ensure plugins are properly initialized. + * + * @param player + * A Video.js player instance. + */ + new (player: Player): Plugin; + + /** + * De-register a Video.js plugin. + * + * @param name + * The name of the plugin to be deregistered. + */ + deregisterPlugin(name: string): void; + + /** + * Gets a plugin by name if it exists. + * + * @param name + * The name of a plugin. + * + * @return The plugin (or `undefined`). + */ + getPlugin(name: string): typeof Plugin; + + /** + * Gets a plugin's version, if available + * + * @param name + * The name of a plugin. + * + * @return The plugin's version or an empty string. + */ + getPluginVersion(name: string): string; + + /** + * Gets an object containing multiple Video.js plugins. + * + * @param [names] + * If provided, should be an array of plugin names. Defaults to _all_ + * plugin names. + * + * @return An object containing plugin(s) associated with their name(s) or + * `undefined` if no matching plugins exist). + * + * @check returning type + */ + getPlugins(names?: string[]): { [name: string]: Plugin } + + /** + * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`). + * + * @param plugin + * If a string, matches the name of a plugin. If a function, will be + * tested directly. + * + * @return Whether or not a plugin is a basic plugin. + */ + isBasic(plugin: string | (() => any)): boolean + /** + * Register a Video.js plugin. + * + * @param name + * The name of the plugin to be registered. Must be a string and + * must not match an existing plugin or a method on the `Player` + * prototype. + * + * @param plugin + * A sub-class of `Plugin` or a function for basic plugins. + * + * @return For advanced plugins, a factory function for that plugin. For + * basic plugins, a wrapper function that initializes the plugin. + */ + registerPlugin(name: string, plugin: (this: Player, options: any) => T): () => T; + registerPlugin(name: string, plugin: T): () => T; + }; + + namespace Plugin { + interface PluginEventHash { + /** + * For basic plugins, the return value of the plugin function. For + * advanced plugins, the plugin instance on which the event is fired. + */ + instance: Plugin; + /** + * The name of the plugin. + */ + name: string; + /** + * For basic plugins, the plugin function. For advanced plugins, the + * plugin class/constructor. + */ + plugin: string; + } + } + + interface ProgressControl extends Component { + /** + * Create the `Component`'s DOM element + * + * @return The element that was created. + */ + createEl(): HTMLDivElement; + + /** + * Disable all controls on the progress control and its children + */ + disable(): void; + + /** + * Enable all controls on the progress control and its children + */ + enable(): void; + + /** + * Are controls are currently enabled for this progress control. + * + * @return true if controls are enabled, false otherwise + */ + enabled(): boolean; + + /** + * Handle `mousedown` or `touchstart` events on the `ProgressControl`. + * + * @param event + * `mousedown` or `touchstart` event that triggered this function + * + * @listens mousedown + * @listens touchstart + */ + handleMouseDown(event: EventTarget.Event): void; + + /** + * When the mouse moves over the `ProgressControl`, the pointer position + * gets passed down to the `MouseTimeDisplay` component. + * + * @param event + * The `mousemove` event that caused this function to run. + * + * @listen mousemove + */ + handleMouseMove(event: EventTarget.Event): void; + + /** + * Handle `mousemove` or `touchmove` events on the `ProgressControl`. + * + * @param event + * `mousedown` or `touchstart` event that triggered this function + * + * @listens mousemove + * @listens touchmove + */ + handleMouseSeek(event: EventTarget.Event): void; + + /** + * Handle `mouseup` or `touchend` events on the `ProgressControl`. + * + * @param event + * `mouseup` or `touchend` event that triggered this function. + * + * @listens touchend + * @listens mouseup + */ + handleMouseUp(event: EventTarget.Event): void; + } + + const ProgressControl: { + prototype: ProgressControl; + + /** + * Creates an instance of this class. + * + * @param player + * The `Player` that this class should be attached to. + * + * @param [options] + * The key/value store of player options. + */ + new (player: Player, options?: ComponentOptions): ProgressControl; + }; + + interface Representation { + id: string; + width: number; + height: number; + bitrate: number; + + enabled(): boolean; + + enabled(enabled: boolean): void; + } + + /** + * Seek bar and container for the progress bars. Uses {@link PlayProgressBar} + * as its `bar`. + */ + interface SeekBar extends Slider { + /** + * Create the `Component`'s DOM element + * + * @return The element that was created. + */ + createEl(): HTMLDivElement; + + /** + * Disable controls for this slider if they are enabled + */ + disable(): void; + + /** + * Enable controls for this slider if they are disabled + */ + enable(): void; + + /** + * Toggles the playback state of the player + * This gets called when enter or space is used on the seekbar + * + * @param event + * The `keydown` event that caused this function to be called + * + */ + handleAction(event: EventTarget.Event): void; + + /** + * We want the seek bar to be full on ended + * no matter what the actual internal values are. so we force it. + * + * @param [event] + * The `timeupdate` or `ended` event that caused this to run. + * + * @listens Player#ended + */ + handleEnded(event: EventTarget.Event): void; + + /** + * Called when this SeekBar has focus and a key gets pressed down. By + * default it will call `this.handleAction` when the key is space or enter. + * + * @param event + * The `keydown` event that caused this function to be called. + * + * @listens keydown + */ + handleKeyPress(event: EventTarget.Event): void; + + /** + * Handle mouse down on seek bar + * + * @param event + * The `mousedown` event that caused this to run. + * + * @listens mousedown + */ + handleMouseDown(event: EventTarget.Event): void; + + /** + * Handle mouse move on seek bar + * + * @param event + * The `mousemove` event that caused this to run. + * + * @listens mousemove + */ + handleMouseMove(event: EventTarget.Event): void; + + /** + * Handle mouse up on seek bar + * + * @param event + * The `mouseup` event that caused this to run. + * + * @listens mouseup + */ + handleMouseUp(event: EventTarget.Event): void; + + /** + * Get the percentage of media played so far. + * + * @return The percentage of media played so far (0 to 1). + */ + getPercent(): number; + + /** + * Move more quickly fast forward for keyboard-only users + */ + stepForward(): void; + + /** + * Move more quickly rewind for keyboard-only users + */ + stepBack(): void; + + /** + * Update the seek bar's UI. + * + * @listens Player#timeupdate + * + * @return The current percent at a number from 0-1 + */ + update(): number; + } + + const SeekBar: { + prototype: SeekBar; + + /** + * Creates an instance of this class. + * + * @param player + * The `Player` that this class should be attached to. + * + * @param [options] + * The key/value store of player options. + */ + new (player: Player, options?: SliderOptions): SeekBar; + }; + + /** + * The base functionality for a slider. Can be vertical or horizontal. + * For instance the volume bar or the seek bar on a video is a slider. + */ + interface Slider extends Component { + options_: SliderOptions; + + /** + * Enable controls for this slider if they are disabled + */ + enable(): void; + + /** + * Are controls are currently enabled for this slider or not. + * + * @return true if controls are enabled, false otherwise + */ + enabled(): boolean; + + /** + * Disable controls for this slider if they are enabled + */ + disable(): void; + + /** + * Create the `Slider`s DOM element. + * + * @param type + * Type of element to create. + * + * @param [props={}] + * List of properties in Object form. + * + * @param [attributes={}] + * list of attributes in Object form. + * + * @return The element that gets created. + */ + createEl(type: string, props?: any, attributes?: any): Element; + + /** + * Handle `mousedown` or `touchstart` events on the `Slider`. + * + * @param event + * `mousedown` or `touchstart` event that triggered this function + * + * @listens mousedown + * @listens touchstart + * @fires Slider#slideractive + */ + handleMouseDown(event: EventTarget.Event): void; + + /** + * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`. + * The `mousemove` and `touchmove` events will only only trigger this function during + * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and + * {@link Slider#handleMouseUp}. + * + * @param event + * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered + * this function + * + * @listens mousemove + * @listens touchmove + */ + handleMouseMove(event: EventTarget.Event): void; + + /** + * Handle `mouseup` or `touchend` events on the `Slider`. + * + * @param event + * The `mouseup` event that caused this to run. + * + * @listens touchend + * @listens mouseup + * @fires Slider#sliderinactive + */ + handleMouseUp(event: EventTarget.Event): void; + + /** + * Update the progress bar of the `Slider`. + * + * @return The percentage of progress the progress bar represents as a + * number from 0 to 1. + */ + update(): number; + + /** + * Calculate distance for slider + * + * @param event + * The event that caused this function to run. + * + * @return The current position of the Slider. + * - position.x for vertical `Slider`s + * - position.y for horizontal `Slider`s + */ + calculateDistance(event: EventTarget.Event): number; + + /** + * Handle a `focus` event on this `Slider`. + * + * @listens focus + */ + handleFocus(): void; + + /** + * Handle a `focus` event on this `Slider`. + * + * @listens focus + */ + handleFocus(): void; + + /** + * Handle a `blur` event on this `Slider`. + * + * @listens blur + */ + handleBlur(): void; + + /** + * Listener for click events on slider, used to prevent clicks + * from bubbling up to parent elements like button menus. + * + * @param event + * Event that caused this object to run + */ + handleClick(event: EventTarget.Event): void; + + /** + * Get/set if slider is horizontal for vertical + * + * @param [bool] + * - true if slider is vertical, + * - false is horizontal + * + * @return - true if slider is vertical, and getting + * - false if the slider is horizontal, and getting + */ + vertical(bool: boolean): void; + + vertical(): boolean; + } + + const Slider: { + prototype: Slider; + + /** + * Create an instance of this class + * + * @param player + * The `Player` that this class should be attached to. + * + * @param [options] + * The key/value store of player options. + */ + new (player: Player, options?: SliderOptions): Slider; + }; + + interface SliderOptions extends ComponentOptions { + /** + * Set property names to bar to match with the child Slider class is looking for + */ + barName?: string; + + /** + * Set a horizontal or vertical class on the slider depending on the slider type + */ + vertical?: boolean; + } + + /** + * Just an empty spacer element that can be used as an append point for plugins, etc. + * Also can be used to create space between elements when necessary. + */ + interface Spacer extends Component { + /** + * Builds the default DOM `className`. + * + * @return The DOM `className` for this object. + */ + buildCSSClass(): string; + + /** + * Create the `Component`'s DOM element + * + * @return The element that was created. + */ + createEl(): HTMLDivElement; + } + + const Spacer: { + prototype: Spacer; + + /** + * Creates an instance of this class. + * + * @param player + * The `Player` that this class should be attached to. + * + * @param [options] + * The key/value store of player options. + * + * @param [ready] + * Function that gets called when the `Component` is ready. + */ + new (player: Player, options?: ComponentOptions, ready?: Component.ReadyCallback): Spacer; + }; + + interface Tech extends Component { + /** + * Boolean indicating whether the `Tech` supports fullscreen resize control. + * Resizing plugins using request fullscreen reloads the plugin + * + * @default + */ + featuresFullscreenResize: boolean; + + /** + * Boolean indicating whether the `Tech` supports muting volume. + * + * @default + */ + featuresMuteControl: boolean; + + /** + * Boolean indicating whether the `Tech` supports the native `TextTrack`s. + * This will help us integrate with native `TextTrack`s if the browser supports them. + * + * @default + */ + featuresNativeTextTracks: boolean; + + /** + * Boolean indicating whether the `Tech` supports changing the speed at which the video + * plays. Examples: + * - Set player to play 2x (twice) as fast + * - Set player to play 0.5x (half) as fast + * + * @default + */ + featuresPlaybackRate: boolean; + + /** + * Boolean indicating whether the `Tech` supports the `progress` event. This is currently + * not triggered by video-js-swf. This will be used to determine if + * {@link Tech#manualProgressOn} should be called. + * + * @default + */ + featuresProgressEvents: boolean; + + /** + * Boolean indicating whether the `Tech` supports the `sourceset` event. + * + * A tech should set this to `true` and then use {@link Tech#triggerSourceset} + * to trigger a {@link Tech#event:sourceset} at the earliest time after getting + * a new source. + * + * @default + */ + featuresSourceset: boolean; + + /** + * Boolean indicating whether the `Tech` supports the `timeupdate` event. This is currently + * not triggered by video-js-swf. This will be used to determine if + * {@link Tech#manualTimeUpdates} should be called. + * + * @default + */ + featuresTimeupdateEvents: boolean; + + /** + * Boolean indicating whether the `Tech` supports volume control. + * + * @default + */ + featuresVolumeControl: boolean; + + /** + * Creates a remote text track object and returns an html track element. + * + * > Note: This can be an emulated {@link HTMLTrackElement} or a native one. + * + * @param options + * See {@link Tech#createRemoteTextTrack} for more detailed properties. + * + * @param [manualCleanup=true] + * - When false: the TextTrack will be automatically removed from the video + * element whenever the source changes + * - When True: The TextTrack will have to be cleaned up manually + * + * @return An Html Track Element. + * + * @deprecated The default functionality for this function will be equivalent + * to "manualCleanup=false" in the future. The manualCleanup parameter will + * also be removed. + */ + addRemoteTextTrack(options: TextTrackOptions, manualCleanup: true): HTMLTrackElement; + + /** + * Create and returns a remote {@link TextTrack} object. + * + * @param kind + * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata) + * + * @param [label] + * Label to identify the text track + * + * @param [language] + * Two letter language abbreviation + * + * @return The TextTrack that gets created. + */ + addTextTrack(kind: string, label: string, language: string): TextTrack; + + /** + * Emulate TextTracks using vtt.js if necessary + * + * @fires Tech#vttjsloaded + * @fires Tech#vttjserror + */ + addWebVttScript_(): void; + + /** + * Get the {@link AudioTrackList} + * + * @return Tech.prototype.audioTracks + */ + audioTracks(): TrackList; + + /** + * Get and create a `TimeRange` object for buffering. + * + * @return The time range object that was created. + */ + buffered(): any; + + /** + * Get the percentage of the current video that is currently buffered. + * + * @return A number from 0 to 1 that represents the decimal percentage of the + * video that is buffered. + * + */ + bufferedPercent(): number; + + /** + * Check if the tech can support the given mime-type. + * + * The base tech does not support any type, but source handlers might + * overwrite this. + * + * @param type + * The mimetype to check for support + * + * @return 'probably', 'maybe', or empty string + * + * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType} + */ + canPlayType(type: string): string; + + /** + * Remove any TextTracks added via addRemoteTextTrack that are + * flagged for automatic garbage collection + */ + cleanupAutoTextTracks(): void; + + /** + * Clear out a single `TrackList` or an array of `TrackLists` given their names. + * + * > Note: Techs without source handlers should call this between sources for `video` + * & `audio` tracks. You don't want to use them between tracks! + * + * @param types + * TrackList names to clear, valid names are `video`, `audio`, and + * `text`. + */ + clearTracks(types: string | string[]): void; + + /** + * Create an emulated TextTrack for use by addRemoteTextTrack + * + * This is intended to be overridden by classes that inherit from + * Tech in order to create native or custom TextTracks. + * + * @param options + * The object should contain the options to initialize the TextTrack with. + * + * @param [options.kind] + * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata). + * + * @param [options.label]. + * Label to identify the text track + * + * @param [options.language] + * Two letter language abbreviation. + * + * @return The track element that gets created. + */ + createRemoteTextTrack(options: TextTrackOptions): HTMLTextAreaElement; + + /** + * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList}, + * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech. + * + * @fires Component#dispose + */ + dispose(): void; + + /** + * Emulate texttracks + * + */ + emulateTextTracks(): void; + + /** + * Get or set an error on the Tech. + * + * @param [err] + * Error to set on the Tech + * + * @return The current error object on the tech, or null if there isn't one. + */ + error(err: MediaError): MediaError | null; + + /** + * Gets available media playback quality metrics as specified by the W3C's Media + * Playback Quality API. + * + * @see [Spec]{@link https://wicg.github.io/media-playback-quality} + * + * @return An object with supported media playback quality metrics + */ + getVideoPlaybackQuality(): any; + + /** + * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and + * {@link TextTrackList} events. + * + * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`. + * + * @fires Tech#audiotrackchange + * @fires Tech#videotrackchange + * @fires Tech#texttrackchange + */ + initTrackListeners(): void; + + manualProgressOff(): void; + + /** + * Polyfill the `progress` event for browsers that don't support it natively. + * + * @see {@link Tech#trackProgress} + */ + manualProgressOn(): void; + + /** + * Turn off the polyfill for `progress` events that was created in + * {@link Tech#manualProgressOn} + */ + manualTimeUpdatesOff(): void; + + /** + * Polyfill the `timeupdate` event for browsers that don't support it. + * + * @see {@link Tech#trackCurrentTime} + */ + manualTimeUpdatesOn(): void; + + /** + * Update our internal duration on a `durationchange` event by calling + * {@link Tech#duration}. + * + * @param event + * The `durationchange` event that caused this to run. + * + * @listens Tech#durationchange + */ + onDurationChange(event: Event): void; + + /** + * Attempt to force override of native audio tracks. + * + * @param override - If set to true native audio will be overridden, + * otherwise native audio will potentially be used. + */ + overrideNativeAudioTracks(override: boolean): void; + + /** + * Attempt to force override of native video tracks. + * + * @param override - If set to true native video will be overridden, + * otherwise native video will potentially be used. + */ + overrideNativeVideoTracks(override: boolean): void; + + /** + * Returns the `TimeRange`s that have been played through for the current source. + * + * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`. + * It only checks whether the source has played at all or not. + * + * @return - A single time range if this video has played + * - An empty set of ranges if not. + */ + played(): any; + + /** + * A method to check for the presence of the 'playsinline'
  • {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}Restricted