@types/rax
Version:
TypeScript definitions for rax
1,210 lines (1,064 loc) • 130 kB
TypeScript
// for reference and documentation on how exactly to do it.
/// <reference path="global.d.ts" />
import * as CSS from "csstype";
import * as PropTypes from "prop-types";
type NativeAnimationEvent = AnimationEvent;
type NativeClipboardEvent = ClipboardEvent;
type NativeCompositionEvent = CompositionEvent;
type NativeDragEvent = DragEvent;
type NativeFocusEvent = FocusEvent;
type NativeKeyboardEvent = KeyboardEvent;
type NativeMouseEvent = MouseEvent;
type NativeTouchEvent = TouchEvent;
type NativePointerEvent = PointerEvent;
type NativeTransitionEvent = TransitionEvent;
type NativeUIEvent = UIEvent;
type NativeWheelEvent = WheelEvent;
type Booleanish = boolean | "true" | "false";
/**
* defined in scheduler/tracing
*/
interface SchedulerInteraction {
id: number;
name: string;
timestamp: number;
}
// eslint-disable-next-line @definitelytyped/export-just-namespace
export = Rax;
export as namespace Rax;
declare namespace Rax {
export const shared: {
Host: any;
Instance: RaxInstance;
Element: RaxElement;
flattenChildren: any;
};
/**
* ======================================================================
* Rax Elements
* ======================================================================
*/
type ElementType<P = any> =
| {
[K in keyof JSX.IntrinsicElements]: P extends JSX.IntrinsicElements[K] ? K : never;
}[keyof JSX.IntrinsicElements]
| ComponentType<P>;
type ComponentType<P = {}> = ComponentClass<P> | FunctionComponent<P>;
type JSXElementConstructor<P> =
| ((props: P) => RaxElement | null)
| (new(props: P) => Component<P, any>);
type Key = string | number;
interface RefObject<T> {
readonly current: T | null;
}
type Ref<T> =
| { bivarianceHack(instance: T | null): void }["bivarianceHack"]
| RefObject<T>
| null;
type LegacyRef<T> = string | Ref<T>;
/**
* Gets the instance type for a Rax element. The instance will be different for various component types:
*
* - Rax class components will be the class instance. So if you had `class Foo extends Component<{}> {}`
* and used `ElementRef<typeof Foo>` then the type would be the instance of `Foo`.
* - Rax stateless functional components do not have a backing instance and so `ElementRef<typeof Bar>`
* (when `Bar` is `function Bar() {}`) will give you the `undefined` type.
* - JSX intrinsics like `div` will give you their DOM instance. For `ElementRef<'div'>` that would be
* `HTMLDivElement`. For `ElementRef<'input'>` that would be `HTMLInputElement`.
* - Rax stateless functional components that forward a `ref` will give you the `ElementRef` of the forwarded
* to component.
*
* `C` must be the type _of_ a Rax component so you need to use typeof as in `ElementRef<typeof MyComponent>`.
*/
type ElementRef<
C extends
| ForwardRefExoticComponent<any>
| { new(props: any): Component<any> }
| ((props: any, context?: any) => RaxElement | null)
| keyof JSX.IntrinsicElements,
> =
// need to check first if `ref` is a valid prop for ts@3.0
// otherwise it will infer `{}` instead of `never`
"ref" extends keyof ComponentPropsWithRef<C> ? NonNullable<ComponentPropsWithRef<C>["ref"]> extends Ref<
infer Instance
> ? Instance
: never
: never;
type ComponentState = any;
interface Attributes {
key?: Key | null | undefined;
}
interface RefAttributes<T> extends Attributes {
ref?: Ref<T> | undefined;
}
interface ClassAttributes<T> extends Attributes {
ref?: LegacyRef<T> | undefined;
}
interface RaxElement<
P = any,
T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>,
> {
type: T;
props: P;
key: Key | null;
}
interface RaxComponentElement<
T extends keyof JSX.IntrinsicElements | JSXElementConstructor<any>,
P = Pick<ComponentProps<T>, Exclude<keyof ComponentProps<T>, "key" | "ref">>,
> extends RaxElement<P, T> {}
interface FunctionComponentElement<P> extends RaxElement<P, FunctionComponent<P>> {
ref?: "ref" extends keyof P ? (P extends { ref?: infer R | undefined } ? R : never) : never | undefined;
}
type CElement<P, T extends Component<P, ComponentState>> = ComponentElement<P, T>;
interface ComponentElement<P, T extends Component<P, ComponentState>> extends RaxElement<P, ComponentClass<P>> {
ref?: LegacyRef<T> | undefined;
}
type ClassicElement<P> = CElement<P, ClassicComponent<P, ComponentState>>;
// string fallback for custom web-components
interface DOMElement<P extends HTMLAttributes<T> | SVGAttributes<T>, T extends Element>
extends RaxElement<P, string>
{
ref: LegacyRef<T>;
}
// RaxHTML for RaxHTMLElement
interface RaxHTMLElement<T extends HTMLElement> extends DetailedRaxHTMLElement<AllHTMLAttributes<T>, T> {}
interface DetailedRaxHTMLElement<P extends HTMLAttributes<T>, T extends HTMLElement> extends DOMElement<P, T> {
type: keyof RaxHTML;
}
// RaxSVG for RaxSVGElement
interface RaxSVGElement extends DOMElement<SVGAttributes<SVGElement>, SVGElement> {
type: keyof RaxSVG;
}
interface RaxPortal extends RaxElement {
key: Key | null;
children: RaxNode;
}
/**
* ======================================================================
* Rax Factories
* ======================================================================
*/
type Factory<P> = (props?: Attributes & P, ...children: RaxNode[]) => RaxElement<P>;
type FunctionComponentFactory<P> = (
props?: Attributes & P,
...children: RaxNode[]
) => FunctionComponentElement<P>;
type ComponentFactory<P, T extends Component<P, ComponentState>> = (
props?: ClassAttributes<T> & P,
...children: RaxNode[]
) => CElement<P, T>;
type CFactory<P, T extends Component<P, ComponentState>> = ComponentFactory<P, T>;
type ClassicFactory<P> = CFactory<P, ClassicComponent<P, ComponentState>>;
type DOMFactory<P extends DOMAttributes<T>, T extends Element> = (
props?: ClassAttributes<T> & P | null,
...children: RaxNode[]
) => DOMElement<P, T>;
interface HTMLFactory<T extends HTMLElement> extends DetailedHTMLFactory<AllHTMLAttributes<T>, T> {}
interface DetailedHTMLFactory<P extends HTMLAttributes<T>, T extends HTMLElement> extends DOMFactory<P, T> {
(props?: ClassAttributes<T> & P | null, ...children: RaxNode[]): DetailedRaxHTMLElement<P, T>;
}
interface SVGFactory extends DOMFactory<SVGAttributes<SVGElement>, SVGElement> {
(
props?: ClassAttributes<SVGElement> & SVGAttributes<SVGElement> | null,
...children: RaxNode[]
): RaxSVGElement;
}
/**
* ======================================================================
* Rax Nodes
* ======================================================================
*/
type RaxText = string | number;
type RaxChild = RaxElement | RaxText;
interface RaxNodeArray extends Array<RaxNode> {}
type RaxFragment = {} | RaxNodeArray;
type RaxNode = RaxChild | RaxFragment | RaxPortal | boolean | null | undefined;
export const RaxFragment: FunctionComponent<{}>;
/**
* ======================================================================
* Rax Top Level API
* ======================================================================
*/
// DOM Elements
// TODO: generalize this to everything in `keyof RaxHTML`, not just "input"
function createElement(
type: "input",
props?: InputHTMLAttributes<HTMLInputElement> & ClassAttributes<HTMLInputElement> | null,
...children: RaxNode[]
): DetailedRaxHTMLElement<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>;
function createElement<P extends HTMLAttributes<T>, T extends HTMLElement>(
type: keyof RaxHTML,
props?: ClassAttributes<T> & P | null,
...children: RaxNode[]
): DetailedRaxHTMLElement<P, T>;
function createElement<P extends SVGAttributes<T>, T extends SVGElement>(
type: keyof RaxSVG,
props?: ClassAttributes<T> & P | null,
...children: RaxNode[]
): RaxSVGElement;
function createElement<P extends DOMAttributes<T>, T extends Element>(
type: string,
props?: ClassAttributes<T> & P | null,
...children: RaxNode[]
): DOMElement<P, T>;
// Custom components
function createElement<P extends {}>(
type: FunctionComponent<P>,
props?: Attributes & P | null,
...children: RaxNode[]
): FunctionComponentElement<P>;
function createElement<P extends {}>(
type: ClassType<P, ClassicComponent<P, ComponentState>, ClassicComponentClass<P>>,
props?: ClassAttributes<ClassicComponent<P, ComponentState>> & P | null,
...children: RaxNode[]
): CElement<P, ClassicComponent<P, ComponentState>>;
function createElement<
P extends {},
T extends Component<P, ComponentState>,
C extends ComponentClass<P>,
>(
type: ClassType<P, T, C>,
props?: ClassAttributes<T> & P | null,
...children: RaxNode[]
): CElement<P, T>;
function createElement<P extends {}>(
type: FunctionComponent<P> | ComponentClass<P> | string,
props?: Attributes & P | null,
...children: RaxNode[]
): RaxElement<P>;
// Context via RenderProps
interface ProviderProps<T> {
value: T;
children?: RaxNode | undefined;
}
interface ConsumerProps<T> {
children: (value: T) => RaxNode;
unstable_observedBits?: number | undefined;
}
interface ExoticComponent<P = {}> {
/**
* **NOTE**: Exotic components are not callable.
*/
(props: P): RaxElement | null;
readonly $$typeof: symbol;
}
interface NamedExoticComponent<P = {}> extends ExoticComponent<P> {
displayName?: string | undefined;
}
interface ProviderExoticComponent<P> extends ExoticComponent<P> {
propTypes?: WeakValidationMap<P> | undefined;
}
type ContextType<C extends Context<any>> = C extends Context<infer T> ? T : never;
type Provider<T> = ProviderExoticComponent<ProviderProps<T>>;
type Consumer<T> = ExoticComponent<ConsumerProps<T>>;
interface Context<T> {
Provider: Provider<T>;
Consumer: Consumer<T>;
displayName?: string | undefined;
}
function createContext<T>(
defaultValue: T,
calculateChangedBits?: (prev: T, next: T) => number,
): Context<T>;
const Children: RaxChildren;
const Fragment: ExoticComponent<{ children?: RaxNode | undefined }>;
const version: string;
interface RenderOption {
driver: any;
hydrate?: boolean;
}
export const render: Renderer;
export interface Renderer {
<T extends Element>(
element: DOMElement<DOMAttributes<T>, T>,
container: Element | DocumentFragment | null,
options?: RenderOption,
callback?: () => void,
): T;
(
element: Array<DOMElement<DOMAttributes<any>, any>>,
container: Element | DocumentFragment | null,
options?: RenderOption,
callback?: () => void,
): Element;
(
element: FunctionComponentElement<any> | Array<FunctionComponentElement<any>>,
container: Element | DocumentFragment | null,
options?: RenderOption,
callback?: () => void,
): void;
<P, T extends Component<P, ComponentState>>(
element: CElement<P, T>,
container: Element | DocumentFragment | null,
options?: RenderOption,
callback?: () => void,
): T;
(
element: Array<CElement<any, Component<any, ComponentState>>>,
container: Element | DocumentFragment | null,
options?: RenderOption,
callback?: () => void,
): Component<any, ComponentState>;
<P>(
element: RaxElement<P>,
container: Element | DocumentFragment | null,
options?: RenderOption,
callback?: () => void,
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
): Component<P, ComponentState> | Element | void;
(
element: RaxElement[],
container: Element | DocumentFragment | null,
options?: RenderOption,
callback?: () => void,
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
): Component<any, ComponentState> | Element | void;
}
/**
* ======================================================================
* Rax Component API
* ======================================================================
*/
type RaxInstance = Component<any> | Element;
// Base component for plain JS classes
interface Component<P = {}, S = {}, SS = any> extends ComponentLifecycle<P, S, SS> {}
class Component<P, S> {
readonly props: Readonly<P> & Readonly<{ children?: RaxNode | undefined }>;
state: Readonly<S>;
constructor(props: Readonly<P>);
setState<K extends keyof S>(
state:
| ((prevState: Readonly<S>, props: Readonly<P>) => Pick<S, K> | S | null)
| (Pick<S, K> | S | null),
callback?: () => void,
): void;
forceUpdate(callBack?: () => void): void;
render(): RaxNode;
refs: {
[key: string]: RaxInstance;
};
context: any;
}
class PureComponent<P = {}, S = {}, SS = any> extends Component<P, S, SS> {}
interface ClassicComponent<P = {}, S = {}> extends Component<P, S> {
replaceState(nextState: S, callback?: () => void): void;
isMounted(): boolean;
getInitialState?(): S;
}
interface ChildContextProvider<CC> {
getChildContext(): CC;
}
type FC<P = {}> = FunctionComponent<P>;
interface FunctionComponent<P = {}> {
(props: PropsWithChildren<P>, context?: any): RaxElement | null;
propTypes?: WeakValidationMap<P> | undefined;
contextTypes?: ValidationMap<any> | undefined;
defaultProps?: Partial<P> | undefined;
displayName?: string | undefined;
}
type ForwardedRef<T> = ((instance: T | null) => void) | MutableRefObject<T | null> | null;
interface ForwardRefRenderFunction<T, P = {}> {
(props: PropsWithChildren<P>, ref: ForwardedRef<T>): RaxElement | null;
displayName?: string | undefined;
// explicit rejected with `never` required due to
// https://github.com/microsoft/TypeScript/issues/36826
/**
* defaultProps are not supported on render functions
*/
defaultProps?: never | undefined;
/**
* propTypes are not supported on render functions
*/
propTypes?: never | undefined;
}
/**
* @deprecated Use ForwardRefRenderFunction. forwardRef doesn't accept a
* "real" component.
*/
interface RefForwardingComponent<T, P = {}> extends ForwardRefRenderFunction<T, P> {}
interface ComponentClass<P = {}, S = ComponentState> extends StaticLifecycle<P, S> {
new(props: P, context?: any): Component<P, S>;
propTypes?: WeakValidationMap<P> | undefined;
contextType?: Context<any> | undefined;
contextTypes?: ValidationMap<any> | undefined;
childContextTypes?: ValidationMap<any> | undefined;
defaultProps?: Partial<P> | undefined;
displayName?: string | undefined;
}
interface ClassicComponentClass<P = {}> extends ComponentClass<P> {
new(props: P, context?: any): ClassicComponent<P, ComponentState>;
getDefaultProps?(): P;
}
/**
* We use an intersection type to infer multiple type parameters from
* a single argument, which is useful for many top-level API defs.
* See https://github.com/Microsoft/TypeScript/issues/7234 for more info.
*/
type ClassType<P, T extends Component<P, ComponentState>, C extends ComponentClass<P>> =
& C
& (new(props: P, context?: any) => T);
/**
* ======================================================================
* Rax Component Specs and Lifecycle
* ======================================================================
*/
// This should actually be something like `Lifecycle<P, S> | DeprecatedLifecycle<P, S>`,
// as Rax will _not_ call the deprecated lifecycle methods if any of the new lifecycle
// methods are present.
interface ComponentLifecycle<P, S, SS = any> {
/**
* Called immediately after a component is mounted. Setting state here will trigger re-rendering.
*/
componentDidMount?(): void;
/**
* Called to determine whether the change in props and state should trigger a re-render.
*
* `Component` always returns true.
* `PureComponent` implements a shallow comparison on props and state and returns true if any
* props or states have changed.
*
* If false is returned, `Component#render`, `componentWillUpdate`
* and `componentDidUpdate` will not be called.
*/
shouldComponentUpdate?(
nextProps: Readonly<P>,
nextState: Readonly<S>,
nextContext: any,
): boolean;
/**
* Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
* cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
*/
componentWillUnmount?(): void;
/**
* Catches exceptions generated in descendant components. Unhandled exceptions will cause
* the entire component tree to unmount.
*/
componentDidCatch?(error: Error, errorInfo: ErrorInfo): void;
/**
* Runs before Rax applies the result of `render` to the document, and
* returns an object to be given to componentDidUpdate. Useful for saving
* things such as scroll position before `render` causes changes to it.
*
* Note: the presence of getSnapshotBeforeUpdate prevents any of the deprecated
* lifecycle events from running.
*/
getSnapshotBeforeUpdate?(prevProps: Readonly<P>, prevState: Readonly<S>): SS | null;
/**
* Called immediately after updating occurs. Not called for the initial render.
*
* The snapshot is only present if getSnapshotBeforeUpdate is present and returns non-null.
*/
componentDidUpdate?(prevProps: Readonly<P>, prevState: Readonly<S>, snapshot?: SS): void;
componentWillMount?(): void;
componentWillReceiveProps?(nextProps: Readonly<P>, nextContext: any): void;
componentWillUpdate?(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): void;
}
// Unfortunately, we have no way of declaring that the component constructor must implement this
interface StaticLifecycle<P, S> {
getDerivedStateFromProps?: GetDerivedStateFromProps<P, S> | undefined;
getDerivedStateFromError?: GetDerivedStateFromError<P, S> | undefined;
}
type GetDerivedStateFromProps<P, S> =
/**
* Returns an update to a component's state based on its new props and old state.
*
* Note: its presence prevents any of the deprecated lifecycle methods from being invoked
*/
(nextProps: Readonly<P>, prevState: S) => Partial<S> | null;
type GetDerivedStateFromError<P, S> =
/**
* This lifecycle is invoked after an error has been thrown by a descendant component.
* It receives the error that was thrown as a parameter and should return a value to update state.
*
* Note: its presence prevents any of the deprecated lifecycle methods from being invoked
*/
(error: any) => Partial<S> | null;
interface Mixin<P, S> extends ComponentLifecycle<P, S> {
mixins?: Array<Mixin<P, S>> | undefined;
statics?: {
[key: string]: any;
} | undefined;
displayName?: string | undefined;
propTypes?: ValidationMap<any> | undefined;
contextTypes?: ValidationMap<any> | undefined;
childContextTypes?: ValidationMap<any> | undefined;
getDefaultProps?(): P;
getInitialState?(): S;
}
interface ComponentSpec<P, S> extends Mixin<P, S> {
render(): RaxNode;
[propertyName: string]: any;
}
function createRef<T>(): RefObject<T>;
// will show `ForwardRef(${Component.displayName || Component.name})` in devtools by default,
// but can be given its own specific name
interface ForwardRefExoticComponent<P> extends NamedExoticComponent<P> {
defaultProps?: Partial<P> | undefined;
}
function forwardRef<T, P = {}>(
render: ForwardRefRenderFunction<T, P>,
): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;
/** Ensures that the props do not include ref at all */
type PropsWithoutRef<P> =
// Just Pick would be sufficient for this, but I'm trying to avoid unnecessary mapping over union types
// https://github.com/Microsoft/TypeScript/issues/28339
"ref" extends keyof P ? Pick<P, Exclude<keyof P, "ref">> : P;
/** Ensures that the props do not include string ref, which cannot be forwarded */
type PropsWithRef<P> =
// Just "P extends { ref?: infer R }" looks sufficient, but R will infer as {} if P is {}.
"ref" extends keyof P
? P extends { ref?: infer R | undefined }
? string extends R ? PropsWithoutRef<P> & { ref?: Exclude<R, string> | undefined }
: P
: P
: P;
type PropsWithChildren<P> = P & { children?: RaxNode | undefined };
/**
* NOTE: prefer ComponentPropsWithRef, if the ref is forwarded,
* or ComponentPropsWithoutRef when refs are not supported.
*/
type ComponentProps<
T extends keyof JSX.IntrinsicElements | JSXElementConstructor<any>,
> = T extends JSXElementConstructor<infer P> ? P
: T extends keyof JSX.IntrinsicElements ? JSX.IntrinsicElements[T]
: {};
type ComponentPropsWithRef<T extends ElementType> = T extends ComponentClass<infer P>
? PropsWithoutRef<P> & RefAttributes<InstanceType<T>>
: PropsWithRef<ComponentProps<T>>;
type ComponentPropsWithoutRef<T extends ElementType> = PropsWithoutRef<ComponentProps<T>>;
type ComponentRef<T extends ElementType> = T extends NamedExoticComponent<
ComponentPropsWithoutRef<T> & RefAttributes<infer Method>
> ? Method
: ComponentPropsWithRef<T> extends RefAttributes<infer Method> ? Method
: never;
// will show `Memo(${Component.displayName || Component.name})` in devtools by default,
// but can be given its own specific name
type MemoExoticComponent<T extends ComponentType<any>> =
& NamedExoticComponent<
ComponentPropsWithRef<T>
>
& {
readonly type: T;
};
function memo<P extends object>(
Component: FC<P>,
propsAreEqual?: (
prevProps: Readonly<PropsWithChildren<P>>,
nextProps: Readonly<PropsWithChildren<P>>,
) => boolean,
): NamedExoticComponent<P>;
function memo<T extends ComponentType<any>>(
Component: T,
propsAreEqual?: (
prevProps: Readonly<ComponentProps<T>>,
nextProps: Readonly<ComponentProps<T>>,
) => boolean,
): MemoExoticComponent<T>;
/**
* ======================================================================
* Rax Hooks
* ======================================================================
*/
// Unlike the class component setState, the updates are not allowed to be partial
type SetStateAction<S> = S | ((prevState: S) => S);
// this technically does accept a second argument, but it's already under a deprecation warning
// and it's not even released so probably better to not define it.
type Dispatch<A> = (value: A) => void;
// Unlike redux, the actions _can_ be anything
type Reducer<S, A> = (prevState: S, action: A) => S;
// types used to try and prevent the compiler from reducing S
// to a supertype common with the second argument to useReducer()
type ReducerState<R extends Reducer<any, any>> = R extends Reducer<infer S, any> ? S : never;
type ReducerAction<R extends Reducer<any, any>> = R extends Reducer<any, infer A> ? A : never;
// The identity check is done with the SameValue algorithm (Object.is), which is stricter than ===
// TODO (TypeScript 3.0): ReadonlyArray<unknown>
type DependencyList = readonly any[];
// NOTE: callbacks are _only_ allowed to return either void, or a destructor.
// The destructor is itself only allowed to return void.
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
type EffectCallback = () => void | (() => void | undefined);
interface MutableRefObject<T> {
current: T;
}
// This will technically work if you give a Consumer<T> or Provider<T> but it's deprecated and warns
/**
* Accepts a context object (the value returned from `Rax.createContext`) and returns the current
* context value, as given by the nearest context provider for the given context.
*/
function useContext<T>(
context: Context<T>, /* , (not public API) observedBits?: number|boolean */
): T;
/**
* Returns a stateful value, and a function to update it.
*/
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
// convenience overload when first argument is ommitted
/**
* Returns a stateful value, and a function to update it.
*/
function useState<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>];
/**
* An alternative to `useState`.
*
* `useReducer` is usually preferable to `useState` when you have complex state logic that involves
* multiple sub-values. It also lets you optimize performance for components that trigger deep
* updates because you can pass `dispatch` down instead of callbacks.
*/
// overload where "I" may be a subset of ReducerState<R>; used to provide autocompletion.
// If "I" matches ReducerState<R> exactly then the last overload will allow initializer to be ommitted.
// the last overload effectively behaves as if the identity function (x => x) is the initializer.
function useReducer<R extends Reducer<any, any>, I>(
reducer: R,
initializerArg: I & ReducerState<R>,
initializer: (arg: I & ReducerState<R>) => ReducerState<R>,
): [ReducerState<R>, Dispatch<ReducerAction<R>>];
/**
* An alternative to `useState`.
*
* `useReducer` is usually preferable to `useState` when you have complex state logic that involves
* multiple sub-values. It also lets you optimize performance for components that trigger deep
* updates because you can pass `dispatch` down instead of callbacks.
*/
// overload for free "I"; all goes as long as initializer converts it into "ReducerState<R>".
function useReducer<R extends Reducer<any, any>, I>(
reducer: R,
initializerArg: I,
initializer: (arg: I) => ReducerState<R>,
): [ReducerState<R>, Dispatch<ReducerAction<R>>];
/**
* An alternative to `useState`.
*
* `useReducer` is usually preferable to `useState` when you have complex state logic that involves
* multiple sub-values. It also lets you optimize performance for components that trigger deep
* updates because you can pass `dispatch` down instead of callbacks.
*/
// I'm not sure if I keep this 2-ary or if I make it (2,3)-ary; it's currently (2,3)-ary.
// The Flow types do have an overload for 3-ary invocation with undefined initializer.
// NOTE: without the ReducerState indirection, TypeScript would reduce S to be the most common
// supertype between the reducer's return type and the initialState (or the initializer's return type),
// which would prevent autocompletion from ever working.
// TODO: double-check if this weird overload logic is necessary. It is possible it's either a bug
// in older versions, or a regression in newer versions of the typescript completion service.
function useReducer<R extends Reducer<any, any>>(
reducer: R,
initialState: ReducerState<R>,
initializer?: undefined,
): [ReducerState<R>, Dispatch<ReducerAction<R>>];
/**
* `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument
* (`initialValue`). The returned object will persist for the full lifetime of the component.
*
* Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable
* value around similar to how you’d use instance fields in classes.
*/
// TODO (TypeScript 3.0): <T extends unknown>
function useRef<T>(initialValue: T): MutableRefObject<T>;
// convenience overload for refs given as a ref prop as they typically start with a null value
/**
* `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument
* (`initialValue`). The returned object will persist for the full lifetime of the component.
*
* Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable
* value around similar to how you’d use instance fields in classes.
*
* Usage note: if you need the result of useRef to be directly mutable, include `| null` in the type
* of the generic argument.
*/
// TODO (TypeScript 3.0): <T extends unknown>
function useRef<T>(initialValue: T | null): RefObject<T>;
// convenience overload for potentially undefined initialValue / call with 0 arguments
// has a default to stop it from defaulting to {} instead
/**
* `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument
* (`initialValue`). The returned object will persist for the full lifetime of the component.
*
* Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable
* value around similar to how you’d use instance fields in classes.
*/
// TODO (TypeScript 3.0): <T extends unknown>
function useRef<T = undefined>(): MutableRefObject<T | undefined>;
/**
* The signature is identical to `useEffect`, but it fires synchronously after all DOM mutations.
* Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside
* `useLayoutEffect` will be flushed synchronously, before the browser has a chance to paint.
*
* Prefer the standard `useEffect` when possible to avoid blocking visual updates.
*
* If you’re migrating code from a class component, `useLayoutEffect` fires in the same phase as
* `componentDidMount` and `componentDidUpdate`.
*/
function useLayoutEffect(effect: EffectCallback, deps?: DependencyList): void;
/**
* Accepts a function that contains imperative, possibly effectful code.
*
* @param effect Imperative function that can return a cleanup function
* @param deps If present, effect will only activate if the values in the list change.
*/
function useEffect(effect: EffectCallback, deps?: DependencyList): void;
// NOTE: this does not accept strings, but this will have to be fixed by removing strings from type Ref<T>
/**
* `useImperativeHandle` customizes the instance value that is exposed to parent components when using
* `ref`. As always, imperative code using refs should be avoided in most cases.
*
* `useImperativeHandle` should be used with `Rax.forwardRef`.
*/
function useImperativeHandle<T, R extends T>(
ref: Ref<T> | undefined,
init: () => R,
deps?: DependencyList,
): void;
// I made 'inputs' required here and in useMemo as there's no point to memoizing without the memoization key
// useCallback(X) is identical to just using X, useMemo(() => Y) is identical to just using Y.
/**
* `useCallback` will return a memoized version of the callback that only changes if one of the `inputs`
* has changed.
*/
// TODO (TypeScript 3.0): <T extends (...args: never[]) => unknown>
function useCallback<T extends (...args: any[]) => any>(callback: T, deps: DependencyList): T;
/**
* `useMemo` will only recompute the memoized value when one of the `deps` has changed.
*
* Usage note: if calling `useMemo` with a referentially stable function, also give it as the input in
* the second argument.
*
* ```ts
* function expensive () { ... }
*
* function Component () {
* const expensiveResult = useMemo(expensive, [expensive])
* return ...
* }
* ```
*/
// allow undefined, but don't make it optional as that is very likely a mistake
function useMemo<T>(factory: () => T, deps: DependencyList | undefined): T;
/**
* ======================================================================
* Rax Event System
* ======================================================================
*/
// TODO: change any to unknown when moving to TS v3
interface BaseSyntheticEvent<E = object, C = any, T = any> {
nativeEvent: E;
currentTarget: C;
target: T;
bubbles: boolean;
cancelable: boolean;
defaultPrevented: boolean;
eventPhase: number;
isTrusted: boolean;
preventDefault(): void;
isDefaultPrevented(): boolean;
stopPropagation(): void;
isPropagationStopped(): boolean;
persist(): void;
timeStamp: number;
type: string;
}
/**
* currentTarget - a reference to the element on which the event listener is registered.
*
* target - a reference to the element from which the event was originally dispatched.
* This might be a child element to the element on which the event listener is registered.
* If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239
*/
interface SyntheticEvent<T = Element, E = Event> extends BaseSyntheticEvent<E, EventTarget & T, EventTarget> {}
interface ClipboardEvent<T = Element> extends SyntheticEvent<T, NativeClipboardEvent> {
clipboardData: DataTransfer;
}
interface CompositionEvent<T = Element> extends SyntheticEvent<T, NativeCompositionEvent> {
data: string;
}
interface DragEvent<T = Element> extends MouseEvent<T, NativeDragEvent> {
dataTransfer: DataTransfer;
}
interface PointerEvent<T = Element> extends MouseEvent<T, NativePointerEvent> {
pointerId: number;
pressure: number;
tiltX: number;
tiltY: number;
width: number;
height: number;
pointerType: "mouse" | "pen" | "touch";
isPrimary: boolean;
}
interface FocusEvent<T = Element> extends SyntheticEvent<T, NativeFocusEvent> {
relatedTarget: EventTarget | null;
target: EventTarget & T;
}
interface FormEvent<T = Element> extends SyntheticEvent<T> {}
interface InvalidEvent<T = Element> extends SyntheticEvent<T> {
target: EventTarget & T;
}
interface ChangeEvent<T = Element> extends SyntheticEvent<T> {
target: EventTarget & T;
}
interface KeyboardEvent<T = Element> extends SyntheticEvent<T, NativeKeyboardEvent> {
altKey: boolean;
/** @deprecated */
charCode: number;
ctrlKey: boolean;
code: string;
/**
* See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method.
*/
getModifierState(key: string): boolean;
/**
* See the [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#named-key-attribute-values). for possible values
*/
key: string;
/** @deprecated */
keyCode: number;
locale: string;
location: number;
metaKey: boolean;
repeat: boolean;
shiftKey: boolean;
/** @deprecated */
which: number;
}
interface MouseEvent<T = Element, E = NativeMouseEvent> extends SyntheticEvent<T, E> {
altKey: boolean;
button: number;
buttons: number;
clientX: number;
clientY: number;
ctrlKey: boolean;
/**
* See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method.
*/
getModifierState(key: string): boolean;
metaKey: boolean;
movementX: number;
movementY: number;
pageX: number;
pageY: number;
relatedTarget: EventTarget;
screenX: number;
screenY: number;
shiftKey: boolean;
}
interface TouchEvent<T = Element> extends SyntheticEvent<T, NativeTouchEvent> {
altKey: boolean;
changedTouches: TouchList;
ctrlKey: boolean;
/**
* See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method.
*/
getModifierState(key: string): boolean;
metaKey: boolean;
shiftKey: boolean;
targetTouches: TouchList;
touches: TouchList;
}
interface UIEvent<T = Element> extends SyntheticEvent<T, NativeUIEvent> {
detail: number;
view: AbstractView;
}
interface WheelEvent<T = Element> extends MouseEvent<T, NativeWheelEvent> {
deltaMode: number;
deltaX: number;
deltaY: number;
deltaZ: number;
}
interface AnimationEvent<T = Element> extends SyntheticEvent<T, NativeAnimationEvent> {
animationName: string;
elapsedTime: number;
pseudoElement: string;
}
interface TransitionEvent<T = Element> extends SyntheticEvent<T, NativeTransitionEvent> {
elapsedTime: number;
propertyName: string;
pseudoElement: string;
}
interface AppearEvent<T = Element> extends SyntheticEvent<T> {
direction: "up" | "down";
}
//
// Event Handler Types
// ----------------------------------------------------------------------
type EventHandler<E extends SyntheticEvent<any>> = {
bivarianceHack(event: E): void;
}["bivarianceHack"];
type RaxEventHandler<T = Element> = EventHandler<SyntheticEvent<T>>;
type ClipboardEventHandler<T = Element> = EventHandler<ClipboardEvent<T>>;
type CompositionEventHandler<T = Element> = EventHandler<CompositionEvent<T>>;
type DragEventHandler<T = Element> = EventHandler<DragEvent<T>>;
type FocusEventHandler<T = Element> = EventHandler<FocusEvent<T>>;
type FormEventHandler<T = Element> = EventHandler<FormEvent<T>>;
type ChangeEventHandler<T = Element> = EventHandler<ChangeEvent<T>>;
type KeyboardEventHandler<T = Element> = EventHandler<KeyboardEvent<T>>;
type MouseEventHandler<T = Element> = EventHandler<MouseEvent<T>>;
type TouchEventHandler<T = Element> = EventHandler<TouchEvent<T>>;
type PointerEventHandler<T = Element> = EventHandler<PointerEvent<T>>;
type UIEventHandler<T = Element> = EventHandler<UIEvent<T>>;
type WheelEventHandler<T = Element> = EventHandler<WheelEvent<T>>;
type AnimationEventHandler<T = Element> = EventHandler<AnimationEvent<T>>;
type TransitionEventHandler<T = Element> = EventHandler<TransitionEvent<T>>;
type AppearEventHandler<T = Element> = EventHandler<AppearEvent<T>>;
//
// Props / DOM Attributes
// ----------------------------------------------------------------------
interface HTMLProps<T> extends AllHTMLAttributes<T>, ClassAttributes<T> {}
type DetailedHTMLProps<E extends HTMLAttributes<T>, T> = ClassAttributes<T> & E;
interface SVGProps<T> extends SVGAttributes<T>, ClassAttributes<T> {}
interface DOMAttributes<T> {
children?: RaxNode | undefined;
dangerouslySetInnerHTML?: {
__html: string;
} | undefined;
// weex
[key: string]: any;
// Clipboard Events
onCopy?: ClipboardEventHandler<T> | undefined;
onCopyCapture?: ClipboardEventHandler<T> | undefined;
onCut?: ClipboardEventHandler<T> | undefined;
onCutCapture?: ClipboardEventHandler<T> | undefined;
onPaste?: ClipboardEventHandler<T> | undefined;
onPasteCapture?: ClipboardEventHandler<T> | undefined;
// Composition Events
onCompositionEnd?: CompositionEventHandler<T> | undefined;
onCompositionEndCapture?: CompositionEventHandler<T> | undefined;
onCompositionStart?: CompositionEventHandler<T> | undefined;
onCompositionStartCapture?: CompositionEventHandler<T> | undefined;
onCompositionUpdate?: CompositionEventHandler<T> | undefined;
onCompositionUpdateCapture?: CompositionEventHandler<T> | undefined;
// Focus Events
onFocus?: FocusEventHandler<T> | undefined;
onFocusCapture?: FocusEventHandler<T> | undefined;
onBlur?: FocusEventHandler<T> | undefined;
onBlurCapture?: FocusEventHandler<T> | undefined;
// Form Events
onChange?: FormEventHandler<T> | undefined;
onChangeCapture?: FormEventHandler<T> | undefined;
onBeforeInput?: FormEventHandler<T> | undefined;
onBeforeInputCapture?: FormEventHandler<T> | undefined;
onInput?: FormEventHandler<T> | undefined;
onInputCapture?: FormEventHandler<T> | undefined;
onReset?: FormEventHandler<T> | undefined;
onResetCapture?: FormEventHandler<T> | undefined;
onSubmit?: FormEventHandler<T> | undefined;
onSubmitCapture?: FormEventHandler<T> | undefined;
onInvalid?: FormEventHandler<T> | undefined;
onInvalidCapture?: FormEventHandler<T> | undefined;
// Image Events
onLoad?: RaxEventHandler<T> | undefined;
onLoadCapture?: RaxEventHandler<T> | undefined;
onError?: RaxEventHandler<T> | undefined; // also a Media Event
onErrorCapture?: RaxEventHandler<T> | undefined; // also a Media Event
// Keyboard Events
onKeyDown?: KeyboardEventHandler<T> | undefined;
onKeyDownCapture?: KeyboardEventHandler<T> | undefined;
onKeyPress?: KeyboardEventHandler<T> | undefined;
onKeyPressCapture?: KeyboardEventHandler<T> | undefined;
onKeyUp?: KeyboardEventHandler<T> | undefined;
onKeyUpCapture?: KeyboardEventHandler<T> | undefined;
// Media Events
onAbort?: RaxEventHandler<T> | undefined;
onAbortCapture?: RaxEventHandler<T> | undefined;
onCanPlay?: RaxEventHandler<T> | undefined;
onCanPlayCapture?: RaxEventHandler<T> | undefined;
onCanPlayThrough?: RaxEventHandler<T> | undefined;
onCanPlayThroughCapture?: RaxEventHandler<T> | undefined;
onDurationChange?: RaxEventHandler<T> | undefined;
onDurationChangeCapture?: RaxEventHandler<T> | undefined;
onEmptied?: RaxEventHandler<T> | undefined;
onEmptiedCapture?: RaxEventHandler<T> | undefined;
onEncrypted?: RaxEventHandler<T> | undefined;
onEncryptedCapture?: RaxEventHandler<T> | undefined;
onEnded?: RaxEventHandler<T> | undefined;
onEndedCapture?: RaxEventHandler<T> | undefined;
onLoadedData?: RaxEventHandler<T> | undefined;
onLoadedDataCapture?: RaxEventHandler<T> | undefined;
onLoadedMetadata?: RaxEventHandler<T> | undefined;
onLoadedMetadataCapture?: RaxEventHandler<T> | undefined;
onLoadStart?: RaxEventHandler<T> | undefined;
onLoadStartCapture?: RaxEventHandler<T> | undefined;
onPause?: RaxEventHandler<T> | undefined;
onPauseCapture?: RaxEventHandler<T> | undefined;
onPlay?: RaxEventHandler<T> | undefined;
onPlayCapture?: RaxEventHandler<T> | undefined;
onPlaying?: RaxEventHandler<T> | undefined;
onPlayingCapture?: RaxEventHandler<T> | undefined;
onProgress?: RaxEventHandler<T> | undefined;
onProgressCapture?: RaxEventHandler<T> | undefined;
onRateChange?: RaxEventHandler<T> | undefined;
onRateChangeCapture?: RaxEventHandler<T> | undefined;
onSeeked?: RaxEventHandler<T> | undefined;
onSeekedCapture?: RaxEventHandler<T> | undefined;
onSeeking?: RaxEventHandler<T> | undefined;
onSeekingCapture?: RaxEventHandler<T> | undefined;
onStalled?: RaxEventHandler<T> | undefined;
onStalledCapture?: RaxEventHandler<T> | undefined;
onSuspend?: RaxEventHandler<T> | undefined;
onSuspendCapture?: RaxEventHandler<T> | undefined;
onTimeUpdate?: RaxEventHandler<T> | undefined;
onTimeUpdateCapture?: RaxEventHandler<T> | undefined;
onVolumeChange?: RaxEventHandler<T> | undefined;
onVolumeChangeCapture?: RaxEventHandler<T> | undefined;
onWaiting?: RaxEventHandler<T> | undefined;
onWaitingCapture?: RaxEventHandler<T> | undefined;
// MouseEvents
onAuxClick?: MouseEventHandler<T> | undefined;
onAuxClickCapture?: MouseEventHandler<T> | undefined;
onClick?: MouseEventHandler<T> | undefined;
onClickCapture?: MouseEventHandler<T> | undefined;
onContextMenu?: MouseEventHandler<T> | undefined;
onContextMenuCapture?: MouseEventHandler<T> | undefined;
onDoubleClick?: MouseEventHandler<T> | undefined;
onDoubleClickCapture?: MouseEventHandler<T> | undefined;
onDrag?: DragEventHandler<T> | undefined;
onDragCapture?: DragEventHandler<T> | undefined;
onDragEnd?: DragEventHandler<T> | undefined;
onDragEndCapture?: DragEventHandler<T> | undefined;
onDragEnter?: DragEventHandler<T> | undefined;
onDragEnterCapture?: DragEventHandler<T> | undefined;
onDragExit?: DragEventHandler<T> | undefined;
onDragExitCapture?: DragEventHandler<T> | undefined;
onDragLeave?: DragEventHandler<T> | undefined;
onDragLeaveCapture?: DragEventHandler<T> | undefined;
onDragOver?: DragEventHandler<T> | undefined;
onDragOverCapture?: DragEventHandler<T> | undefined;
onDragStart?: DragEventHandler<T> | undefined;
onDragStartCapture?: DragEventHandler<T> | undefined;
onDrop?: DragEventHandler<T> | undefined;
onDropCapture?: DragEventHandler<T> | undefined;
onMouseDown?: MouseEventHandler<T> | undefined;
onMouseDownCapture?: MouseEventHandler<T> | undefined;
onMouseEnter?: MouseEventHandler<T> | undefined;
onMouseLeave?: MouseEventHandler<T> | undefined;
onMouseMove?: MouseEventHandler<T> | undefined;
onMouseMoveCapture?: MouseEventHandler<T> | undefined;
onMouseOut?: MouseEventHandler<T> | undefined;
onMouseOutCapture?: MouseEventHandler<T> | undefined;
onMouseOver?: MouseEventHandler<T> | undefined;
onMouseOverCapture?: MouseEventHandler<T> | undefined;
onMouseUp?: MouseEventHandler<T> | undefined;
onMouseUpCapture?: MouseEventHandler<T> | undefined;
// Selection Events
onSelect?: RaxEventHandler<T> | undefined;
onSelectCapture?: RaxEventHandler<T> | undefined;
// Touch Events
onTouchCancel?: TouchEventHandler<T> | undefined;
onTouchCancelCapture?: TouchEventHandler<T> | undefined;
onTouchEnd?: TouchEventHandler<T> | undefined;
onTouchEndCapture?: TouchEventHandler<T> | undefined;
onTouchMove?: TouchEventHandler<T> | undefined;
onTouchMoveCapture?: TouchEventHandler<T> | undefined;
onTouchStart?: TouchEventHandler<T> | undefined;
onTouchStartCapture?: TouchEventHandler<T> | undefined;
// Pointer Events
onPointerDown?: PointerEventHandler<T> | undefined;
onPointerDownCapture?: PointerEventHandler<T> | undefined;
onPointerMove?: PointerEventHandler<T> | undefined;
onPointerMoveCapture?: PointerEventHandler<T> | undefined;
onPointerUp?: PointerEventHandler<T> | undefined;
onPointerUpCapture?: PointerEventHandler<T> | undefined;
onPointerCancel?: PointerEventHandler<T> | undefined;
onPointerCancelCapture?: PointerEventHandler<T> | undefined;
onPointerEnter?: PointerEventHandler<T> | undefined;
onPointerEnterCapture?: PointerEventHandler<T> | undefined;
onPointerLeave?: PointerEventHandler<T> | undefined;
onPointerLeaveCapture?: PointerEventHandler<T> | unde