Commit 6cc198bf authored by Sangjune Bae's avatar Sangjune Bae
Browse files

first commit

parent 81c6da4b
import React from 'react';
export declare type AsyncSetState<TState> = (stateUpdate: React.SetStateAction<TState>) => Promise<TState>;
/**
* A hook that mirrors `useState` in function and API, expect that setState
* calls return a promise that resolves after the state has been set (in an effect).
*
* This is _similar_ to the second callback in classy setState calls, but fires later.
*
* ```ts
* const [counter, setState] = useStateAsync(1);
*
* const handleIncrement = async () => {
* await setState(2);
* doWorkRequiringCurrentState()
* }
* ```
*
* @param initialState initialize with some state value same as `useState`
*/
export default function useStateAsync<TState>(initialState: TState | (() => TState)): [TState, AsyncSetState<TState>];
"use strict";
exports.__esModule = true;
exports.default = useStateAsync;
var _react = require("react");
/**
* A hook that mirrors `useState` in function and API, expect that setState
* calls return a promise that resolves after the state has been set (in an effect).
*
* This is _similar_ to the second callback in classy setState calls, but fires later.
*
* ```ts
* const [counter, setState] = useStateAsync(1);
*
* const handleIncrement = async () => {
* await setState(2);
* doWorkRequiringCurrentState()
* }
* ```
*
* @param initialState initialize with some state value same as `useState`
*/
function useStateAsync(initialState) {
var _useState = (0, _react.useState)(initialState),
state = _useState[0],
setState = _useState[1];
var resolvers = (0, _react.useRef)([]);
(0, _react.useEffect)(function () {
resolvers.current.forEach(function (resolve) {
return resolve(state);
});
resolvers.current.length = 0;
}, [state]);
var setStateAsync = (0, _react.useCallback)(function (update) {
return new Promise(function (resolve, reject) {
setState(function (prevState) {
try {
var nextState; // ugly instanceof for typescript
if (update instanceof Function) {
nextState = update(prevState);
} else {
nextState = update;
} // If state does not change, we must resolve the promise because
// react won't re-render and effect will not resolve. If there are already
// resolvers queued, then it should be safe to assume an update will happen
if (!resolvers.current.length && Object.is(nextState, prevState)) {
resolve(nextState);
} else {
resolvers.current.push(resolve);
}
return nextState;
} catch (e) {
reject(e);
throw e;
}
});
});
}, [setState]);
return [state, setStateAsync];
}
\ No newline at end of file
import { SyntheticEvent } from 'react';
export declare type ThrottledHandler<TEvent> = ((event: TEvent) => void) & {
clear(): void;
};
/**
* Creates a event handler function throttled by `requestAnimationFrame` that
* returns the **most recent** event. Useful for noisy events that update react state.
*
* ```tsx
* function Component() {
* const [position, setPosition] = useState();
* const handleMove = useThrottledEventHandler<React.PointerEvent>(
* (event) => {
* setPosition({
* top: event.clientX,
* left: event.clientY,
* })
* }
* )
*
* return (
* <div onPointerMove={handleMove}>
* <div style={position} />
* </div>
* );
* }
* ```
*
* @param handler An event handler function
* @typeParam TEvent The event object passed to the handler function
* @returns The event handler with a `clear` method attached for clearing any in-flight handler calls
*
*/
export default function useThrottledEventHandler<TEvent = SyntheticEvent>(handler: (event: TEvent) => void): ThrottledHandler<TEvent>;
"use strict";
exports.__esModule = true;
exports.default = useThrottledEventHandler;
var _react = require("react");
var _useMounted = _interopRequireDefault(require("./useMounted"));
var _useEventCallback = _interopRequireDefault(require("./useEventCallback"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
var isSyntheticEvent = function isSyntheticEvent(event) {
return typeof event.persist === 'function';
};
/**
* Creates a event handler function throttled by `requestAnimationFrame` that
* returns the **most recent** event. Useful for noisy events that update react state.
*
* ```tsx
* function Component() {
* const [position, setPosition] = useState();
* const handleMove = useThrottledEventHandler<React.PointerEvent>(
* (event) => {
* setPosition({
* top: event.clientX,
* left: event.clientY,
* })
* }
* )
*
* return (
* <div onPointerMove={handleMove}>
* <div style={position} />
* </div>
* );
* }
* ```
*
* @param handler An event handler function
* @typeParam TEvent The event object passed to the handler function
* @returns The event handler with a `clear` method attached for clearing any in-flight handler calls
*
*/
function useThrottledEventHandler(handler) {
var isMounted = (0, _useMounted.default)();
var eventHandler = (0, _useEventCallback.default)(handler);
var nextEventInfoRef = (0, _react.useRef)({
event: null,
handle: null
});
var clear = function clear() {
cancelAnimationFrame(nextEventInfoRef.current.handle);
nextEventInfoRef.current.handle = null;
};
var handlePointerMoveAnimation = function handlePointerMoveAnimation() {
var next = nextEventInfoRef.current;
if (next.handle && next.event) {
if (isMounted()) {
next.handle = null;
eventHandler(next.event);
}
}
next.event = null;
};
var throttledHandler = function throttledHandler(event) {
if (!isMounted()) return;
if (isSyntheticEvent(event)) {
event.persist();
} // Special handling for a React.Konva event which reuses the
// event object as it bubbles, setting target
else if ('evt' in event) {
event = _extends({}, event);
}
nextEventInfoRef.current.event = event;
if (!nextEventInfoRef.current.handle) {
nextEventInfoRef.current.handle = requestAnimationFrame(handlePointerMoveAnimation);
}
};
throttledHandler.clear = clear;
return throttledHandler;
}
\ No newline at end of file
/**
* Returns a controller object for setting a timeout that is properly cleaned up
* once the component unmounts. New timeouts cancel and replace existing ones.
*/
export default function useTimeout(): {
set: (fn: () => void, delayMs?: number) => void;
clear: () => void;
};
"use strict";
exports.__esModule = true;
exports.default = useTimeout;
var _react = require("react");
var _useMounted = _interopRequireDefault(require("./useMounted"));
var _useWillUnmount = _interopRequireDefault(require("./useWillUnmount"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
* Browsers including Internet Explorer, Chrome, Safari, and Firefox store the
* delay as a 32-bit signed integer internally. This causes an integer overflow
* when using delays larger than 2,147,483,647 ms (about 24.8 days),
* resulting in the timeout being executed immediately.
*
* via: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
*/
var MAX_DELAY_MS = Math.pow(2, 31) - 1;
function setChainedTimeout(handleRef, fn, timeoutAtMs) {
var delayMs = timeoutAtMs - Date.now();
handleRef.current = delayMs <= MAX_DELAY_MS ? setTimeout(fn, delayMs) : setTimeout(function () {
return setChainedTimeout(handleRef, fn, timeoutAtMs);
}, MAX_DELAY_MS);
}
/**
* Returns a controller object for setting a timeout that is properly cleaned up
* once the component unmounts. New timeouts cancel and replace existing ones.
*/
function useTimeout() {
var isMounted = (0, _useMounted.default)(); // types are confused between node and web here IDK
var handleRef = (0, _react.useRef)();
(0, _useWillUnmount.default)(function () {
return clearTimeout(handleRef.current);
});
return (0, _react.useMemo)(function () {
var clear = function clear() {
return clearTimeout(handleRef.current);
};
function set(fn, delayMs) {
if (delayMs === void 0) {
delayMs = 0;
}
if (!isMounted()) return;
clear();
if (delayMs <= MAX_DELAY_MS) {
// For simplicity, if the timeout is short, just set a normal timeout.
handleRef.current = setTimeout(fn, delayMs);
} else {
setChainedTimeout(handleRef, fn, Date.now() + delayMs);
}
}
return {
set: set,
clear: clear
};
}, []);
}
\ No newline at end of file
import { EffectCallback, DependencyList } from 'react';
/**
* Runs an effect only when the dependencies have changed, skipping the
* initial "on mount" run. Caution, if the dependency list never changes,
* the effect is **never run**
*
* ```ts
* const ref = useRef<HTMLInput>(null);
*
* // focuses an element only if the focus changes, and not on mount
* useUpdateEffect(() => {
* const element = ref.current?.children[focusedIdx] as HTMLElement
*
* element?.focus()
*
* }, [focusedIndex])
* ```
* @param effect An effect to run on mount
*
* @category effects
*/
declare function useUpdateEffect(fn: EffectCallback, deps: DependencyList): void;
export default useUpdateEffect;
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _react = require("react");
/**
* Runs an effect only when the dependencies have changed, skipping the
* initial "on mount" run. Caution, if the dependency list never changes,
* the effect is **never run**
*
* ```ts
* const ref = useRef<HTMLInput>(null);
*
* // focuses an element only if the focus changes, and not on mount
* useUpdateEffect(() => {
* const element = ref.current?.children[focusedIdx] as HTMLElement
*
* element?.focus()
*
* }, [focusedIndex])
* ```
* @param effect An effect to run on mount
*
* @category effects
*/
function useUpdateEffect(fn, deps) {
var isFirst = (0, _react.useRef)(true);
(0, _react.useEffect)(function () {
if (isFirst.current) {
isFirst.current = false;
return;
}
return fn();
}, deps);
}
var _default = useUpdateEffect;
exports.default = _default;
\ No newline at end of file
/// <reference types="react" />
/**
* Returns a ref that is immediately updated with the new value
*
* @param value The Ref value
* @category refs
*/
export default function useUpdatedRef<T>(value: T): import("react").MutableRefObject<T>;
"use strict";
exports.__esModule = true;
exports.default = useUpdatedRef;
var _react = require("react");
/**
* Returns a ref that is immediately updated with the new value
*
* @param value The Ref value
* @category refs
*/
function useUpdatedRef(value) {
var valueRef = (0, _react.useRef)(value);
valueRef.current = value;
return valueRef;
}
\ No newline at end of file
/**
* Attach a callback that fires when a component unmounts
*
* @param fn Handler to run when the component unmounts
* @category effects
*/
export default function useWillUnmount(fn: () => void): void;
"use strict";
exports.__esModule = true;
exports.default = useWillUnmount;
var _useUpdatedRef = _interopRequireDefault(require("./useUpdatedRef"));
var _react = require("react");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Attach a callback that fires when a component unmounts
*
* @param fn Handler to run when the component unmounts
* @category effects
*/
function useWillUnmount(fn) {
var onUnmount = (0, _useUpdatedRef.default)(fn);
(0, _react.useEffect)(function () {
return function () {
return onUnmount.current();
};
}, []);
}
\ No newline at end of file
interface Window {
ResizeObserver: ResizeObserver
}
/**
* The ResizeObserver interface is used to observe changes to Element's content
* rect.
*
* It is modeled after MutationObserver and IntersectionObserver.
*/
interface ResizeObserver {
new (callback: ResizeObserverCallback)
/**
* Adds target to the list of observed elements.
*/
observe: (target: Element) => void
/**
* Removes target from the list of observed elements.
*/
unobserve: (target: Element) => void
/**
* Clears both the observationTargets and activeTargets lists.
*/
disconnect: () => void
}
/**
* This callback delivers ResizeObserver's notifications. It is invoked by a
* broadcast active observations algorithm.
*/
interface ResizeObserverCallback {
(entries: ResizeObserverEntry[], observer: ResizeObserver): void
}
interface ResizeObserverEntry {
/**
* @param target The Element whose size has changed.
*/
new (target: Element)
/**
* The Element whose size has changed.
*/
readonly target: Element
/**
* Element's content rect when ResizeObserverCallback is invoked.
*/
readonly contentRect: DOMRectReadOnly
}
interface DOMRectReadOnly {
fromRect(other: DOMRectInit | undefined): DOMRectReadOnly
readonly x: number
readonly y: number
readonly width: number
readonly height: number
readonly top: number
readonly right: number
readonly bottom: number
readonly left: number
toJSON: () => any
}
import useCallbackRef from './useCallbackRef';
import useCommittedRef from './useCommittedRef';
import useEventCallback from './useEventCallback';
import useEventListener from './useEventListener';
import useGlobalListener from './useGlobalListener';
import useInterval from './useInterval';
import useRafInterval from './useRafInterval';
import useMergeState from './useMergeState';
import useMergeStateFromProps from './useMergeStateFromProps';
import useMounted from './useMounted';
import usePrevious from './usePrevious';
import useImage from './useImage';
import useResizeObserver from './useResizeObserver';
export { useCallbackRef, useCommittedRef, useEventCallback, useEventListener, useGlobalListener, useInterval, useRafInterval, useMergeState, useMergeStateFromProps, useMounted, usePrevious, useImage, useResizeObserver, };
import useCallbackRef from './useCallbackRef';
import useCommittedRef from './useCommittedRef';
import useEventCallback from './useEventCallback';
import useEventListener from './useEventListener';
import useGlobalListener from './useGlobalListener';
import useInterval from './useInterval';
import useRafInterval from './useRafInterval';
import useMergeState from './useMergeState';
import useMergeStateFromProps from './useMergeStateFromProps';
import useMounted from './useMounted';
import usePrevious from './usePrevious';
import useImage from './useImage';
import useResizeObserver from './useResizeObserver';
export { useCallbackRef, useCommittedRef, useEventCallback, useEventListener, useGlobalListener, useInterval, useRafInterval, useMergeState, useMergeStateFromProps, useMounted, usePrevious, useImage, useResizeObserver };
\ No newline at end of file
export interface UseAnimationFrameReturn {
cancel(): void;
/**
* Request for the provided callback to be called on the next animation frame.
* Previously registered callbacks will be cancelled
*/
request(callback: FrameRequestCallback): void;
/**
* Request for the provided callback to be called on the next animation frame.
* Previously registered callbacks can be cancelled by providing `cancelPrevious`
*/
request(cancelPrevious: boolean, callback: FrameRequestCallback): void;
}
/**
* Returns a controller object for requesting and cancelling an animation freame that is properly cleaned up
* once the component unmounts. New requests cancel and replace existing ones.
*
* ```ts
* const [style, setStyle] = useState({});
* const animationFrame = useAnimationFrame();
*
* const handleMouseMove = (e) => {
* animationFrame.request(() => {
* setStyle({ top: e.clientY, left: e.clientY })
* })
* }
*
* const handleMouseUp = () => {
* animationFrame.cancel()
* }
*
* return (
* <div onMouseUp={handleMouseUp} onMouseMove={handleMouseMove}>
* <Ball style={style} />
* </div>
* )
* ```
*/
export default function useAnimationFrame(): UseAnimationFrameReturn;
import { useRef } from 'react';
import useMounted from './useMounted';
import useStableMemo from './useStableMemo';
import useWillUnmount from './useWillUnmount';
/**
* Returns a controller object for requesting and cancelling an animation freame that is properly cleaned up
* once the component unmounts. New requests cancel and replace existing ones.
*
* ```ts
* const [style, setStyle] = useState({});
* const animationFrame = useAnimationFrame();
*
* const handleMouseMove = (e) => {
* animationFrame.request(() => {
* setStyle({ top: e.clientY, left: e.clientY })
* })
* }
*
* const handleMouseUp = () => {
* animationFrame.cancel()
* }
*
* return (
* <div onMouseUp={handleMouseUp} onMouseMove={handleMouseMove}>
* <Ball style={style} />
* </div>
* )
* ```
*/
export default function useAnimationFrame() {
var isMounted = useMounted();
var handle = useRef();
var cancel = function cancel() {
if (handle.current != null) {
cancelAnimationFrame(handle.current);
}
};
useWillUnmount(cancel);
return useStableMemo(function () {
return {
request: function request(cancelPrevious, fn) {
if (!isMounted()) return;
if (cancelPrevious) cancel();
handle.current = requestAnimationFrame(fn || cancelPrevious);
},
cancel: cancel
};
}, []);
}
\ No newline at end of file
export declare type BreakpointDirection = 'up' | 'down' | true;
export declare type BreakpointMap<TKey extends string> = Partial<Record<TKey, BreakpointDirection>>;
/**
* Create a responsive hook we a set of breakpoint names and widths.
* You can use any valid css units as well as a numbers (for pixels).
*
* **NOTE:** The object key order is important! it's assumed to be in order from smallest to largest
*
* ```ts
* const useBreakpoint = createBreakpointHook({
* xs: 0,
* sm: 576,
* md: 768,
* lg: 992,
* xl: 1200,
* })
* ```
*
* **Watch out!** using string values will sometimes construct media queries using css `calc()` which
* is NOT supported in media queries by all browsers at the moment. use numbers for
* the widest range of browser support.
*
* @param breakpointValues A object hash of names to breakpoint dimensions
*/
export declare function createBreakpointHook<TKey extends string>(breakpointValues: Record<TKey, string | number>): {
(breakpointMap: Partial<Record<TKey, BreakpointDirection>>): boolean;
(breakpoint: TKey, direction?: true | "up" | "down" | undefined): boolean;
};
export declare type DefaultBreakpoints = 'xs' | 'sm' | 'md' | 'lg' | 'xl';
export declare type DefaultBreakpointMap = BreakpointMap<DefaultBreakpoints>;
declare const useBreakpoint: {
(breakpointMap: Partial<Record<DefaultBreakpoints, BreakpointDirection>>): boolean;
(breakpoint: DefaultBreakpoints, direction?: true | "up" | "down" | undefined): boolean;
};
export default useBreakpoint;
import useMediaQuery from './useMediaQuery';
import { useMemo } from 'react';
/**
* Create a responsive hook we a set of breakpoint names and widths.
* You can use any valid css units as well as a numbers (for pixels).
*
* **NOTE:** The object key order is important! it's assumed to be in order from smallest to largest
*
* ```ts
* const useBreakpoint = createBreakpointHook({
* xs: 0,
* sm: 576,
* md: 768,
* lg: 992,
* xl: 1200,
* })
* ```
*
* **Watch out!** using string values will sometimes construct media queries using css `calc()` which
* is NOT supported in media queries by all browsers at the moment. use numbers for
* the widest range of browser support.
*
* @param breakpointValues A object hash of names to breakpoint dimensions
*/
export function createBreakpointHook(breakpointValues) {
var names = Object.keys(breakpointValues);
function and(query, next) {
if (query === next) {
return next;
}
return query ? query + " and " + next : next;
}
function getNext(breakpoint) {
return names[Math.min(names.indexOf(breakpoint) + 1, names.length - 1)];
}
function getMaxQuery(breakpoint) {
var next = getNext(breakpoint);
var value = breakpointValues[next];
if (typeof value === 'number') value = value - 0.2 + "px";else value = "calc(" + value + " - 0.2px)";
return "(max-width: " + value + ")";
}
function getMinQuery(breakpoint) {
var value = breakpointValues[breakpoint];
if (typeof value === 'number') {
value = value + "px";
}
return "(min-width: " + value + ")";
}
/**
* Match a set of breakpoints
*
* ```tsx
* const MidSizeOnly = () => {
* const isMid = useBreakpoint({ lg: 'down', sm: 'up' });
*
* if (isMid) return <div>On a Reasonable sized Screen!</div>
* return null;
* }
* ```
* @param breakpointMap An object map of breakpoints and directions, queries are constructed using "and" to join
* breakpoints together
*/
function useBreakpoint(breakpointOrMap, direction) {
if (direction === void 0) {
direction = true;
}
var breakpointMap;
if (typeof breakpointOrMap === 'object') {
breakpointMap = breakpointOrMap;
} else {
var _breakpointMap;
breakpointMap = (_breakpointMap = {}, _breakpointMap[breakpointOrMap] = direction, _breakpointMap);
}
var query = useMemo(function () {
return Object.entries(breakpointMap).reduce(function (query, _ref) {
var key = _ref[0],
direction = _ref[1];
if (direction === 'up' || direction === true) {
query = and(query, getMinQuery(key));
}
if (direction === 'down' || direction === true) {
query = and(query, getMaxQuery(key));
}
return query;
}, '');
}, [JSON.stringify(breakpointMap)]);
return useMediaQuery(query);
}
return useBreakpoint;
}
var useBreakpoint = createBreakpointHook({
xs: 0,
sm: 576,
md: 768,
lg: 992,
xl: 1200
});
export default useBreakpoint;
\ No newline at end of file
/**
* A convenience hook around `useState` designed to be paired with
* the component [callback ref](https://reactjs.org/docs/refs-and-the-dom.html#callback-refs) api.
* Callback refs are useful over `useRef()` when you need to respond to the ref being set
* instead of lazily accessing it in an effect.
*
* ```ts
* const [element, attachRef] = useCallbackRef<HTMLDivElement>()
*
* useEffect(() => {
* if (!element) return
*
* const calendar = new FullCalendar.Calendar(element)
*
* return () => {
* calendar.destroy()
* }
* }, [element])
*
* return <div ref={attachRef} />
* ```
*
* @category refs
*/
export default function useCallbackRef<TValue = unknown>(): [TValue | null, (ref: TValue | null) => void];
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment