Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Alex Jerabek
2018-06-18 10:07:53 -07:00
45 changed files with 3032 additions and 1263 deletions
File diff suppressed because it is too large Load Diff
+419 -215
View File
@@ -1,10 +1,9 @@
// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.5
// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.6
// Project: http://angularjs.org
// Definitions by: Diego Vilar <https://github.com/diegovilar>, Tony Curtis <https://github.com/daltin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TypeScript Version: 2.4
/// <reference types="angular" />
/// <reference path="mocks.d.ts" />
import * as angular from 'angular';
@@ -13,7 +12,6 @@ import * as angular from 'angular';
// ngMock module (angular-mocks.js)
///////////////////////////////////////////////////////////////////////////////
declare module 'angular' {
///////////////////////////////////////////////////////////////////////////
// AngularStatic
// We reopen it to add the MockStatic definition
@@ -23,27 +21,27 @@ declare module 'angular' {
}
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject
// Depending on context, it might return a function, however having `void | (() => void)`
// as a return type seems to be not useful. E.g. it requires type assertions in `beforeEach(inject(...))`.
interface IInjectStatic {
(...fns: Function[]): any;
(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works
strictDi(val?: boolean): void;
(...fns: Array<Injectable<(...args: any[]) => void>>): any; // void | (() => void);
strictDi(val?: boolean): any; // void | (() => void);
}
interface IMockStatic {
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.dump
dump(obj: any): string;
inject: IInjectStatic
inject: IInjectStatic;
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.module
module: {
(...modules: any[]): any;
sharedInjector(): void;
}
};
// see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate
TzDate(offset: number, timestamp: number): Date;
TzDate(offset: number, timestamp: string): Date;
TzDate(offset: number, timestamp: number | string): Date;
}
///////////////////////////////////////////////////////////////////////////
@@ -62,7 +60,6 @@ declare module 'angular' {
///////////////////////////////////////////////////////////////////////////
interface ITimeoutService {
flush(delay?: number): void;
flushNext(expectedDelay?: number): void;
verifyNoPendingTasks(): void;
}
@@ -96,9 +93,11 @@ declare module 'angular' {
///////////////////////////////////////////////////////////////////////////
interface IControllerService {
// Although the documentation doesn't state this, locals are optional
<T>(controllerConstructor: new (...args: any[]) => T, locals?: any, bindings?: any): T;
<T>(controllerConstructor: (...args: any[]) => T, locals?: any, bindings?: any): T;
<T>(controllerName: string, locals?: any, bindings?: any): T;
<T>(
controllerConstructor: (new (...args: any[]) => T) | ((...args: any[]) => T) | string,
locals?: any,
bindings?: any
): T;
}
///////////////////////////////////////////////////////////////////////////
@@ -108,268 +107,473 @@ declare module 'angular' {
interface IComponentControllerService {
// TBinding is an interface exposed by a component as per John Papa's style guide
// https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#accessible-members-up-top
<T, TBinding>(componentName: string, locals: { $scope?: IScope, [key: string]: any }, bindings?: TBinding, ident?: string): T;
<T, TBinding>(
componentName: string,
locals: { $scope?: IScope; [key: string]: any },
bindings?: TBinding,
ident?: string
): T;
}
///////////////////////////////////////////////////////////////////////////
// HttpBackendService
// see https://docs.angularjs.org/api/ngMock/service/$httpBackend
///////////////////////////////////////////////////////////////////////////
interface IHttpBackendService {
/**
* Flushes pending requests using the trained responses. Requests are flushed in the order they were made, but it is also possible to skip one or more requests (for example to have them flushed later). This is useful for simulating scenarios where responses arrive from the server in any order.
*
* If there are no pending requests to flush when the method is called, an exception is thrown (as this is typically a sign of programming error).
* @param count Number of responses to flush. If undefined/null, all pending requests (starting after `skip`) will be flushed.
* @param skip Number of pending requests to skip. For example, a value of 5 would skip the first 5 pending requests and start flushing from the 6th onwards. _(default: 0)_
*/
* Flushes pending requests using the trained responses. Requests are flushed in the order they
* were made, but it is also possible to skip one or more requests (for example to have them
* flushed later). This is useful for simulating scenarios where responses arrive from the server
* in any order.
*
* If there are no pending requests to flush when the method is called, an exception is thrown (as
* this is typically a sign of programming error).
*
* @param count Number of responses to flush. If undefined/null, all pending requests (starting
* after `skip`) will be flushed.
* @param skip Number of pending requests to skip. For example, a value of 5 would skip the first 5 pending requests and start flushing from the 6th onwards. _(default: 0)_
*/
flush(count?: number, skip?: number): void;
/**
* Resets all request expectations, but preserves all backend definitions.
*/
* Resets all request expectations, but preserves all backend definitions.
*/
resetExpectations(): void;
/**
* Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.
* @param digest Do digest before checking expectation. Pass anything except false to trigger digest. NOTE this flag is purposely undocumented by Angular, which means it's not to be used in normal client code.
*/
* Verifies that all of the requests defined via the `expect` api were made. If any of the
* requests were not made, verifyNoOutstandingExpectation throws an exception.
* @param digest Do digest before checking expectation. Pass anything except false to trigger digest.
* NOTE: this flag is purposely undocumented by Angular, which means it's not to be used in normal client code.
*/
verifyNoOutstandingExpectation(digest?: boolean): void;
/**
* Verifies that there are no outstanding requests that need to be flushed.
*/
* Verifies that there are no outstanding requests that need to be flushed.
*/
verifyNoOutstandingRequest(): void;
/**
* Creates a new request expectation.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expect(
method: string,
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for DELETE requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation for DELETE requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectDELETE(
url: string | RegExp | ((url: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for GET requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation for GET requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectGET(
url: string | RegExp | ((url: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for HEAD requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
* @param keys Array of keys to assign to regex matches in the request url.
*/
/**
* Creates a new request expectation for HEAD requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
expectHEAD(
url: string | RegExp | ((url: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for JSONP requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation for JSONP requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectJSONP(
url: string | RegExp | ((url: string) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for PATCH requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation for PATCH requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectPATCH(
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for POST requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation for POST requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectPOST(
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for PUT requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation for PUT requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectPUT(
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new request expectation that compares only with the requested route.
* This method offers colon delimited matching of the url path, ignoring the query string.
* This allows declarations similar to how application routes are configured with `$routeProvider`.
* As this method converts the definition url to regex, declaration order is important.
* @param method HTTP method
* @param url HTTP url string that supports colon param matching
*/
expectRoute(method: string, url: string): mock.IRequestHandler;
/**
* Creates a new backend definition for DELETE requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
when(
method: string,
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for GET requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in request url described above
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition for DELETE requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenDELETE(
url: string | RegExp | ((url: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for HEAD requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition for GET requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in request url described above
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenGET(
url: string | RegExp | ((url: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for JSONP requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition for HEAD requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenHEAD(
url: string | RegExp | ((url: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for PATCH requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition for JSONP requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenJSONP(
url: string | RegExp | ((url: string) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for POST requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition for PATCH requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenPATCH(
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for PUT requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
/**
* Creates a new backend definition for POST requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true
* if the url matches the current definition.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenPOST(
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for PUT requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true
* if the url matches the current definition.
* @param data HTTP request body or function that receives data string and returns true if the data
* is as expected.
* @param headers HTTP headers or function that receives http header object and returns true if the
* headers match the current definition.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenPUT(
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition that compares only with the requested route.
* This method offers colon delimited matching of the url path, ignoring the query string.
* This allows declarations similar to how application routes are configured with `$routeProvider`.
* As this method converts the definition url to regex, declaration order is important.
* @param method HTTP method.
* @param url HTTP url string that supports colon param matching.
*/
whenRoute(method: string, url: string): mock.IRequestHandler;
}
///////////////////////////////////////////////////////////////////////////
// AnimateService
// see https://docs.angularjs.org/api/ngMock/service/$animate
///////////////////////////////////////////////////////////////////////////
module animate {
namespace animate {
interface IAnimateService {
/**
* This method will close all pending animations (both Javascript and CSS) and it will also flush any remaining animation frames and/or callbacks.
* This method will close all pending animations (both Javascript and CSS) and it will also flush any remaining
* animation frames and/or callbacks.
*/
closeAndFlush(): void;
/**
* This method is used to flush the pending callbacks and animation frames to either start an animation or conclude an animation. Note that this will not actually close an actively running animation (see `closeAndFlush()` for that).
* This method is used to flush the pending callbacks and animation frames to either start
* an animation or conclude an animation. Note that this will not actually close an
* actively running animation (see `closeAndFlush()`} for that).
*/
flush(): void;
}
}
export module mock {
// returned interface by the the mocked HttpBackendService expect/when methods
namespace mock {
/** Object returned by the the mocked HttpBackendService expect/when methods */
interface IRequestHandler {
/**
* Controls the response for a matched request using a function to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param func Function that receives the request HTTP method, url, data, headers, and an array of keys to regex matches in the request url and returns an array containing response status (number), data, headers, and status text.
*/
respond(func: ((method: string, url: string, data: string | Object, headers: Object, params?: any) => [number, string | Object, Object, string])): IRequestHandler;
/**
* Controls the response for a matched request using supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param status HTTP status code to add to the response.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
/**
* Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
// Available when ngMockE2E is loaded
/**
* Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.)
*/
* Controls the response for a matched request using a function to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param func Function that receives the request HTTP method, url, data, headers, and an array of keys
* to regex matches in the request url and returns an array containing response status (number), data,
* headers, and status text.
*/
respond(
func: ((
method: string,
url: string,
data: string | object,
headers: IHttpHeaders,
params: { [key: string]: string }
) => [number, string | object, IHttpHeaders, string])
): IRequestHandler;
/**
* Controls the response for a matched request using supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param status HTTP status code to add to the response.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(
status: number,
data: string | object,
headers?: IHttpHeaders,
responseText?: string
): IRequestHandler;
/**
* Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(
data: string | object,
headers?: IHttpHeaders,
responseText?: string
): IRequestHandler;
/**
* Any request matching a backend definition or expectation with passThrough handler will be
* passed through to the real backend (an XHR request will be made to the server.)
* Available when ngMockE2E is loaded
*/
passThrough(): IRequestHandler;
}
interface IHttpHeaders {
[headerName: string]: any;
}
/**
* Contains additional event data used by the `browserTrigger` function when creating an event.
*/
interface IBrowserTriggerEventData {
/**
* [Event.bubbles](https://developer.mozilla.org/docs/Web/API/Event/bubbles).
* Not applicable to all events.
*/
bubbles?: boolean;
/**
* [Event.cancelable](https://developer.mozilla.org/docs/Web/API/Event/cancelable).
* Not applicable to all events.
*/
cancelable?: boolean;
/**
* [charCode](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/charcode)
* for keyboard events (keydown, keypress, and keyup).
*/
charcode?: number;
/**
* The elapsedTime for
* [TransitionEvent](https://developer.mozilla.org/docs/Web/API/TransitionEvent)
* and [AnimationEvent](https://developer.mozilla.org/docs/Web/API/AnimationEvent).
*/
elapsedTime?: number;
/**
* [keyCode](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/keycode)
* for keyboard events (keydown, keypress, and keyup).
*/
keycode?: number;
/**
* An array of possible modifier keys (ctrl, alt, shift, meta) for
* [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent) and
* keyboard events (keydown, keypress, and keyup).
*/
keys?: Array<'ctrl' | 'alt' | 'shift' | 'meta'>;
/**
* The [relatedTarget](https://developer.mozilla.org/docs/Web/API/MouseEvent/relatedTarget)
* for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent).
*/
relatedTarget?: Node;
/**
* [which](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/which)
* for keyboard events (keydown, keypress, and keyup).
*/
which?: number;
/**
* x-coordinates for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent)
* and [TouchEvent](https://developer.mozilla.org/docs/Web/API/TouchEvent).
*/
x?: number;
/**
* y-coordinates for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent)
* and [TouchEvent](https://developer.mozilla.org/docs/Web/API/TouchEvent).
*/
y?: number;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// functions attached to global object (window)
///////////////////////////////////////////////////////////////////////////////
//Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs.
//declare var module: (...modules: any[]) => any;
// Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs.
// declare var module: (...modules: any[]) => any;
declare global {
export var inject: angular.IInjectStatic;
const inject: angular.IInjectStatic;
/**
* This is a global (window) function that is only available when the `ngMock` module is included.
* It can be used to trigger a native browser event on an element, which is useful for unit testing.
*
* @param element Either a wrapped jQuery/jqLite node or a DOM element
* @param eventType Optional event type. If none is specified, the function tries to determine
* the right event type for the element, e.g. `change` for `input[text]`.
* @param eventData An optional object which contains additional event data used when creating the event.
*/
function browserTrigger(
element: JQuery | Element,
eventType?: string,
eventData?: angular.mock.IBrowserTriggerEventData
): void;
}
+4 -4
View File
@@ -1,14 +1,14 @@
declare module "angular-mocks/ngMock" {
var _: string;
const _: string;
export = _;
}
declare module "angular-mocks/ngMockE2E" {
var _: string;
const _: string;
export = _;
}
declare module "angular-mocks/ngAnimateMock" {
var _: string;
const _: string;
export = _;
}
}
+8 -77
View File
@@ -1,79 +1,10 @@
{
"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",
"rules": {
"callable-types": false,
"interface-name": false,
"no-declare-current-package": false,
"no-unnecessary-generics": false,
"only-arrow-functions": false
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/wardbell/bardjs
// Definitions by: Andrew Archibald <https://github.com/TepigMC>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TypeScript Version: 2.4
/// <reference types="angular" />
/// <reference types="chai" />
+1 -1
View File
@@ -354,7 +354,7 @@ export type TooltipEvent = "show.bs.tooltip" | "shown.bs.tooltip" | "hide.bs.too
// --------------------------------------------------------------------------------------
declare global {
interface JQuery<TElement extends Node = HTMLElement> extends Iterable<TElement> {
interface JQuery<TElement = HTMLElement> {
alert(action?: "close" | "dispose"): this;
button(action: "toggle" | "dispose"): this;
+5
View File
@@ -21,6 +21,11 @@ declare namespace dygraphs {
* A per-series color definition. Used in conjunction with, and overrides, the colors option.
*/
color?: string;
/**
* A function which plot data for this series on the chart.
*/
plotter?: any;
/**
* Draw a small dot at each point, in addition to a line going through the point. This makes
+1 -1
View File
@@ -1173,7 +1173,7 @@ declare module 'ember' {
* key. You can pass an optional second argument with the target value. Otherwise
* this will match any property that evaluates to false.
*/
rejectBy(key: string, value?: string): NativeArray<T>;
rejectBy(key: string, value?: any): NativeArray<T>;
/**
* Returns the first item in the array for which the callback returns true.
* This method works similar to the `filter()` method defined in JavaScript 1.6
+1 -1
View File
@@ -1,6 +1,6 @@
declare var el: Element;
declare var els: Element[];
declare var els: HTMLElement[];
declare var mixinFn: Function;
function TestComponent() {
+28 -7
View File
@@ -1,4 +1,4 @@
// Type definitions for joi v13.0.1
// Type definitions for joi v13.3.0
// Project: https://github.com/hapijs/joi
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Laurence Dougal Myers <https://github.com/laurence-myers>
@@ -12,6 +12,7 @@
// Anjun Wang <https://github.com/wanganjun>
// Rafael Kallis <https://github.com/rafaelkallis>
// Conan Lai <https://github.com/aconanlai>
// Peter Thorson <https://github.com/zaphoyd>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
@@ -106,6 +107,13 @@ export interface EmailOptions {
minDomainAtoms?: number;
}
export interface HexOptions {
/**
* hex decoded representation must be byte aligned
*/
byteAligned: boolean;
}
export interface IpOptions {
/**
* One or more IP address versions to validate against. Valid values: ipv4, ipv6, ipvfuture
@@ -512,6 +520,11 @@ export interface NumberSchema extends AnySchema {
* Requires the number to be negative.
*/
negative(): this;
/**
* Requires the number to be a TCP port, so between 0 and 65535.
*/
port(): this;
}
export interface StringSchema extends AnySchema {
@@ -624,7 +637,7 @@ export interface StringSchema extends AnySchema {
/**
* Requires the string value to be a valid hexadecimal string.
*/
hex(): this;
hex(options?: HexOptions): this;
/**
* Requires the string value to be a valid hostname as per RFC1123.
@@ -714,10 +727,15 @@ export interface ArraySchema extends AnySchema {
export interface ObjectSchema extends AnySchema {
/**
* Sets the allowed object keys.
* Sets or extends the allowed object keys.
*/
keys(schema?: SchemaMap): this;
/**
* Appends the allowed object keys. If schema is null, undefined, or {}, no changes will be applied.
*/
append(schema?: SchemaMap): this;
/**
* Specifies the minimum number of keys in the object.
*/
@@ -966,7 +984,7 @@ export interface Rules<P extends object = any> {
name: string;
params?: ObjectSchema | {[key in keyof P]: SchemaLike; };
setup?(this: ExtensionBoundSchema, params: P): Schema | void;
validate?<R = any>(this: ExtensionBoundSchema, params: P, value: any, state: State, options: ValidationOptions): Err | R;
validate?(this: ExtensionBoundSchema, params: P, value: any, state: State, options: ValidationOptions): any;
description?: string | ((params: P) => string);
}
@@ -974,8 +992,8 @@ export interface Extension {
name: string;
base?: Schema;
language?: LanguageOptions;
coerce?<R = any>(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): Err | R;
pre?<R = any>(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): Err | R;
coerce?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): any;
pre?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): any;
describe?(this: Schema, description: Description): Description;
rules?: Rules[];
}
@@ -1101,10 +1119,13 @@ export function ref(key: string, options?: ReferenceOptions): Reference;
export function isRef(ref: any): ref is Reference;
/**
* Get a sub-schema of an existing schema based on a path. Path separator is a dot (.).
* Get a sub-schema of an existing schema based on a `path` that can be either a string or an array
* of strings For string values path separator is a dot (`.`)
*/
export function reach(schema: ObjectSchema, path: string): Schema;
export function reach<T extends Schema>(schema: ObjectSchema, path: string): T;
export function reach(schema: ObjectSchema, path: string[]): Schema;
export function reach<T extends Schema>(schema: ObjectSchema, path: string[]): T;
/**
* Creates a new Joi instance customized with the extension(s) you provide included.
+16 -4
View File
@@ -96,6 +96,12 @@ emailOpts = { minDomainAtoms: num };
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
let hexOpts: Joi.HexOptions = null;
hexOpts = { byteAligned: bool };
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
let ipOpts: Joi.IpOptions = null;
ipOpts = { version: str };
@@ -602,6 +608,7 @@ numSchema = numSchema.precision(num);
numSchema = numSchema.multiple(num);
numSchema = numSchema.positive();
numSchema = numSchema.negative();
numSchema = numSchema.port();
namespace common {
numSchema = numSchema.allow(x);
@@ -659,6 +666,9 @@ objSchema = Joi.object(schemaMap);
objSchema = objSchema.keys();
objSchema = objSchema.keys(schemaMap);
objSchema = objSchema.append();
objSchema = objSchema.append(schemaMap);
objSchema = objSchema.min(num);
objSchema = objSchema.max(num);
objSchema = objSchema.length(num);
@@ -801,6 +811,7 @@ strSchema = strSchema.guid();
strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] } as Joi.GuidOptions);
strSchema = strSchema.guid({ version: 'uuidv4' });
strSchema = strSchema.hex();
strSchema = strSchema.hex(hexOpts);
strSchema = strSchema.hostname();
strSchema = strSchema.isoDate();
strSchema = strSchema.lowercase();
@@ -969,6 +980,7 @@ description = Joi.describe(schema);
description = schema.describe();
schema = Joi.reach(objSchema, '');
schema = Joi.reach(objSchema, []);
const Joi2 = Joi.extend({ name: '', base: schema });
@@ -988,13 +1000,13 @@ const Joi3 = Joi.extend({
{
name: 'asd',
params: {
allowF: Joi.boolean().default(false),
allowFalse: Joi.boolean().default(false),
},
setup(params) {
const fIsAllowed = params.allowF;
const fIsAllowed = params.allowFalse;
},
validate(params, value, state, options) {
if (value === 'asd' || params.allowF && value === 'asdf') {
validate(params, value: boolean, state, options) {
if (value || params.allowFalse && !value) {
return value;
}
return this.createError('asd', { v: value }, state, options);
+47 -15
View File
@@ -40,7 +40,7 @@ type _Event = Event;
// Used by JQuery.Promise3 and JQuery.Promise
type _Promise<T> = Promise<T>;
interface JQueryStatic<TElement extends Node = HTMLElement> {
interface JQueryStatic<TElement = HTMLElement> {
/**
* @see {@link http://api.jquery.com/jquery.ajax/#jQuery-ajax1}
* @deprecated Use jQuery.ajaxSetup(options)
@@ -137,23 +137,53 @@ interface JQueryStatic<TElement extends Node = HTMLElement> {
// HACK: The discriminator parameter handles the edge case of passing a Window object to JQueryStatic. It doesn't actually exist on the factory function.
<FElement extends Node = HTMLElement>(window: Window, discriminator: boolean): JQueryStatic<FElement>;
/**
* Return a collection of matched elements either found in the DOM based on passed argument(s) or created
* by passing an HTML string.
*
* @param element_elementArray A DOM element to wrap in a jQuery object.
* An array containing a set of DOM elements to wrap in a jQuery object.
* @see {@link https://api.jquery.com/jQuery/}
* @since 1.0
*/
<T extends Element>(element_elementArray: T | ArrayLike<T>): JQuery<T>;
/**
* Return a collection of matched elements either found in the DOM based on passed argument(s) or created
* by passing an HTML string.
*
* @param selection An existing jQuery object to clone.
* @see {@link https://api.jquery.com/jQuery/}
* @since 1.0
*/
<T>(selection: JQuery<T>): JQuery<T>;
/**
* Accepts a string containing a CSS selector which is then used to match a set of elements.
*
* Creates DOM elements on the fly from the provided string of raw HTML.
*
* Binds a function to be executed when the DOM has finished loading.
*
* @param selector_object_callback A string containing a selector expression
* A DOM element to wrap in a jQuery object.
* An array containing a set of DOM elements to wrap in a jQuery object.
* A plain object to wrap in a jQuery object.
* An existing jQuery object to clone.
* A string of HTML to create on the fly. Note that this parses HTML, not XML.
* The function to execute when the DOM is ready.
* @see {@link https://api.jquery.com/jQuery/}
* @since 1.0
*/
(selector_object_callback: JQuery.Selector | JQuery.htmlString | ((this: Document, $: JQueryStatic<TElement>) => void)): JQuery<TElement>; // tslint:disable-line:unified-signatures
/**
* Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string.
*
* @param object A plain object to wrap in a jQuery object.
* @see {@link https://api.jquery.com/jQuery/}
* @since 1.0
*/
<T extends JQuery.PlainObject>(object: T): JQuery<T>;
/**
* Returns an empty jQuery set.
*
* @see {@link https://api.jquery.com/jQuery/}
* @since 1.4
*/
(selector_object_callback?: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray<Element> | JQuery |
JQuery.PlainObject | Window |
((this: Document, $: JQueryStatic<TElement>) => void)): JQuery<TElement>;
(): JQuery<TElement>;
/**
* A multi-purpose callbacks list object that provides a powerful way to manage callback lists.
*
@@ -659,7 +689,7 @@ interface JQueryStatic<TElement extends Node = HTMLElement> {
* @see {@link https://api.jquery.com/jQuery.map/}
* @since 1.0
*/
map<T, R>(array: T[], callback: (elementOfArray: T, indexInArray: number) => R): R[];
map<T, TReturn>(array: T[], callback: (this: Window, elementOfArray: T, indexInArray: number) => JQuery.TypeOrArray<TReturn> | null | undefined): TReturn[];
/**
* Translate all items in an array or object to new array of items.
*
@@ -671,7 +701,7 @@ interface JQueryStatic<TElement extends Node = HTMLElement> {
* @see {@link https://api.jquery.com/jQuery.map/}
* @since 1.6
*/
map<T, K extends keyof T, R>(obj: T, callback: (propertyOfObject: T[K], key: K) => R): R[];
map<T, K extends keyof T, TReturn>(obj: T, callback: (this: Window, propertyOfObject: T[K], key: K) => JQuery.TypeOrArray<TReturn> | null | undefined): TReturn[];
/**
* Merge the contents of two arrays together into the first array.
*
@@ -3098,7 +3128,7 @@ interface JQueryStatic<TElement extends Node = HTMLElement> {
when(...deferreds: any[]): JQuery.Promise<any, any, never>;
}
interface JQuery<TElement extends Node = HTMLElement> extends Iterable<TElement> {
interface JQuery<TElement = HTMLElement> extends Iterable<TElement> {
/**
* A string containing the jQuery version number.
*
@@ -4253,7 +4283,7 @@ interface JQuery<TElement extends Node = HTMLElement> extends Iterable<TElement>
* @see {@link https://api.jquery.com/map/}
* @since 1.2
*/
map(callback: (this: TElement, index: number, domElement: TElement) => any | any[] | null | undefined): this;
map<TReturn>(callback: (this: TElement, index: number, domElement: TElement) => JQuery.TypeOrArray<TReturn> | null | undefined): JQuery<TReturn>;
/**
* Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.
*
@@ -6363,7 +6393,9 @@ declare namespace JQuery {
};
// Writable properties on XMLHttpRequest
interface XHRFields extends Partial<Pick<XMLHttpRequest, 'onreadystatechange' | 'responseType' | 'timeout' | 'withCredentials' | 'msCaching'>> { }
interface XHRFields extends Partial<Pick<XMLHttpRequest, 'onreadystatechange' | 'responseType' | 'timeout' | 'withCredentials'>> {
msCaching?: string;
}
}
interface Transport {
@@ -7922,9 +7954,9 @@ declare namespace JQuery {
// endregion
interface EventHandler<TCurrentTarget extends EventTarget, TData = null> extends EventHandlerBase<TCurrentTarget, JQuery.Event<TCurrentTarget, TData>> { }
interface EventHandler<TCurrentTarget, TData = null> extends EventHandlerBase<TCurrentTarget, JQuery.Event<TCurrentTarget, TData>> { }
interface EventHandlerBase<TContext extends object, T> {
interface EventHandlerBase<TContext, T> {
// Extra parameters can be passed from trigger()
(this: TContext, t: T, ...args: any[]): void | false | any;
}
+216 -17
View File
@@ -42,7 +42,7 @@ function JQueryStatic() {
// $ExpectType JQuery<HTMLElement>
$([new HTMLElement()]);
// $ExpectType JQuery<HTMLElement>
// $ExpectType JQuery<{ foo: string; hello: string; }>
$({ foo: 'bar', hello: 'world' });
// $ExpectType JQuery<HTMLElement>
@@ -58,6 +58,39 @@ function JQueryStatic() {
// $ExpectType JQuery<HTMLElement>
$();
// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/19597#issuecomment-378218432
function issue_19597_378218432() {
let myDiv = $(document.createElement('div')); // gets default jQuery<HTMLElement> 8-/
// $ExpectType JQuery<HTMLDivElement>
myDiv;
myDiv.on('click', (evt) => {
let target = evt.target; // HTMLElement
// $ExpectType HTMLDivElement
target;
});
let myDiv1 = $<HTMLDivElement>(document.createElement('div')); // expected 0-2 Arguments but got 1. huh?
// let myDiv2 = $<HTMLDivElement, null>(document.createElement('div')); // expected 0-1 Arguments but got 2. huh?
let myForcedDiv: JQuery<HTMLDivElement> = $(document.createElement('div')) as any;
myForcedDiv.on('click', (evt) => {
let target = evt.target; // HTMLDivElement
// $ExpectType HTMLDivElement
target;
});
let myDoc = $(document); // gets default jQuery<HTMLElement>
// $ExpectType JQuery<Document>
myDoc;
myDoc.on('click', (evt) => {
let target = evt.target; // HTMLElement
// $ExpectType Document
target;
});
let myDocForced: JQuery<Document> = $(document); // type HTMLElement is not assignable to Type Document
let myWindow = $(window); // gets default jQuery<HTMLElement>
// $ExpectType JQuery<Window>
myWindow;
let myWindowForced: JQuery<Window> = $(window); // type Window does not satisfy contraint Node
}
}
function ajaxSettings() {
@@ -699,7 +732,9 @@ function JQueryStatic() {
function map() {
// $ExpectType number[]
$.map([1, 2, 3], (elementOfArray, indexInArray) => {
$.map([1, 2, 3], function (elementOfArray, indexInArray) {
// $ExpectType Window
this;
// $ExpectType number
elementOfArray;
// $ExpectType number
@@ -708,11 +743,49 @@ function JQueryStatic() {
return 200 + 10;
});
// $ExpectType number[]
$.map([1, 2, 3], function (elementOfArray, indexInArray) {
// $ExpectType Window
this;
// $ExpectType number
elementOfArray;
// $ExpectType number
indexInArray;
return [200, 10];
});
// $ExpectType (number | null)[]
$.map([1, 2, 3], function (elementOfArray, indexInArray) {
// $ExpectType Window
this;
// $ExpectType number
elementOfArray;
// $ExpectType number
indexInArray;
return [200, 10, null];
});
// $ExpectType (number | undefined)[]
$.map([1, 2, 3], function (elementOfArray, indexInArray) {
// $ExpectType Window
this;
// $ExpectType number
elementOfArray;
// $ExpectType number
indexInArray;
return [200, 10, undefined];
});
// $ExpectType (false | 1)[]
$.map({
myProp: true,
name: 'Rogers',
}, (propertyOfObject, key) => {
}, function (propertyOfObject, key) {
// $ExpectType Window
this;
// $ExpectType string | boolean
propertyOfObject;
// $ExpectType "myProp" | "name"
@@ -725,6 +798,67 @@ function JQueryStatic() {
return false;
}
});
// $ExpectType (string | number | boolean)[]
$.map({
myProp: true,
name: 'Rogers',
}, function (propertyOfObject, key) {
// $ExpectType Window
this;
// $ExpectType string | boolean
propertyOfObject;
// $ExpectType "myProp" | "name"
key;
return [propertyOfObject, 24];
});
// $ExpectType (false | 1)[]
$.map({
myProp: true,
name: 'Rogers',
anotherProp: 70,
}, function (propertyOfObject, key) {
// $ExpectType Window
this;
// $ExpectType string | number | boolean
propertyOfObject;
// $ExpectType "myProp" | "name" | "anotherProp"
key;
switch (key) {
case 'myProp':
return 1;
case 'name':
return false;
}
return null;
});
// $ExpectType (false | 1)[]
$.map({
myProp: true,
name: 'Rogers',
anotherProp: 70,
}, function (propertyOfObject, key) {
// $ExpectType Window
this;
// $ExpectType string | number | boolean
propertyOfObject;
// $ExpectType "myProp" | "name" | "anotherProp"
key;
switch (key) {
case 'myProp':
return 1;
case 'name':
return false;
}
return undefined;
});
}
function merge() {
@@ -2041,7 +2175,7 @@ function JQuery() {
function ajax() {
function ajaxComplete() {
// $ExpectType JQuery<HTMLElement>
// $ExpectType JQuery<Document>
$(document).ajaxComplete(function(event, jqXHR, ajaxOptions) {
// $ExpectType Document
this;
@@ -2057,7 +2191,7 @@ function JQuery() {
}
function ajaxError() {
// $ExpectType JQuery<HTMLElement>
// $ExpectType JQuery<Document>
$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
// $ExpectType Document
this;
@@ -2075,7 +2209,7 @@ function JQuery() {
}
function ajaxSend() {
// $ExpectType JQuery<HTMLElement>
// $ExpectType JQuery<Document>
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
// $ExpectType Document
this;
@@ -2091,7 +2225,7 @@ function JQuery() {
}
function ajaxStart() {
// $ExpectType JQuery<HTMLElement>
// $ExpectType JQuery<Document>
$(document).ajaxStart(function() {
// $ExpectType Document
this;
@@ -2101,7 +2235,7 @@ function JQuery() {
}
function ajaxStop() {
// $ExpectType JQuery<HTMLElement>
// $ExpectType JQuery<Document>
$(document).ajaxStop(function() {
// $ExpectType Document
this;
@@ -2111,7 +2245,7 @@ function JQuery() {
}
function ajaxSuccess() {
// $ExpectType JQuery<HTMLElement>
// $ExpectType JQuery<Document>
$(document).ajaxSuccess(function(event, jqXHR, ajaxOptions, data) {
// $ExpectType Document
this;
@@ -5898,8 +6032,9 @@ function JQuery() {
}
function contents() {
// $ExpectType JQuery<HTMLElement | Comment | Text>
$('p').contents();
// TODO: Flaky test due to type ordering.
// // $ExpectType JQuery<HTMLElement | Comment | Text>
// $('p').contents();
}
function end() {
@@ -6131,7 +6266,7 @@ function JQuery() {
}
function map() {
// $ExpectType JQuery<HTMLElement>
// $ExpectType JQuery<string>
$('p').map(function(index, domElement) {
// $ExpectType HTMLElement
this;
@@ -6143,7 +6278,7 @@ function JQuery() {
return 'myVal';
});
// $ExpectType JQuery<HTMLElement>
// $ExpectType JQuery<string>
$('p').map(function(index, domElement) {
// $ExpectType HTMLElement
this;
@@ -6155,7 +6290,7 @@ function JQuery() {
return ['myVal1', 'myVal2'];
});
// $ExpectType JQuery<HTMLElement>
// $ExpectType JQuery<string | null>
$('p').map(function(index, domElement) {
// $ExpectType HTMLElement
this;
@@ -6164,10 +6299,10 @@ function JQuery() {
// $ExpectType HTMLElement
domElement;
return null;
return ['myVal1', 'myVal2', null];
});
// $ExpectType JQuery<HTMLElement>
// $ExpectType JQuery<string | undefined>
$('p').map(function(index, domElement) {
// $ExpectType HTMLElement
this;
@@ -6176,8 +6311,72 @@ function JQuery() {
// $ExpectType HTMLElement
domElement;
return undefined;
return ['myVal1', 'myVal2', undefined];
});
// $ExpectType JQuery<string>
$('p').map(function(index, domElement) {
// $ExpectType HTMLElement
this;
// $ExpectType number
index;
// $ExpectType HTMLElement
domElement;
let value: string;
if (index % 2 === 0) {
return null;
}
value = 'myVal';
return value;
});
// $ExpectType JQuery<string>
$('p').map(function(index, domElement) {
// $ExpectType HTMLElement
this;
// $ExpectType number
index;
// $ExpectType HTMLElement
domElement;
let value: string;
if (index % 2 === 0) {
return undefined;
}
value = 'myVal';
return value;
});
// // $ExpectType JQuery<never>
// $('p').map(function(index, domElement) {
// // $ExpectType HTMLElement
// this;
// // $ExpectType number
// index;
// // $ExpectType HTMLElement
// domElement;
//
// return null;
// });
// // $ExpectType JQuery<never>
// $('p').map(function(index, domElement) {
// // $ExpectType HTMLElement
// this;
// // $ExpectType number
// index;
// // $ExpectType HTMLElement
// domElement;
//
// return undefined;
// });
}
function slice() {
+1 -1
View File
@@ -3428,7 +3428,7 @@ function examples() {
function map_0() {
$('p')
.append($('input').map(function() {
return $(this).val();
return $(this).val() as string;
})
.get()
.join(', '));
@@ -1,5 +1,5 @@
import jq = require('jquery/dist/jquery.slim');
const $window = jq(window);
// $ExpectType JQuery<HTMLElement>
// $ExpectType JQuery<Window>
$window;
@@ -1,7 +1,7 @@
import jq = require('jquery');
const $window = jq(window);
// $ExpectType JQuery<HTMLElement>
// $ExpectType JQuery<Window>
$window;
class CanvasLayersDirective {
+1
View File
@@ -14,6 +14,7 @@
"no-empty-interface": false,
"no-misused-new": false,
"no-object-literal-type-assertion": false,
"no-redundant-jsdoc-2": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
+1 -1
View File
@@ -67,7 +67,7 @@ export declare class Element {
getText(): string;
getChildText(name: string, xmlns: any): string;
getChildText(name: string, xmlns?: any): string;
/**
* Return all direct descendents that are Elements.
+5
View File
@@ -2,6 +2,11 @@ import * as ltx from 'ltx';
ltx.parse('<document/>');
const getChildTextElement = ltx.parse('<test><child>body text</child></test>') as ltx.Element;
if (getChildTextElement.getChildText('child') !== 'body text') {
throw new Error("body does not match");
}
const p = new ltx.Parser();
p.on('tree', (ignored: any) => {});
@@ -1,6 +1,6 @@
import * as materialize from "materialize-css";
const elem = document.querySelector('.whatever')!;
const elem = document.querySelector('.whatever') as HTMLElement;
M.textareaAutoResize(elem);
M.textareaAutoResize($(elem));
+5
View File
@@ -68,6 +68,11 @@ export declare interface Response {
readonly names: Translations;
};
readonly postal?: { code: string };
readonly isp?: {
readonly isp: string;
readonly autonomous_system_number: number;
};
readonly connection?: { connection_type: string };
}
export declare interface Translations {
+4 -7
View File
@@ -1,12 +1,9 @@
// Type definitions for memoize-one 3.1
// Project: https://github.com/alexreardon/memoize-one#readme
// Definitions by: Karol Majewski <https://github.com/karol-majewski>
// Definitions by: Karol Majewski <https://github.com/karol-majewski>, Frank Li <https://github.com/franklixuefei>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = memoizeOne;
declare function memoizeOne<T extends (...args: any[]) => any>(resultFn: T, isEqual?: EqualityFn): T;
export type EqualityFn = (a: any, b: any) => boolean;
declare function memoizeOne<T extends (...args: any[]) => any>(resultFn: T, isEqual?: memoizeOne.EqualityFn): T;
declare namespace memoizeOne {
type EqualityFn = (a: any, b: any) => boolean;
}
export default memoizeOne;
+2 -2
View File
@@ -1,4 +1,4 @@
import memoizeOne = require('memoize-one');
import memoizeOne, { EqualityFn } from 'memoize-one';
declare function add(a: number, b: number): number ;
declare function lousyEqualityFn(a: any, b: any): boolean;
@@ -30,4 +30,4 @@ memoizeOne(add, (a: string, b: string) => 0); // $ExpectError
/**
* The `EqualityFn` type is publicly accessible.
*/
const simpleIsEqual: memoizeOne.EqualityFn = (x: number, y: number): boolean => (x === y);
const simpleIsEqual: EqualityFn = (x: number, y: number): boolean => (x === y);
+6 -6
View File
@@ -80,12 +80,12 @@ declare module "moment" {
}
interface LocaleSpecification {
durationLabelsLong: DurationLabelDef;
durationLabelsStandard: DurationLabelDef;
durationLabelsShort: DurationLabelDef;
durationTimeTemplates: DurationTimeDef;
durationLabelTypes: DurationLabelTypeDef[];
durationPluralKey: (token: string, integerValue: number, decimalValue: number) => string;
durationLabelsLong?: DurationLabelDef;
durationLabelsStandard?: DurationLabelDef;
durationLabelsShort?: DurationLabelDef;
durationTimeTemplates?: DurationTimeDef;
durationLabelTypes?: DurationLabelTypeDef[];
durationPluralKey?: (token: string, integerValue: number, decimalValue: number) => string;
}
type TemplateFunction = ((this: DurationFormatSettings) => string);
+5 -5
View File
@@ -39,7 +39,7 @@ declare namespace naver.maps {
*/
interface MapEventListener {
eventName: string;
listener: () => any;
listener: (event: any) => any;
listenerId: string;
target: any;
}
@@ -1303,14 +1303,14 @@ declare namespace naver.maps {
function Event(): void;
namespace Event {
function addDOMListener(element: HTMLElement, eventName: string, listener: () => any): void;
function addListener(target: any, eventName: string, listener: () => any): MapEventListener;
function addDOMListener(element: HTMLElement, eventName: string, listener: (event: any) => any): void;
function addListener(target: any, eventName: string, listener: (event: any) => any): MapEventListener;
function clearInstanceListeners(target: any): void;
function clearListeners(target: any, fromEventName: string): void;
function forward(source: any, fromEventName: string, target: any, toEventName: string): MapEventListener;
function hasListener(target: any, eventName: string): boolean;
function once(target: any, eventName: string, listener: () => any): MapEventListener;
function removeDOMListener(element: HTMLElement, eventName: string, listener: () => any): void;
function once(target: any, eventName: string, listener: (event: any) => any): MapEventListener;
function removeDOMListener(element: HTMLElement, eventName: string, listener: (event: any) => any): void;
function removeDOMListener(listeners: DOMEventListener | DOMEventListener[]): void;
function removeListener(listeners: MapEventListener | MapEventListener[]): void;
function resumeDispatch(target: any, eventName: string): void;
+16 -2
View File
@@ -160,15 +160,21 @@ export class Gpio extends NodeJS.EventEmitter {
disableInterrupt(): Gpio;
/**
* Enables alerts for the GPIO.
* Enables alerts for the GPIO. Returns this.
*/
enableAlert(): Gpio;
/**
* Disables aterts for the GPIO.
* Disables aterts for the GPIO. Returns this.
*/
disableAlert(): Gpio;
/**
* Sets a glitch filter on a GPIO. Returns this.
* @param steady Time, in microseconds, during which the level must be stable. Maximum value: 300000
*/
glitchFilter(steady: number): Gpio;
/*----------------------*
* mode
*----------------------*/
@@ -410,3 +416,11 @@ export function terminate(): void;
* @param peripheral an unsigned integer specifying the peripheral for timing (CLOCK_PWM or CLOCK_PCM)
*/
export function configureClock(microseconds: number, peripheral: number): void;
/**
* Configures pigpio to use the specified socket port.
* The default setting is to use port 8888.
* If configureSocketPort is called, it must be called before creating Gpio objects.
* @param port an unsigned integer specifying the pigpio socket port number
*/
export function configureSocketPort(port: number): void;
+35
View File
@@ -5,6 +5,7 @@ import * as assert from 'assert';
const Gpio = pigpio.Gpio;
pigpio.configureClock(1, pigpio.CLOCK_PWM);
pigpio.configureSocketPort(23456);
const led = new Gpio(18, {
mode: Gpio.OUTPUT,
@@ -878,3 +879,37 @@ import * as assert from 'assert';
clearInterval(iv);
}, 2000);
})();
(function gpio_glitch_filter(): void {
const Gpio = pigpio.Gpio;
const input = new Gpio(7, {
mode: Gpio.INPUT,
pullUpDown: Gpio.PUD_OFF,
alert: true
});
const output = new Gpio(8, {
mode: Gpio.OUTPUT
});
let count = 0;
output.digitalWrite(0);
input.glitchFilter(50);
input.on('alert', (level, tick) => {
if (level === 1) {
count++;
console.log(' rising edge, count=' + count);
}
});
output.trigger(30, 1); // alert function should not be executed (blocked by glitchFilter)
setTimeout(() => {
output.trigger(70, 1); // alert function should be executed
}, 500);
setTimeout(() => {
assert.strictEqual(count, 1, 'expected 1 alert function call instead of ' + count);
console.log(" success...");
process.exit(0);
}, 1000);
})();
+48 -15
View File
@@ -1088,10 +1088,11 @@ export interface TextInputFocusEventData {
eventCount: number;
}
export interface TextInputScrollEvent {
nativeEvent: {
contentOffset: { x: number; y: number; }
}
/**
* @see TextInputProps.onScroll
*/
export interface TextInputScrollEventData {
contentOffset: { x: number; y: number; }
}
/**
@@ -1232,7 +1233,7 @@ export interface TextInputProps
*
* May also contain other properties from ScrollEvent but on Android contentSize is not provided for performance reasons.
*/
onScroll?: (event: TextInputScrollEvent) => void;
onScroll?: (e: NativeSyntheticEvent<TextInputScrollEventData>) => void;
/**
* The string that will be rendered before text input has been entered
@@ -1332,7 +1333,10 @@ interface TextInputState {
declare class TextInputComponent extends React.Component<TextInputProps> {}
declare const TextInputBase: Constructor<NativeMethodsMixin> & Constructor<TimerMixin> & typeof TextInputComponent;
export class TextInput extends TextInputBase {
State: TextInputState;
/**
* Access the current focus state.
*/
static State: TextInputState;
/**
* Returns if the input is currently focused.
@@ -3412,9 +3416,26 @@ interface ImagePropsAndroid {
fadeDuration?: number;
}
// See https://facebook.github.io/react-native/docs/image.html#source
/**
* @see https://facebook.github.io/react-native/docs/image.html#source
*/
export type ImageSourcePropType = ImageURISource | ImageURISource[] | ImageRequireSource;
/**
* @see ImagePropsBase.onLoad
*/
interface ImageLoadEventDataAndroid {
uri?: string;
}
interface ImageLoadEventData extends ImageLoadEventDataAndroid {
source: {
height: number;
width: number;
url: string;
}
}
/**
* @see https://facebook.github.io/react-native/docs/image.html
*/
@@ -3435,8 +3456,9 @@ export interface ImagePropsBase extends ImagePropsIOS, ImagePropsAndroid, Access
/**
* Invoked when load completes successfully
* { source: { url, height, width } }.
*/
onLoad?: () => void;
onLoad?: (event: NativeSyntheticEvent<ImageLoadEventData>) => void;
/**
* Invoked when load either succeeds or fails
@@ -3887,6 +3909,13 @@ export interface SectionListProps<ItemT> extends ScrollViewProps {
*/
initialNumToRender?: number;
/**
* Used to extract a unique key for a given item at the specified index. Key is used for caching
* and as the react key to track item re-ordering. The default extractor checks `item.key`, then
* falls back to using the index, like React does.
*/
keyExtractor?: (item: ItemT, index: number) => string;
/**
* Called once when the scroll position gets within onEndReachedThreshold of the rendered content.
*/
@@ -3900,19 +3929,23 @@ export interface SectionListProps<ItemT> extends ScrollViewProps {
*/
onEndReachedThreshold?: number | null;
/**
* Used to extract a unique key for a given item at the specified index. Key is used for caching
* and as the react key to track item re-ordering. The default extractor checks `item.key`, then
* falls back to using the index, like React does.
*/
keyExtractor?: (item: ItemT, index: number) => string;
/**
* If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality.
* Make sure to also set the refreshing prop correctly.
*/
onRefresh?: (() => void) | null;
/**
* Used to handle failures when scrolling to an index that has not been measured yet.
* Recommended action is to either compute your own offset and `scrollTo` it, or scroll as far
* as possible and then try again after more items have been rendered.
*/
onScrollToIndexFailed?: (info: {
index: number,
highestMeasuredFrameIndex: number,
averageItemLength: number
}) => void;
/**
* Set this true while waiting for new data from a refresh.
*/
+73 -37
View File
@@ -24,6 +24,7 @@ import {
Dimensions,
Image,
ImageStyle,
ImageLoadEventData,
InteractionManager,
ListView,
ListViewDataSource,
@@ -55,7 +56,7 @@ import {
StatusBar,
NativeSyntheticEvent,
GestureResponderEvent,
TextInputScrollEvent,
TextInputScrollEventData
} from "react-native";
declare module "react-native" {
@@ -150,6 +151,25 @@ const viewProperty = StyleSheet.flatten(viewStyle).backgroundColor;
const textProperty = StyleSheet.flatten(textStyle).fontSize;
const imageProperty = StyleSheet.flatten(imageStyle).resizeMode;
const testNativeSyntheticEvent = <T extends {}>(e: NativeSyntheticEvent<T>): void => {
e.isDefaultPrevented();
e.preventDefault();
e.isPropagationStopped();
e.stopPropagation();
e.persist();
e.cancelable;
e.bubbles;
e.currentTarget;
e.defaultPrevented;
e.eventPhase;
e.isTrusted;
e.nativeEvent;
e.target;
e.timeStamp;
e.type;
e.nativeEvent;
}
class CustomView extends React.Component {
render() {
return <Text style={[StyleSheet.absoluteFill, { ...StyleSheet.absoluteFillObject }]}>Custom View</Text>;
@@ -198,19 +218,14 @@ class Welcome extends React.Component {
export default Welcome;
// EventsTest
export class EventsTest extends React.Component {
onPressButton(e: GestureResponderEvent) {
// TouchableNativeFeedbackTest
export class TouchableNativeFeedbackTest extends React.Component {
onPressButton = (e: GestureResponderEvent) => {
e.persist();
e.isPropagationStopped();
e.isDefaultPrevented();
}
onScroll(e: TextInputScrollEvent) {
console.log(`x: ${ e.nativeEvent.contentOffset.x }`);
console.log(`y: ${ e.nativeEvent.contentOffset.y }`);
}
render() {
return (
<TouchableNativeFeedback
@@ -218,10 +233,6 @@ export class EventsTest extends React.Component {
>
<View style={{width: 150, height: 100, backgroundColor: 'red'}}>
<Text style={{margin: 30}}>Button</Text>
<TextInput
multiline
onScroll={this.onScroll}
/>
</View>
</TouchableNativeFeedback>
)
@@ -229,7 +240,6 @@ export class EventsTest extends React.Component {
}
// App State
function appStateListener(state: string) {
console.log("New state: " + state);
}
@@ -245,7 +255,6 @@ function appStateIOSTest() {
}
// ViewPagerAndroid
export class ViewPagerAndroidTest {
render() {
return (
@@ -462,45 +471,52 @@ deviceEventEmitterStatic.addListener("keyboardWillShow", data => true);
deviceEventEmitterStatic.addListener("keyboardWillShow", data => true, {});
class TextInputRefTest extends React.Component<{}, {username: string}> {
class TextInputTest extends React.Component<{}, {username: string}> {
username: TextInput | null = null;
handleUsernameChange(text: string) {
handleUsernameChange = (text: string) => {
console.log(`text: ${ text }`);
}
onScroll = (e: NativeSyntheticEvent<TextInputScrollEventData>) => {
testNativeSyntheticEvent(e);
console.log(`x: ${ e.nativeEvent.contentOffset.x }`);
console.log(`y: ${ e.nativeEvent.contentOffset.y }`);
}
handleOnBlur = (e: NativeSyntheticEvent<TextInputFocusEventData>) => {
testNativeSyntheticEvent(e);
}
handleOnFocus = (e: NativeSyntheticEvent<TextInputFocusEventData>) => {
testNativeSyntheticEvent(e);
}
render() {
return (
<View>
<Text onPress={() => this.username.focus()}>Username</Text>
<TextInput
ref={input => this.username = input}
value={this.state.username}
onChangeText={this.handleUsernameChange.bind(this)}
onChangeText={this.handleUsernameChange}
/>
<TextInput
multiline
onScroll={this.onScroll}
/>
<TextInput
onBlur={this.handleOnBlur}
onFocus={this.handleOnFocus}
/>
</View>
);
}
}
class TextInputFocusBlurEventTest extends React.Component {
handleOnBlur(e: NativeSyntheticEvent<TextInputFocusEventData>) {
}
handleOnFocus(e: NativeSyntheticEvent<TextInputFocusEventData>) {
}
render() {
return (
<View>
<TextInput
onBlur={(e: NativeSyntheticEvent<TextInputFocusEventData>) => this.handleOnBlur(e)}
onFocus={(e: NativeSyntheticEvent<TextInputFocusEventData>) => this.handleOnFocus(e)}
/>
</View>
)
}
}
class StatusBarTest extends React.Component {
render() {
StatusBar.setBarStyle("dark-content", true);
@@ -517,6 +533,26 @@ class StatusBarTest extends React.Component {
}
}
export class ImageTest extends React.Component {
onLoad(e: NativeSyntheticEvent<ImageLoadEventData>) {
testNativeSyntheticEvent(e);
console.log('height:', e.nativeEvent.source.height);
console.log('width:', e.nativeEvent.source.width);
console.log('url:', e.nativeEvent.source.url);
}
render() {
return (
<View>
<Image
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
onLoad={this.onLoad}
/>
</View>
);
}
}
class StylePropsTest extends React.PureComponent {
render() {
const uri = 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png'
+1 -1
View File
@@ -576,7 +576,7 @@ export interface NavigationScreenProp<S, P = NavigationParams> {
closeDrawer: () => any;
toggleDrawer: () => any;
getParam: <T extends keyof P>(param: T, fallback?: P[T]) => P[T];
setParams: (newParams: P) => boolean;
setParams: (newParams: Partial<P>) => boolean;
addListener: (
eventName: string,
callback: NavigationEventCallback
@@ -489,3 +489,28 @@ const CustomHeaderStack = createStackNavigator({
}
}
});
interface ScreenProps {
name: string;
onPlay(): void;
}
class SetParamsTest extends React.Component<NavigationScreenProps<ScreenProps>> {
componentDidMount() {
this.props.navigation.setParams({
onPlay: this.onPlay
});
}
onPlay = () => {
//
}
render() {
const name = this.props.navigation.getParam('name');
return (
<Text>My name is {name}</Text>
);
}
}
+3 -3
View File
@@ -26,7 +26,7 @@ export type JQueryAjaxSettingsBase =
/**
* Same as jQuery v3 `JQuery.EventHandlerBase`.
*/
export type JQueryEventHandlerBase<TContext extends object, T> =
export type JQueryEventHandlerBase<TContext, T> =
(this: TContext, t: T, ...args: any[]) => void | false;
/**
@@ -221,7 +221,7 @@ export interface Options<Result = DataFormat | GroupedDataFormat, RemoteResult =
// jQuery And Select2 Plugin
// --------------------------------------------------------------------------
export interface Select2Plugin<TElement extends Node = HTMLElement> {
export interface Select2Plugin<TElement = HTMLElement> {
amd: { require: Require; };
defaults: {
@@ -252,7 +252,7 @@ export interface Select2Plugin<TElement extends Node = HTMLElement> {
}
declare global {
interface JQuery<TElement extends Node = HTMLElement> {
interface JQuery<TElement = HTMLElement> {
select2: Select2Plugin<TElement>;
data(key: "select2"): Select2;
+36
View File
@@ -149,6 +149,15 @@ export class Profile {
* Configuration options for the FirefoxDriver.
*/
export class Options {
/**
* Specify additional command line arguments that should be used when starting
* the Firefox browser.
*
* @param {...(string|!Array<string>)} args The arguments to include.
* @return {!Options} A self reference.
*/
addArguments(...args: string[]): Options;
/**
* Sets the browser to be in headless mode.
*
@@ -156,6 +165,33 @@ export class Options {
*/
headless(): Options;
/**
* Sets the initial window size when running in
* {@linkplain #headless headless} mode.
*
* @param {{width: number, height: number}} size The desired window size.
* @return {!Options} A self reference.
* @throws {TypeError} if width or height is unspecified, not a number, or
* less than or equal to 0.
*/
windowSize(size: { width: number, height: number }): Options;
/**
* Add extensions that should be installed when starting Firefox.
*
* @param {...string} paths The paths to the extension XPI files to install.
* @return {!Options} A self reference.
*/
addExtensions(...paths: string[]): Options;
/**
* @param {string} key the preference key.
* @param {(string|number|boolean)} value the preference value.
* @return {!Options} A self reference.
* @throws {TypeError} if either the key or value has an invalid type.
*/
setPreference(key: string, value: string | number | boolean): Options;
/**
* Sets the profile to use. The profile may be specified as a
* {@link Profile} object or as the path to an existing Firefox profile to use
+46 -1
View File
@@ -2160,6 +2160,21 @@ export class Builder {
*/
setChromeOptions(options: chrome.Options): Builder;
/**
* @return {chrome.Options} the Chrome specific options currently configured
* for this builder.
*/
getChromeOptions(): chrome.Options;
/**
* Sets the service builder to use for managing the chromedriver child process
* when creating new Chrome sessions.
*
* @param {chrome.ServiceBuilder} service the service to use.
* @return {!Builder} A self reference.
*/
setChromeService(service: chrome.ServiceBuilder): Builder;
/**
* Sets the control flow that created drivers should execute actions in. If
* the flow is never set, or is set to {@code null}, it will use the active
@@ -2181,6 +2196,15 @@ export class Builder {
*/
setEdgeOptions(options: edge.Options): Builder;
/**
* Sets the {@link edge.ServiceBuilder} to use to manage the
* MicrosoftEdgeDriver child process when creating sessions locally.
*
* @param {edge.ServiceBuilder} service the service to use.
* @return {!Builder} a self reference.
*/
setEdgeService(service: edge.ServiceBuilder): Builder;
/**
* Sets whether native events should be used.
* @param {boolean} enabled Whether to enable native events.
@@ -2199,6 +2223,21 @@ export class Builder {
*/
setFirefoxOptions(options: firefox.Options): Builder;
/**
* @return {firefox.Options} the Firefox specific options currently configured
* for this instance.
*/
getFirefoxOptions(): firefox.Options;
/**
* Sets the {@link firefox.ServiceBuilder} to use to manage the geckodriver
* child process when creating Firefox sessions locally.
*
* @param {firefox.ServiceBuilder} service the service to use.
* @return {!Builder} a self reference.
*/
setFirefoxService(service: firefox.ServiceBuilder): Builder;
/**
* Set Internet Explorer specific {@linkplain ie.Options options} for drivers
* created by this builder. Any proxy settings defined on the given options
@@ -2246,7 +2285,13 @@ export class Builder {
* @param {!safari.Options} options The Safari options to use.
* @return {!Builder} A self reference.
*/
setSafari(options: safari.Options): Builder;
setSafariOptions(options: safari.Options): Builder;
/**
* @return {safari.Options} the Safari specific options currently configured
* for this instance.
*/
getSafariOptions(): safari.Options;
/**
* Sets how elements should be scrolled into view for interaction.
+6
View File
@@ -25,6 +25,12 @@ function TestFirefoxDriver() {
function TestFirefoxOptions() {
let options: firefox.Options = new firefox.Options();
options = options.addArguments('foo', 'bar');
options = options.windowSize({ width: 320, height: 480 });
options = options.addExtensions('foo', 'bar');
options = options.setPreference('a', 1);
options = options.setPreference('a', true);
options = options.setPreference('a', '1');
options = options.setBinary('binary');
options = options.setBinary(new firefox.Binary());
options = options.setLoggingPreferences(new webdriver.logging.Preferences());
+11
View File
@@ -1,8 +1,10 @@
import * as webdriver from 'selenium-webdriver';
import * as chrome from 'selenium-webdriver/chrome';
import * as edge from 'selenium-webdriver/edge';
import * as firefox from 'selenium-webdriver/firefox';
import * as http from 'selenium-webdriver/http';
import * as remote from 'selenium-webdriver/remote';
import * as safari from 'selenium-webdriver/safari';
import * as testing from 'selenium-webdriver/testing';
function TestBuilder() {
@@ -18,16 +20,25 @@ function TestBuilder() {
builder = builder.setAlertBehavior('behavior');
builder = builder.setChromeOptions(new chrome.Options());
builder = builder.setChromeService(new chrome.ServiceBuilder());
builder = builder.setControlFlow(new webdriver.promise.ControlFlow());
builder = builder.setEdgeOptions(new edge.Options());
builder = builder.setEdgeService(new edge.ServiceBuilder());
builder = builder.setEnableNativeEvents(true);
builder = builder.setFirefoxOptions(new firefox.Options());
builder = builder.setFirefoxService(new firefox.ServiceBuilder());
builder = builder.setLoggingPrefs(new webdriver.logging.Preferences());
builder = builder.setLoggingPrefs({ key: 'value' });
builder = builder.setProxy({ proxyType: 'type' });
builder = builder.setSafariOptions(new safari.Options());
builder = builder.setScrollBehavior(1);
builder = builder.usingServer('http://someserver');
builder = builder.withCapabilities(new webdriver.Capabilities());
builder = builder.withCapabilities({ something: true });
const chromeOptions: chrome.Options = builder.getChromeOptions();
const firefoxOptions: firefox.Options = builder.getFirefoxOptions();
const safariOptions: safari.Options = builder.getSafariOptions();
}
declare const promise: webdriver.promise.Promise<string>;
+437 -422
View File
@@ -1,8 +1,9 @@
// Type definitions for shopify-buy 0.4.2
// Type definitions for shopify-buy 1.4.0
// Project: http://shopify.github.io/js-buy-sdk/api/
// Definitions by: Martin Köhn <https://github.com/openminder>
// Stephen Traiforos <https://github.com/straiforos>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TypeScript Version: 2.7
/**
* The JS Buy SDK is a lightweight library that allows you to build ecommerce into any website.
@@ -12,441 +13,455 @@
* website or javascript application. This is helpful if you already have a website and need to add ecommerce
* or only need a simple buy button on your site.
*/
declare namespace ShopifyBuy {
/**
* Create a ShopClient. This is the main entry point to the SDK.
export function buildClient(config: Config): Client;
export interface Client {
product: ShopifyBuy.ProductResource;
collection: ShopifyBuy.CollectionResource;
checkout: ShopifyBuy.CheckoutResource;
shop: ShopResource;
image: Image;
fetchNextPage<T extends GraphModel>(nextArray: T[]): T[];
}
export interface Config {
domain: string;
storefrontAccessToken: string;
}
export interface ProductResource {
fetch(id: string): Promise<Product>;
fetchAll(pageSizeopt?: number): Promise<Product[]>;
fetchByHandle(handle: string): Promise<Product>;
fetchMultiple(ids: string[]): Promise<Product[]>;
fetchQuery(query: Query): Promise<Product[]>;
/**
* Product Helper Namespace
* @link https://shopify.github.io/js-buy-sdk/ProductResource.html
*/
variantForOptions(product: Product, options: Option): ProductVariant;
}
export interface CollectionResource {
fetch(id: string): Promise<Product[]>;
fetchWithProducts(id: string): Promise<any[]>; // TODO fix to be a type: Docs: Fetches a single collection by ID on the shop, not including products.
fetchAll(pageSizeopt?: number): Promise<any[]>; // TODO fix to be a type: Docs: Fetches all collections on the shop, not including products.
fetchAllWithProducts(): Promise<any[]>; // TODO fix to be a type: DOC: Fetches all collections on the shop, including products.
fetchWithProducts(id: string): Promise<any[]>; // TODO fix to be a type: DOC: Fetches all collections on the shop, including products.
fetchByHandle(handle: string): Promise<any[]>; // TODO fix to be a type: DOC: Fetches a collection by handle on the shop. Assuming it does not give products
fetchQuery(query: Query): Promise<any[]>; // TODO fix to be a type: DOC: Fetches a collection by handle on the shop. Assuming it does not give products
}
export interface CheckoutResource {
create(
email?: string,
lineItems?: LineItem[],
shippingAddress?: Address,
note?: string,
customAttributes?: AttributeInput[]
): Promise<Cart>;
fetch(id: string): Promise<Cart>;
addLineItems(checkoutId: string | number, lineItems: LineItem[]): Promise<Cart>;
/**
* Remove all line items from cart
*/
clearLineItems(
checkoutId: string | number,
lineItems: LineItem[]
): Promise<Cart>;
/**
* Add items to cart. Updates cart's lineItems
*/
addVariants(item: Item, nextItem?: Array<Item>): Promise<Cart>;
/**
* Remove a line item from cart based on line item id
*/
removeLineItem(
checkoutId: string | number,
lineItemIds: string[]
): Promise<Cart>;
/**
* Update a line item quantity based on line item id
*/
updateLineItem(
checkoutId: string | number,
lineItems: AttributeInput[]
): Promise<Cart>;
}
export interface ShopResource {
fetchInfo(): Promise<Shop>;
fetchPolicies(): Promise<Shop>;
}
export interface Query {
/**
* query: title, collection_type, updated_at
* TODO probably will remove before Defintely Typed PR,
* as their community guidelines
*/
query: string;
sortBy: string;
after?: string;
before?: string;
first?: string;
last?: string;
reverse?: boolean;
}
export interface Product extends GraphModel {
/**
* A product description.
*/
description: string;
/**
* Product unique ID
*/
id: string | number;
/**
* An Array of Objects that contain meta data about an image including src of the images.
*/
images: Array<Image>;
/**
* All variants of a product.
*/
variants: Array<ProductVariant>;
/**
* Get an array of Product Options. Product Options can be used to define
* the currently selectedVariant from which you can get a checkout url (ProductVariant.checkoutUrl)
* or can be added to a cart (Cart.createLineItemsFromVariants).
*/
options: Array<Option>;
/**
* Retrieve variant for currently selected options. By default the first value in each option is selected
* which means selectedVariant will never be null. With a selectedVariant you can
* create checkout url (ProductVariant.checkoutUrl) or
* it can be added to a cart (Cart.createLineItemsFromVariants).
*/
selectedVariant: ProductVariant;
/**
* Retrieve image for currently selected variantImage.
*/
selectedVariantImage: Image;
/**
* A read only Array of Strings represented currently selected option values. eg. ["Large", "Red"]
*/
selections: Array<string>;
/**
* The product title
*/
title: string;
}
export interface ProductVariant extends GraphModel {
/**
* Variant in stock. Always true if inventory tracking is disabled.
*/
available: boolean;
/**
* Compare at price for variant. The compareAtPrice would be the price of the
* product previously before the product went on sale.
*/
compareAtPrice: string;
/**
* Price of variant, formatted according to shop currency format string. For instance "$10.00"
*/
formattedPrice: string;
/**
* Variant weight in grams. If no weight is defined grams will be 0.
*/
grams: number;
/**
* Variant unique ID
*/
id: string | number;
/**
* Image for variant
*/
image: Image;
/**
* Image variants available for a variant.
*/
imageVariant: Array<ImageVariant>;
/**
* Option values associated with this variant, ex {name: "color", value: "Blue"}
*/
optionValues: Array<OptionValue>;
/**
* Price of the variant. The price will be in the following form: "10.00"
*/
price: string;
/**
* ID of product variant belongs to
*/
productId: string | number;
/**
* Title of product variant belongs to
*/
productTitle: string;
/**
* Title of variant
*/
title: string;
/*
* Get a checkout url for a specific product variant.
* You can optionally pass a quantity.
* If no quantity is passed then quantity will default to 1.
*/
checkoutUrl(quantitiy: number): string;
}
export interface Option {
/**
* name of option (ex. "Size", "Color")
*/
name: string;
/**
* get/set the currently selected option value with one of the values from the Product Options/values array.
* For instance if the option values array had the following ["Large", "Medium", "Small"] setting selected to be
* "Large", "Medium", or "Small" would be valid any other value would throw an Error.
*/
selected: string;
/**
* an Array possible values for option. For instance if this option
* is a "Size" option an example value for values could be: ["Large", "Medium", "Small"]
*/
values: Array<OptionValue>;
}
export interface OptionValue {
name: string;
option_id: string;
value: any;
}
export interface Collection {
handle: string;
body_html: string;
image: Image;
id: string;
metafields: any[];
published: boolean;
published_at: string;
published_scope: string;
sort_order: string;
template_suffix: string;
title: string;
updated_at: string;
}
export interface Cart extends GraphModel {
/**
* Get checkout URL for current cart
*/
checkoutUrl: string;
/**
* get ID for current cart
*/
id: string | number;
/**
* Gets the total quantity of all line items. Example: you've added two variants
* with quantities 3 and 2. lineItemCount will be 5.
*/
lineItemCount: number;
/**
* Get an Array of CartLineItemModel's
*/
lineItems: LineItem[];
/**
* Get current subtotal price for all line items.
* Example: two items have been added to the cart that cost $1.25 then the subtotal will be 2.50
*/
subtotal: string;
}
export interface LineItem extends GraphModel {
/**
* Compare at price for variant. The compareAtPrice would be the price of the product
* previously before the product went on sale.
* If no compareAtPrice is set then this value will be null. An example value: "5.00".
*/
compare_at_price: string;
/**
* Variant's weight in grams. If no weight is set then 0 is returned.
*/
grams: number;
/**
* A line item ID.
*/
id: string | number;
/**
* Variant's image.
*/
image: Image;
/**
* The total price for this line item. For instance if the variant costs 1.50 and you have a
* quantity of 2 then line_price will be 3.00.
*/
line_price: string;
/**
* Price of the variant. For example: "5.00".
*/
price: string;
/**
* ID of variant's product.
*/
product_id: string | number;
/**
* Count of variants to order.
*/
quantity: number;
/**
* Product title of variant's parent product.
*/
title: string;
/**
* ID of line item variant.
*/
variant_id: string | number;
/**
* Title of variant.
*/
variant_title: string;
}
export interface Item {
variant: ProductVariant;
quantity: number;
}
export interface Address {
address1: String;
address2: String;
city: String;
company: String;
country: String;
firstName: String;
lastName: String;
phone: String;
province: String;
zip: String;
}
/**
* https://help.shopify.com/api/custom-storefronts/storefront-api/reference/input_object/attributeinput
* https://help.shopify.com/api/custom-storefronts/storefront-api/reference/input_object/checkoutlineitemupdateinput
*/
export function buildClient(configAttrs: Shopify.Config): Shopify.ShopClient
export interface AttributeInput {
key?: string;
value?: string;
id?: string | number;
quantity?: number;
variantId?: string;
}
/**
* TODO Validate schema matches js-buy
* Derived from REST API Docs: https://help.shopify.com/api/custom-storefronts/storefront-api/reference/object/shop#fields
*/
export interface Shop {
description: string;
moneyFormat: string;
name: string;
/**
* TODO Add types for the Shop properties below
* PaymentSettings, ShopPolicy etc
*/
paymentSettings: any;
primaryDomain: any;
privacyPolicy: any;
refundPolicy: any;
termsOfService: any;
}
/**
* Internal Image description
*/
interface Image {
id: string | number
created_at: string
position: number
updated_at: string
product_id: string
src: string
variant_ids: Array<string>
export interface Image extends GraphModel {
id: string | number;
created_at: string;
position: number;
updated_at: string;
product_id: string;
src: string;
variant_ids: Array<string>;
}
interface ImageVariant {
name: string,
dimensions: string,
src: string
export interface ImageVariant extends Image {
name: string;
dimensions: string;
src: string;
/**
* Returns src URL for new image size/variant
* @param image The image you would like a different size for.
* @param options Image Max width and height configuration.
*/
imageForSize(image: Image, options: ImageOptions): string;
}
interface OptionValue {
name: string,
option_id: string | number,
value: any
export interface ImageOptions {
maxWidth: number;
maxHeight: number;
}
/**
* Internal BaseModel class
*/
class BaseModel {
constructor(attrs: any, metaAttrs: any)
let NO_IMAGE_URI: string;
attrs: any
serializer: any
adapter: any
shopClient: any
/*
* Base Model for the higher level returned objects from the API using GraphQL
*/
export interface GraphModel {
attrs?: any
onlineStoreUrl?: string
}
var NO_IMAGE_URI: string;
/**
* This namespace contains all globally accessible classes
*/
export namespace Shopify {
/**
* Base Shopify Client config object
*/
interface Config {
/**
* An API Key for your store. Documentation how to get an API Key:
* https://help.shopify.com/api/sdks/js-buy-sdk/getting-started#api-key
*/
apiKey: string
/**
* Typically will be 6 which is the Buy Button App Id. For more info on App Id see:
* https://help.shopify.com/api/sdks/js-buy-sdk/getting-started#app-id
*/
appId: string
/**
* Your shop's full myshopify.com domain. For example: embeds.myshopify.com
*/
domain: string
}
/**
* Cart item, that should be added to the card
*/
interface CartModelItem {
variant: Shopify.ProductVariantModel
quantity: number
}
/**
* Shopify-Buy-SDK Client to handle products and cart
*/
class ShopClient {
/**
* Config data to be used throughout all API interaction
*/
constructor(config?: Config)
/**
* Creates a CartModel instance.
*/
createCart(): Promise<CartModel>
/**
* This function will return an Array of collections from your store
*/
fetchAllCollections(): Promise<Array<any>>
/**
* This function will return an Array of products from your store
*/
fetchAllProducts(): Promise<Array<ProductModel>>
/**
* Retrieve a previously created cart by its key.
*/
fetchCart(id: string): Promise<CartModel>
/**
* Fetch one collection by its ID.
*/
fetchCollection(id: string | number): Promise<any>
/**
* Fetch one product by its ID.
*/
fetchProduct(id: string | number): Promise<ProductModel>
/**
* Fetches a list of collections matching a specified query.
*/
fetchQueryCollections(query?: any): Promise<Array<any>>
/**
* Fetches a list of products matching a specified query.
*/
fetchQueryProducts(query?: any): Promise<Array<ProductModel>>
/**
* This method looks up a reference in localStorage to the most recent cart.
* If one is not found, creates one. If the cart the reference points to doesn't exist,
* create one and store the new reference.
*/
fetchRecentCart(): Promise<CartModel>
}
/**
* Class for products returned by fetch('product')
*/
class ProductModel extends BaseModel {
constructor()
/**
* A product description.
*/
description: string
/**
* Product unique ID
*/
id: string | number
/**
* An Array of Objects that contain meta data about an image including src of the images.
*/
images: Array<Image>
/**
* All variants of a product.
*/
variants: Array<ProductVariantModel>
/**
* Get an array of ProductOptionModels. ProductOptionModels can be used to define
* the currently selectedVariant from which you can get a checkout url (ProductVariantModel.checkoutUrl)
* or can be added to a cart (CartModel.createLineItemsFromVariants).
*/
options: Array<ProductOptionModel>
/**
* Retrieve variant for currently selected options. By default the first value in each option is selected
* which means selectedVariant will never be null. With a selectedVariant you can
* create checkout url (ProductVariantModel.checkoutUrl) or
* it can be added to a cart (CartModel.createLineItemsFromVariants).
*/
selectedVariant: ProductVariantModel
/**
* Retrieve image for currently selected variantImage.
*/
selectedVariantImage: Image
/**
* A read only Array of Strings represented currently selected option values. eg. ["Large", "Red"]
*/
selections: Array<string>
/**
* The product title
*/
title: string
}
/**
* Model for product variant
*/
class ProductVariantModel extends BaseModel {
constructor()
/*
* Get a checkout url for a specific product variant.
* You can optionally pass a quantity.
* If no quantity is passed then quantity will default to 1.
*/
checkoutUrl(quantitiy: number): string
/**
* Variant in stock. Always true if inventory tracking is disabled.
*/
available: boolean
/**
* Compare at price for variant. The compareAtPrice would be the price of the
* product previously before the product went on sale.
*/
compareAtPrice: string
/**
* Price of variant, formatted according to shop currency format string. For instance "$10.00"
*/
formattedPrice: string
/**
* Variant weight in grams. If no weight is defined grams will be 0.
*/
grams: number
/**
* Variant unique ID
*/
id: string | number
/**
* Image for variant
*/
image: Image
/**
* Image variants available for a variant.
*/
imageVariant: Array<ImageVariant>
/**
* Option values associated with this variant, ex {name: "color", value: "Blue"}
*/
optionValues: Array<OptionValue>
/**
* Price of the variant. The price will be in the following form: "10.00"
*/
price: string
/**
* ID of product variant belongs to
*/
productId: string | number
/**
* Title of product variant belongs to
*/
productTitle: string
/**
* Title of variant
*/
title: string
}
/**
* Class for product option
*/
class ProductOptionModel extends BaseModel {
constructor()
/**
* name of option (ex. "Size", "Color")
*/
name: string
/**
* get/set the currently selected option value with one of the values from the ProductOptionModel/values array.
* For instance if the option values array had the following ["Large", "Medium", "Small"] setting selected to be
* "Large", "Medium", or "Small" would be valid any other value would throw an Error.
*/
selected: string
/**
* an Array possible values for option. For instance if this option
* is a "Size" option an example value for values could be: ["Large", "Medium", "Small"]
*/
values: Array<any>
}
/**
* Class for cart model
*/
class CartModel extends BaseModel {
constructor()
/**
* Remove all line items from cart
*/
clearLineItems(): Promise<CartModel>
/**
* Add items to cart. Updates cart's lineItems
*/
addVariants(item: CartModelItem, nextItem?: Array<CartModelItem>): Promise<CartModel>
/**
* Add items to the cart. Updates cart's lineItems based on variants passed in.
*/
createLineItemsFromVariants(...items: CartModelItem[] ): Promise<CartModel>
/**
* Remove a line item from cart based on line item id
*/
removeLineItem(id: string | number): Promise<CartModel>
/**
* Update a line item quantity based on line item id
*/
updateLineItem(id: string | number, quantitiy: number): Promise<CartModel>
/**
* Force update of cart model on server. This function will only be used in advanced
* situations and does not need to be called explicitly to update line items.
* It is automatically called after createLineItemsFromVariants, updateLineItem,
* removeLineItem, and removeLineItem
*/
updateModel(): Promise<CartModel>
/**
* Get checkout URL for current cart
*/
checkoutUrl: string
/**
* get ID for current cart
*/
id: string | number
/**
* Gets the total quantity of all line items. Example: you've added two variants
* with quantities 3 and 2. lineItemCount will be 5.
*/
lineItemCount: number
/**
* Get an Array of CartLineItemModel's
*/
lineItems: Array<CartLineItemModel>
/**
* Get current subtotal price for all line items.
* Example: two items have been added to the cart that cost $1.25 then the subtotal will be 2.50
*/
subtotal: string
}
class CartLineItemModel extends BaseModel {
constructor()
/**
* Compare at price for variant. The compareAtPrice would be the price of the product
* previously before the product went on sale.
* If no compareAtPrice is set then this value will be null. An example value: "5.00".
*/
compare_at_price: string
/**
* Variant's weight in grams. If no weight is set then 0 is returned.
*/
grams: number
/**
* A line item ID.
*/
id: string | number
/**
* Variant's image.
*/
image: Image
/**
* The total price for this line item. For instance if the variant costs 1.50 and you have a
* quantity of 2 then line_price will be 3.00.
*/
line_price: string
/**
* Price of the variant. For example: "5.00".
*/
price: string
/**
* ID of variant's product.
*/
product_id: string | number
/**
* Count of variants to order.
*/
quantity: number
/**
* Product title of variant's parent product.
*/
title: string
/**
* ID of line item variant.
*/
variant_id: string | number
/**
* Title of variant.
*/
variant_title: string
}
}
}
declare module "shopify-buy" {
export = ShopifyBuy
export = ShopifyBuy;
}
+34 -31
View File
@@ -3,22 +3,21 @@
/* Build new ShopifyBuy client
============================================================ */
let client = ShopifyBuy.buildClient({
apiKey: 'bf081e860bc9dc1ce0654fdfbc20892d',
domain: 'embeds',
appId: '6'
domain: 'buyapitypestest.myshopify.com',
storefrontAccessToken: '9f30a6806b613e0cb551b7db59c5ca02'
});
var product : ShopifyBuy.Shopify.ProductModel;
var cart : ShopifyBuy.Shopify.CartModel;
var product : ShopifyBuy.Product;
var cart : ShopifyBuy.Cart;
var cartLineItemCount : number;
if(localStorage.getItem('lastCartId')) {
client.fetchCart(localStorage.getItem('lastCartId')).then(function(remoteCart : ShopifyBuy.Shopify.CartModel) {
client.checkout.fetch(localStorage.getItem('lastCartId')).then(function(remoteCart : ShopifyBuy.Cart) {
cart = remoteCart;
cartLineItemCount = cart.lineItems.length;
renderCartItems();
});
} else {
client.createCart().then(function (newCart : ShopifyBuy.Shopify.CartModel) {
client.checkout.create().then(function (newCart : ShopifyBuy.Cart) {
cart = newCart;
localStorage.setItem('lastCartId', ""+cart.id);
cartLineItemCount = 0;
@@ -29,11 +28,11 @@ var previousFocusItem : any;
/* Fetch product and init
============================================================ */
client.fetchProduct('3614436099').then(function (fetchedProduct : ShopifyBuy.Shopify.ProductModel) {
client.product.fetch('3614436099').then(function (fetchedProduct : ShopifyBuy.Product) {
product = fetchedProduct;
var selectedVariant : ShopifyBuy.Shopify.ProductVariantModel = product.selectedVariant;
var selectedVariant : ShopifyBuy.ProductVariant = product.selectedVariant;
var selectedVariantImage : any = product.selectedVariantImage;
var currentOptions : ShopifyBuy.Shopify.ProductOptionModel[] = product.options;
var currentOptions : ShopifyBuy.Option[] = product.options;
var variantSelectors = generateSelectors(product);
$('.variant-selectors').html(""+variantSelectors);
@@ -49,8 +48,8 @@ client.fetchProduct('3614436099').then(function (fetchedProduct : ShopifyBuy.Sho
/* Generate DOM elements for variant selectors
============================================================ */
function generateSelectors(product : ShopifyBuy.Shopify.ProductModel) {
var elements = product.options.map(function(option : ShopifyBuy.Shopify.ProductOptionModel) {
function generateSelectors(product : ShopifyBuy.Product) {
var elements = product.options.map(function(option : ShopifyBuy.Option) {
var optionsHtml = option.values.map(function(value : any) {
return '<option value="' + value + '">' + value + '</option>';
});
@@ -121,16 +120,16 @@ function bindEventListeners() {
/* Variant option change handler
============================================================ */
function attachOnVariantSelectListeners(product : ShopifyBuy.Shopify.ProductModel) {
function attachOnVariantSelectListeners(product : ShopifyBuy.Product) {
$('.variant-selectors').on('change', 'select', function(event) {
var $element : any = $(event.target);
var name : string = $element.attr('name');
var value : string = $element.val();
product.options.filter(function(option : ShopifyBuy.Shopify.ProductOptionModel) {
product.options.filter(function(option : ShopifyBuy.Option) {
return option.name === name;
})[0].selected = value;
var selectedVariant : ShopifyBuy.Shopify.ProductVariantModel = product.selectedVariant;
var selectedVariant : ShopifyBuy.ProductVariant = product.selectedVariant;
var selectedVariantImage : any = product.selectedVariantImage;
updateProductTitle(product.title);
updateVariantImage(selectedVariantImage);
@@ -155,13 +154,13 @@ function updateVariantImage(image : any) {
/* Update product variant title based on selected variant
============================================================ */
function updateVariantTitle(variant : ShopifyBuy.Shopify.ProductVariantModel) {
function updateVariantTitle(variant : ShopifyBuy.ProductVariant) {
$('#buy-button-1 .variant-title').text(variant.title);
}
/* Update product variant price based on selected variant
============================================================ */
function updateVariantPrice(variant : ShopifyBuy.Shopify.ProductVariantModel) {
function updateVariantPrice(variant : ShopifyBuy.ProductVariant) {
$('#buy-button-1 .variant-price').text('$' + variant.price);
}
@@ -171,7 +170,7 @@ function buyButtonClickHandler(evt : any) {
evt.preventDefault();
var id : string | number = product.selectedVariant.id;
var quantity : number;
var cartLineItem : ShopifyBuy.Shopify.CartLineItemModel = findCartItemByVariantId(id);
var cartLineItem : ShopifyBuy.LineItem = findCartItemByVariantId(id);
quantity = cartLineItem ? cartLineItem.quantity + 1 : 1;
@@ -183,11 +182,11 @@ function buyButtonClickHandler(evt : any) {
/* Update product variant quantity in cart
============================================================ */
function updateQuantity(fn : Function, variantId : string | number) {
var variant : ShopifyBuy.Shopify.ProductVariantModel = product.variants.filter(function (variant : ShopifyBuy.Shopify.ProductVariantModel) {
var variant : ShopifyBuy.ProductVariant = product.variants.filter(function (variant : ShopifyBuy.ProductVariant) {
return (variant.id === variantId);
})[0];
var quantity : number;
var cartLineItem : ShopifyBuy.Shopify.CartLineItemModel = findCartItemByVariantId(variant.id);
var cartLineItem : ShopifyBuy.LineItem = findCartItemByVariantId(variant.id);
if (cartLineItem) {
quantity = fn(cartLineItem.quantity);
updateVariantInCart(cartLineItem, quantity);
@@ -214,10 +213,10 @@ function incrementQuantity(variantId : string | number) {
============================================================ */
function fieldQuantityHandler(evt : any) {
var variantId : string | number = parseInt($(this).closest('.cart-item').attr('data-variant-id'), 10);
var variant : ShopifyBuy.Shopify.ProductVariantModel = product.variants.filter(function (variant : ShopifyBuy.Shopify.ProductVariantModel) {
var variant : ShopifyBuy.ProductVariant = product.variants.filter(function (variant : ShopifyBuy.ProductVariant) {
return (variant.id === variantId);
})[0];
var cartLineItem : ShopifyBuy.Shopify.CartLineItemModel = findCartItemByVariantId(variant.id);
var cartLineItem : ShopifyBuy.LineItem = findCartItemByVariantId(variant.id);
var quantity : number = evt.target.value;
if (cartLineItem) {
updateVariantInCart(cartLineItem, quantity);
@@ -264,9 +263,9 @@ function findCartItemByVariantId(variantId : string | number) {
/* Determine action for variant adding/updating/removing
============================================================ */
function addOrUpdateVariant(variant : ShopifyBuy.Shopify.ProductVariantModel, quantity : number) {
function addOrUpdateVariant(variant : ShopifyBuy.ProductVariant, quantity : number) {
openCart();
var cartLineItem : ShopifyBuy.Shopify.CartLineItemModel = findCartItemByVariantId(variant.id);
var cartLineItem : ShopifyBuy.LineItem = findCartItemByVariantId(variant.id);
if (cartLineItem) {
updateVariantInCart(cartLineItem, quantity);
@@ -279,10 +278,14 @@ function addOrUpdateVariant(variant : ShopifyBuy.Shopify.ProductVariantModel, qu
/* Update details for item already in cart. Remove if necessary
============================================================ */
function updateVariantInCart(cartLineItem : ShopifyBuy.Shopify.CartLineItemModel, quantity : number) {
function updateVariantInCart(cartLineItem : ShopifyBuy.LineItem, quantity : number) {
var variantId : string | number = cartLineItem.variant_id;
var cartLength : number = cart.lineItems.length;
cart.updateLineItem(cartLineItem.id, quantity).then(function(updatedCart : ShopifyBuy.Shopify.CartModel) {
let lineItemVariant: ShopifyBuy.AttributeInput = {
id: cartLineItem.id,
quantity
};
client.checkout.updateLineItem(cartLineItem.id, [lineItemVariant]).then(function(updatedCart : ShopifyBuy.Cart) {
var $cartItem = $('.cart').find('.cart-item[data-variant-id="' + variantId + '"]');
if (updatedCart.lineItems.length >= cartLength) {
$cartItem.find('.cart-item__quantity').val(cartLineItem.quantity);
@@ -306,11 +309,11 @@ function updateVariantInCart(cartLineItem : ShopifyBuy.Shopify.CartLineItemModel
/* Add 'quantity' amount of product 'variant' to cart
============================================================ */
function addVariantToCart(variant : ShopifyBuy.Shopify.ProductVariantModel, quantity : number) {
function addVariantToCart(variant : ShopifyBuy.ProductVariant, quantity : number) {
openCart();
cart.addVariants({ variant: variant, quantity: quantity }).then(function() {
var cartItem : ShopifyBuy.Shopify.CartLineItemModel = cart.lineItems.filter(function (item : ShopifyBuy.Shopify.CartLineItemModel ) {
client.checkout.addVariants({ variant: variant, quantity: quantity }).then(function() {
var cartItem : ShopifyBuy.LineItem = cart.lineItems.filter(function (item : ShopifyBuy.LineItem ) {
return (item.variant_id === variant.id);
})[0];
var $cartItem = renderCartItem(cartItem);
@@ -331,7 +334,7 @@ function addVariantToCart(variant : ShopifyBuy.Shopify.ProductVariantModel, quan
/* Return required markup for single item rendering
============================================================ */
function renderCartItem(lineItem : ShopifyBuy.Shopify.CartLineItemModel) {
function renderCartItem(lineItem : ShopifyBuy.LineItem) {
var lineItemEmptyTemplate = $('#CartItemTemplate').html();
var $lineItemTemplate = $(lineItemEmptyTemplate);
var itemImage = lineItem.image.src;
@@ -400,6 +403,6 @@ function updateCartTabButton() {
/* Set previously focused item for escape handler
============================================================ */
function setPreviousFocusItem(item : ShopifyBuy.Shopify.CartLineItemModel) {
function setPreviousFocusItem(item : ShopifyBuy.LineItem) {
previousFocusItem = item;
}
+14
View File
@@ -0,0 +1,14 @@
import UniversalRouter, { Params } from ".";
import { PathFunctionOptions } from 'path-to-regexp';
export interface GenerateUrlsOptions extends PathFunctionOptions {
/**
* Provide a function to stringifyQueryParams option to generate URL with query string from unknown route params.
*/
stringifyQueryParams?: (params: Params) => string;
}
/**
* In most web applications it's much simpler to just use a string for hyperlinks.
*/
export default function generateUrls(router: UniversalRouter, options?: GenerateUrlsOptions): (routeName: string, params?: Params) => string;
+90 -37
View File
@@ -1,32 +1,65 @@
// Type definitions for universal-router 1.2
// Type definitions for universal-router 6.0
// Project: https://github.com/kriasoft/universal-router
// Definitions by: Jack Moore <https://github.com/jtmthf>
// Tomek Łaziuk <https://github.com/tlaziuk>
// Lodin <https://github.com/Lodin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import pathToRegexp = require('path-to-regexp');
/**
* Params is a key/value object that represents extracted URL paramters. Each
* URL parameter resolves to a string.
* Params is a key/value object that represents extracted URL paramters.
* Each URL parameter resolves to a string.
*/
export interface Params {
[key: string]: string;
[_: string]: any;
}
/**
* Context represents the context that is passed as the second argument
* passed to resolve. By default, it only is require to contain a path, but
* can be extended by the way of generics.
* In addition to a URL path string, any arbitrary data can be passed to the `router.resolve()` method, that becomes available inside action functions.
*/
export interface Context {
path: string;
[_: string]: any;
}
/**
* ActionContext is similar to Context, with the exception of an added params
* object. ActionContext is passed as the first argument to the action
* function.
*/
export interface ActionContext extends Context {
params: Params;
export interface PathnameContext extends Context {
/**
* URL which was transmitted to `router.resolve()`.
*/
pathname: string;
}
export interface ActionContext<C extends Context, R = any> extends PathnameContext {
/**
* Current router instance.
*/
router: UniversalRouter<C, R>;
/**
* Matched route object.
*/
route: Route;
/**
* Middleware style function which can continue resolving.
*/
next: (resume?: boolean, parent?: Route, prevResult?: any) => Promise<R>;
/**
* Base URL path relative to the path of the current route.
*/
baseUrl: string;
/**
* Matched path.
*/
path: string;
/**
* Matched path params.
*/
params: Params;
/**
* An array of keys found in the path, see `path-to-regexp` documentation for details.
* @see https://github.com/pillarjs/path-to-regexp
*/
keys: pathToRegexp.Key[];
}
/**
@@ -34,35 +67,55 @@ export interface ActionContext extends Context {
* action function, and optional children which are an array of Route.
*
* @template C User context that is made union with ActionContext.
* @template R Result that every action function resolves to. If the action
* returns a Promise, R can be the type the Promise resolves to.
* @template R Result that every action function resolves to. If the action returns a Promise, R can be the type the Promise resolves to.
*/
export interface Route<C, R> {
path: string;
action(ctx: ActionContext & C, params: Params): R | Promise<R> | void;
children?: Routes<C, R>;
export interface Route<C extends Context = any, R = any> {
path?: string | RegExp | Array<string | RegExp>;
/**
* unique string
*/
name?: string;
/**
* automatically filled by the router
*/
parent?: Route | null;
/**
* array of route objects
*/
children?: Routes<C, R> | null;
/**
* action method should return anything except `null` or `undefined` to be resolved by router
* otherwise router will throw `Page not found` error if all matched routes returned nothing
*/
action?: (context: ActionContext<C, R> & C, params: Params) => R | Promise<R> | void;
}
/**
* Routes in an array of type Route.
* @template C User context that is made union with ActionContext.
* @template R Result that every action function resolves to. If the action
* returns a Promise, R can be the type the Promise resolves to.
* @template R Result that every action function resolves to. If the action returns a Promise, R can be the type the Promise resolves to.
*/
export type Routes<C, R> = Array<Route<C, R>>;
export type Routes<C extends Context = Context, R = any> = Array<Route<C, R>>;
export interface Options<C extends Context = Context, R = any> {
context?: C;
baseUrl?: string;
resolveRoute?: (context: ActionContext<C, R> & C, params: Params) => any;
errorHandler?: (error: Error & { context: C, code: number }) => any;
}
/**
* Resolve function that is given routes and a path or context object.
* Returns a Promise that resolves to result of the action function of the
* matched route.
*
* @template C User context that is made union with Context.
* @template R Result that every action function resolves to. If the action
* returns a Promise, R can be the type the Promise resolves to.
*
* @param routes - Single route or array of routes.
* @param pathOrContext - path to resolve or
* context object that contains the path along with other data.
* @return - Result of matched action function wrapped in a Promsie.
* @see https://github.com/kriasoft/universal-router/blob/v6.0.0/docs/api.md
*/
export function resolve<C, R>(routes: Routes<C, R> | Route<C, R>, pathOrContext: string | String | Context & C): Promise<R>;
export default class UniversalRouter<C extends Context = Context, R = any> {
constructor(routes: Routes<C, R> | Route<C, R>, options?: Options<C>)
/**
* Traverses the list of routes in the order they are defined until it finds the first route that matches provided URL path string
* and whose action function returns anything other than null or undefined.
*/
resolve(pathnameOrContext: string | PathnameContext): Promise<R>;
/**
* `path-to-regexp` function
*/
static pathToRegexp: typeof pathToRegexp;
}
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"path-to-regexp": "^2.2.0"
}
}
+2 -1
View File
@@ -20,6 +20,7 @@
},
"files": [
"index.d.ts",
"generateUrls.d.ts",
"universal-router-tests.ts"
]
}
}
+1 -4
View File
@@ -1,6 +1,3 @@
{
"extends": "dtslint/dt.json",
"rules": {
"ban-types": false
}
"extends": "dtslint/dt.json"
}
@@ -1,95 +1,74 @@
import { ActionContext, Params, resolve } from "universal-router";
import UniversalRouter from "universal-router";
import generateUrls from "universal-router/generateUrls";
// Test 1
const routes1 = [
{
path: "/one",
action: () => "Page One"
},
{
path: "/two",
action: () => "Page Two"
}
];
new UniversalRouter(
{
path: '',
name: 'root',
action: (context) => context.path,
},
{
context: {
user: 'name',
},
baseUrl: '/base',
errorHandler: (error) => {
console.error(error);
console.dir(error.context);
return error.code === 404
? '<h1>Page Not Found</h1>'
: '<h1>Oops! Something went wrong</h1>';
},
},
).resolve('/').then(console.log);
resolve(routes1, { path: "/one" })
.then(result => console.log(result));
new UniversalRouter({
path: '/admin',
children: [
{
path: '',
action: () => 'Admin Page',
},
{
path: '/users',
children: [
{
path: '',
action: () => 'User List',
},
{
path: '/:username',
action: () => 'User Profile',
},
],
},
],
}).resolve({ pathname: '/admin/users/john' })
.then(result => console.log(result));
// Test 2
const routes2 = [
{
path: "/hello/:username",
action: (context: ActionContext) => `Welcome, ${context.params["username"]}!`
}
];
resolve(routes2, { path: "/hello/john" })
.then(result => console.log(result));
// Test 3
const routes3 = [
{
path: "/hello/:username",
action: (ctx: ActionContext, { username }: Params) => `Welcome, ${username}!`
}
];
resolve(routes3, { path: "/hello/john" })
.then(result => console.log(result));
// Test 4
const routes4 = [
{
path: "/hello",
action: () => new Promise(resolve => {
setTimeout(() => resolve("Welcome!"), 1000);
})
}
];
resolve(routes4, { path: "/hello" })
.then(result => console.log(result));
// Test 5
const routes5 = [
{
path: "/hello/:username",
async action(ctx: ActionContext, { username }: Params) {
const waitable = async (name: string) => {
console.log(`Welcome ${name}`);
};
await waitable(username);
}
}
];
resolve(routes5, { path: "/hello/john" })
.then(result => console.log(result));
// Test 6
const routes6 = [
{ path: "/one", action: () => "<h1>Page One</h1>" },
{ path: "/two", action: () => "<h1>Page Two</h1>" }
];
resolve(routes6, { path: "/one" }).then(result => {
document.body.innerHTML = result || "<h1>Not Found</h1>";
new UniversalRouter({
path: '', // optional
async action({ next }) {
console.log('middleware: start');
const child = await next();
console.log('middleware: end');
return child;
},
children: [
{
path: '/hello',
action() {
console.log('route: return a result');
return 'Hello, world!';
},
},
],
});
// Test 7
interface Render {
render: typeof render;
}
const url = generateUrls(new UniversalRouter([
{ name: 'users', path: '/users' },
{ name: 'user', path: '/user/:username' },
], { baseUrl: '/base' }));
const routes7 = [
{ path: "/one", action: ({ render: func }: ActionContext & Render) => func("<h1>Page One</h1>") },
{ path: "/two", action: ({ render: func }: ActionContext & Render) => func("<h1>Page Two</h1>") }
];
function render(component: string) {
return new Promise(resolve => {
console.log(`Rendering... ${component}`);
});
}
resolve<Render, Promise<{}>>(routes7, { path: "/one", render });
url('users'); // => '/base/users'
url('user', { username: 'john' }); // => '/base/user/john'
+2 -1
View File
@@ -1,11 +1,12 @@
// Type definitions for zen-observable 0.5
// Project: https://github.com/zenparsing/zen-observable
// Definitions by: Kombu <https://github.com/aicest>
// JounQin <https://github.com/JounQin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare global {
interface SymbolConstructor {
observable: symbol;
readonly observable: symbol;
}
namespace ZenObservable {