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

first commit

parent 81c6da4b
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;
"use strict";
exports.__esModule = true;
exports.default = useAnimationFrame;
var _react = require("react");
var _useMounted = _interopRequireDefault(require("./useMounted"));
var _useStableMemo = _interopRequireDefault(require("./useStableMemo"));
var _useWillUnmount = _interopRequireDefault(require("./useWillUnmount"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* 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>
* )
* ```
*/
function useAnimationFrame() {
var isMounted = (0, _useMounted.default)();
var handle = (0, _react.useRef)();
var cancel = function cancel() {
if (handle.current != null) {
cancelAnimationFrame(handle.current);
}
};
(0, _useWillUnmount.default)(cancel);
return (0, _useStableMemo.default)(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;
"use strict";
exports.__esModule = true;
exports.createBreakpointHook = createBreakpointHook;
exports.default = void 0;
var _useMediaQuery = _interopRequireDefault(require("./useMediaQuery"));
var _react = require("react");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* 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
*/
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 = (0, _react.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 (0, _useMediaQuery.default)(query);
}
return useBreakpoint;
}
var useBreakpoint = createBreakpointHook({
xs: 0,
sm: 576,
md: 768,
lg: 992,
xl: 1200
});
var _default = useBreakpoint;
exports.default = _default;
\ 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];
"use strict";
exports.__esModule = true;
exports.default = useCallbackRef;
var _react = require("react");
/**
* 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
*/
function useCallbackRef() {
return (0, _react.useState)(null);
}
\ No newline at end of file
/// <reference types="react" />
/**
* Creates a `Ref` whose value is updated in an effect, ensuring the most recent
* value is the one rendered with. Generally only required for Concurrent mode usage
* where previous work in `render()` may be discarded befor being used.
*
* This is safe to access in an event handler.
*
* @param value The `Ref` value
*/
declare function useCommittedRef<TValue>(value: TValue): React.MutableRefObject<TValue>;
export default useCommittedRef;
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _react = require("react");
/**
* Creates a `Ref` whose value is updated in an effect, ensuring the most recent
* value is the one rendered with. Generally only required for Concurrent mode usage
* where previous work in `render()` may be discarded befor being used.
*
* This is safe to access in an event handler.
*
* @param value The `Ref` value
*/
function useCommittedRef(value) {
var ref = (0, _react.useRef)(value);
(0, _react.useEffect)(function () {
ref.current = value;
}, [value]);
return ref;
}
var _default = useCommittedRef;
exports.default = _default;
\ No newline at end of file
import { DependencyList, EffectCallback } from 'react';
export declare type EffectHook = (effect: EffectCallback, deps?: DependencyList) => void;
export declare type IsEqual<TDeps extends DependencyList> = (nextDeps: TDeps, prevDeps: TDeps) => boolean;
export declare type CustomEffectOptions<TDeps extends DependencyList> = {
isEqual: IsEqual<TDeps>;
effectHook?: EffectHook;
};
/**
* a useEffect() hook with customized depedency comparision
*
* @param effect The effect callback
* @param dependencies A list of dependencies
* @param isEqual A function comparing the next and previous dependencyLists
*/
declare function useCustomEffect<TDeps extends DependencyList = DependencyList>(effect: EffectCallback, dependencies: TDeps, isEqual: IsEqual<TDeps>): void;
/**
* a useEffect() hook with customized depedency comparision
*
* @param effect The effect callback
* @param dependencies A list of dependencies
* @param options
* @param options.isEqual A function comparing the next and previous dependencyLists
* @param options.effectHook the underlying effect hook used, defaults to useEffect
*/
declare function useCustomEffect<TDeps extends DependencyList = DependencyList>(effect: EffectCallback, dependencies: TDeps, options: CustomEffectOptions<TDeps>): void;
export default useCustomEffect;
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _react = require("react");
var _useMounted = _interopRequireDefault(require("./useMounted"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function useCustomEffect(effect, dependencies, isEqualOrOptions) {
var isMounted = (0, _useMounted.default)();
var _ref = typeof isEqualOrOptions === 'function' ? {
isEqual: isEqualOrOptions
} : isEqualOrOptions,
isEqual = _ref.isEqual,
_ref$effectHook = _ref.effectHook,
effectHook = _ref$effectHook === void 0 ? _react.useEffect : _ref$effectHook;
var dependenciesRef = (0, _react.useRef)();
dependenciesRef.current = dependencies;
var cleanupRef = (0, _react.useRef)(null);
effectHook(function () {
// If the ref the is `null` it's either the first effect or the last effect
// ran and was cleared, meaning _this_ update should run, b/c the equality
// check failed on in the cleanup of the last effect.
if (cleanupRef.current === null) {
var cleanup = effect();
cleanupRef.current = function () {
if (isMounted() && isEqual(dependenciesRef.current, dependencies)) {
return;
}
cleanupRef.current = null;
if (cleanup) cleanup();
};
}
return cleanupRef.current;
});
(0, _react.useDebugValue)(effect);
}
var _default = useCustomEffect;
exports.default = _default;
\ No newline at end of file
export default function useEventCallback<TCallback extends (...args: any[]) => any>(fn?: TCallback | null): TCallback;
"use strict";
exports.__esModule = true;
exports.default = useEventCallback;
var _react = require("react");
var _useCommittedRef = _interopRequireDefault(require("./useCommittedRef"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function useEventCallback(fn) {
var ref = (0, _useCommittedRef.default)(fn);
return (0, _react.useCallback)(function () {
return ref.current && ref.current.apply(ref, arguments);
}, [ref]);
}
\ No newline at end of file
declare type EventHandler<T, K extends keyof DocumentEventMap> = (this: T, ev: DocumentEventMap[K]) => any;
/**
* Attaches an event handler outside directly to specified DOM element
* bypassing the react synthetic event system.
*
* @param element The target to listen for events on
* @param event The DOM event name
* @param handler An event handler
* @param capture Whether or not to listen during the capture event phase
*/
export default function useEventListener<T extends Element | Document | Window, K extends keyof DocumentEventMap>(eventTarget: T | (() => T), event: K, listener: EventHandler<T, K>, capture?: boolean | AddEventListenerOptions): void;
export {};
"use strict";
exports.__esModule = true;
exports.default = useEventListener;
var _react = require("react");
var _useEventCallback = _interopRequireDefault(require("./useEventCallback"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Attaches an event handler outside directly to specified DOM element
* bypassing the react synthetic event system.
*
* @param element The target to listen for events on
* @param event The DOM event name
* @param handler An event handler
* @param capture Whether or not to listen during the capture event phase
*/
function useEventListener(eventTarget, event, listener, capture) {
if (capture === void 0) {
capture = false;
}
var handler = (0, _useEventCallback.default)(listener);
(0, _react.useEffect)(function () {
var target = typeof eventTarget === 'function' ? eventTarget() : eventTarget;
target.addEventListener(event, handler, capture);
return function () {
return target.removeEventListener(event, handler, capture);
};
}, [eventTarget]);
}
\ No newline at end of file
/// <reference types="react" />
export interface FocusManagerOptions {
/**
* A callback fired when focus shifts. returning `false` will prevent
* handling the focus event
*/
willHandle?(focused: boolean, event: React.FocusEvent): boolean | void;
/**
* A callback fired after focus is handled but before onChange is called
*/
didHandle?(focused: boolean, event: React.FocusEvent): void;
/**
* A callback fired after focus has changed
*/
onChange?(focused: boolean, event: React.FocusEvent): void;
/**
* When true, the event handlers will not report focus changes
*/
isDisabled: () => boolean;
}
export interface FocusController {
onBlur: (event: any) => void;
onFocus: (event: any) => void;
}
/**
* useFocusManager provides a way to track and manage focus as it moves around
* a container element. An `onChange` is fired when focus enters or leaves the
* element, but not when it moves around inside the element, similar to
* `pointerenter` and `pointerleave` DOM events.
*
* ```tsx
* const [focused, setFocusState] = useState(false)
*
* const { onBlur, onFocus } = useFocusManager({
* onChange: nextFocused => setFocusState(nextFocused)
* })
*
* return (
* <div tabIndex="-1" onFocus={onFocus} onBlur={onBlur}>
* {String(focused)}
* <input />
* <input />
*
* <button>A button</button>
* </div>
* ```
*
*/
export default function useFocusManager(opts: FocusManagerOptions): FocusController;
"use strict";
exports.__esModule = true;
exports.default = useFocusManager;
var _react = require("react");
var _useEventCallback = _interopRequireDefault(require("./useEventCallback"));
var _useMounted = _interopRequireDefault(require("./useMounted"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* useFocusManager provides a way to track and manage focus as it moves around
* a container element. An `onChange` is fired when focus enters or leaves the
* element, but not when it moves around inside the element, similar to
* `pointerenter` and `pointerleave` DOM events.
*
* ```tsx
* const [focused, setFocusState] = useState(false)
*
* const { onBlur, onFocus } = useFocusManager({
* onChange: nextFocused => setFocusState(nextFocused)
* })
*
* return (
* <div tabIndex="-1" onFocus={onFocus} onBlur={onBlur}>
* {String(focused)}
* <input />
* <input />
*
* <button>A button</button>
* </div>
* ```
*
*/
function useFocusManager(opts) {
var isMounted = (0, _useMounted.default)();
var lastFocused = (0, _react.useRef)();
var handle = (0, _react.useRef)();
var willHandle = (0, _useEventCallback.default)(opts.willHandle);
var didHandle = (0, _useEventCallback.default)(opts.didHandle);
var onChange = (0, _useEventCallback.default)(opts.onChange);
var isDisabled = (0, _useEventCallback.default)(opts.isDisabled);
var handleFocusChange = (0, _react.useCallback)(function (focused, event) {
if (event && event.persist) event.persist();
if (willHandle && willHandle(focused, event) === false) return;
clearTimeout(handle.current);
handle.current = setTimeout(function () {
if (focused !== lastFocused.current) {
if (didHandle) didHandle(focused, event); // only fire a change when unmounted if its a blur
if (isMounted() || !focused) {
lastFocused.current = focused;
onChange && onChange(focused, event);
}
}
});
}, [isMounted, willHandle, didHandle, onChange, lastFocused]);
var handleBlur = (0, _react.useCallback)(function (event) {
if (!isDisabled()) handleFocusChange(false, event);
}, [handleFocusChange, isDisabled]);
var handleFocus = (0, _react.useCallback)(function (event) {
if (!isDisabled()) handleFocusChange(true, event);
}, [handleFocusChange, isDisabled]);
return {
onBlur: handleBlur,
onFocus: handleFocus
};
}
\ No newline at end of file
/**
* Returns a function that triggers a component update. the hook equivalent to
* `this.forceUpdate()` in a class component. In most cases using a state value directly
* is preferable but may be required in some advanced usages of refs for interop or
* when direct DOM manipulation is required.
*
* ```ts
* const forceUpdate = useForceUpdate();
*
* const updateOnClick = useCallback(() => {
* forceUpdate()
* }, [forceUpdate])
*
* return <button type="button" onClick={updateOnClick}>Hi there</button>
* ```
*/
export default function useForceUpdate(): () => void;
"use strict";
exports.__esModule = true;
exports.default = useForceUpdate;
var _react = require("react");
/**
* Returns a function that triggers a component update. the hook equivalent to
* `this.forceUpdate()` in a class component. In most cases using a state value directly
* is preferable but may be required in some advanced usages of refs for interop or
* when direct DOM manipulation is required.
*
* ```ts
* const forceUpdate = useForceUpdate();
*
* const updateOnClick = useCallback(() => {
* forceUpdate()
* }, [forceUpdate])
*
* return <button type="button" onClick={updateOnClick}>Hi there</button>
* ```
*/
function useForceUpdate() {
// The toggling state value is designed to defeat React optimizations for skipping
// updates when they are stricting equal to the last state value
var _useReducer = (0, _react.useReducer)(function (state) {
return !state;
}, false),
dispatch = _useReducer[1];
return dispatch;
}
\ No newline at end of file
declare type DocumentEventHandler<K extends keyof DocumentEventMap> = (this: Document, ev: DocumentEventMap[K]) => any;
/**
* Attaches an event handler outside directly to the `document`,
* bypassing the react synthetic event system.
*
* ```ts
* useGlobalListener('keydown', (event) => {
* console.log(event.key)
* })
* ```
*
* @param event The DOM event name
* @param handler An event handler
* @param capture Whether or not to listen during the capture event phase
*/
export default function useGlobalListener<K extends keyof DocumentEventMap>(event: K, handler: DocumentEventHandler<K>, capture?: boolean | AddEventListenerOptions): void;
export {};
"use strict";
exports.__esModule = true;
exports.default = useGlobalListener;
var _useEventListener = _interopRequireDefault(require("./useEventListener"));
var _react = require("react");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Attaches an event handler outside directly to the `document`,
* bypassing the react synthetic event system.
*
* ```ts
* useGlobalListener('keydown', (event) => {
* console.log(event.key)
* })
* ```
*
* @param event The DOM event name
* @param handler An event handler
* @param capture Whether or not to listen during the capture event phase
*/
function useGlobalListener(event, handler, capture) {
if (capture === void 0) {
capture = false;
}
var documentTarget = (0, _react.useCallback)(function () {
return document;
}, []);
return (0, _useEventListener.default)(documentTarget, event, handler, capture);
}
\ No newline at end of file
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