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

first commit

parent 81c6da4b
declare type State = {
image: HTMLImageElement | null;
error: unknown | null;
};
/**
* Fetch and load an image for programatic use such as in a `<canvas>` element.
*
* @param imageOrUrl The `HtmlImageElement` or image url to load
* @param crossOrigin The `crossorigin` attribute to set
*
* ```ts
* const { image, error } = useImage('/static/kittens.png')
* const ref = useRef<HTMLCanvasElement>()
*
* useEffect(() => {
* const ctx = ref.current.getContext('2d')
*
* if (image) {
* ctx.drawImage(image, 0, 0)
* }
* }, [ref, image])
*
* return (
* <>
* {error && "there was a problem loading the image"}
* <canvas ref={ref} />
* </>
* ```
*/
export default function useImage(imageOrUrl?: string | HTMLImageElement | null | undefined, crossOrigin?: 'anonymous' | 'use-credentials' | string): State;
export {};
"use strict";
exports.__esModule = true;
exports.default = useImage;
var _react = require("react");
/**
* Fetch and load an image for programatic use such as in a `<canvas>` element.
*
* @param imageOrUrl The `HtmlImageElement` or image url to load
* @param crossOrigin The `crossorigin` attribute to set
*
* ```ts
* const { image, error } = useImage('/static/kittens.png')
* const ref = useRef<HTMLCanvasElement>()
*
* useEffect(() => {
* const ctx = ref.current.getContext('2d')
*
* if (image) {
* ctx.drawImage(image, 0, 0)
* }
* }, [ref, image])
*
* return (
* <>
* {error && "there was a problem loading the image"}
* <canvas ref={ref} />
* </>
* ```
*/
function useImage(imageOrUrl, crossOrigin) {
var _useState = (0, _react.useState)({
image: null,
error: null
}),
state = _useState[0],
setState = _useState[1];
(0, _react.useEffect)(function () {
if (!imageOrUrl) return undefined;
var image;
if (typeof imageOrUrl === 'string') {
image = new Image();
if (crossOrigin) image.crossOrigin = crossOrigin;
image.src = imageOrUrl;
} else {
image = imageOrUrl;
if (image.complete && image.naturalHeight > 0) {
setState({
image: image,
error: null
});
return;
}
}
function onLoad() {
setState({
image: image,
error: null
});
}
function onError(error) {
setState({
image: image,
error: error
});
}
image.addEventListener('load', onLoad);
image.addEventListener('error', onError);
return function () {
image.removeEventListener('load', onLoad);
image.removeEventListener('error', onError);
};
}, [imageOrUrl, crossOrigin]);
return state;
}
\ No newline at end of file
import { DependencyList, EffectCallback } from 'react';
/**
* An _immediate_ effect that runs an effect callback when its dependency array
* changes. This is helpful for updates should must run during render, most
* commonly state derived from props; a more ergonomic version of https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops
*
* ```ts
* function Example({ value }) {
* const [intermediaryValue, setValue] = useState(value);
*
* useImmediateUpdateEffect(() => {
* setValue(value)
* }, [value])
* ```
*
* @category effects
*/
declare function useImmediateUpdateEffect(effect: EffectCallback, deps: DependencyList): void;
export default useImmediateUpdateEffect;
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _react = require("react");
var _useStableMemo = _interopRequireDefault(require("./useStableMemo"));
var _useWillUnmount = _interopRequireDefault(require("./useWillUnmount"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* An _immediate_ effect that runs an effect callback when its dependency array
* changes. This is helpful for updates should must run during render, most
* commonly state derived from props; a more ergonomic version of https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops
*
* ```ts
* function Example({ value }) {
* const [intermediaryValue, setValue] = useState(value);
*
* useImmediateUpdateEffect(() => {
* setValue(value)
* }, [value])
* ```
*
* @category effects
*/
function useImmediateUpdateEffect(effect, deps) {
var firstRef = (0, _react.useRef)(true);
var tearDown = (0, _react.useRef)();
(0, _useWillUnmount.default)(function () {
if (tearDown.current) tearDown.current();
});
(0, _useStableMemo.default)(function () {
if (firstRef.current) {
firstRef.current = false;
return;
}
if (tearDown.current) tearDown.current();
tearDown.current = effect();
}, deps);
}
var _default = useImmediateUpdateEffect;
exports.default = _default;
\ No newline at end of file
/**
* Setup an [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) on
* a DOM Element.
*
* @param element The DOM element to observe
* @param init IntersectionObserver options
*/
export default function useIntersectionObserver<TElement extends Element>(element: TElement | null | undefined, { threshold, root, rootMargin }?: IntersectionObserverInit): IntersectionObserverEntry[];
"use strict";
exports.__esModule = true;
exports.default = useIntersectionObserver;
var _react = require("react");
var _useStableMemo = _interopRequireDefault(require("./useStableMemo"));
var _useIsomorphicEffect = _interopRequireDefault(require("./useIsomorphicEffect"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Setup an [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) on
* a DOM Element.
*
* @param element The DOM element to observe
* @param init IntersectionObserver options
*/
function useIntersectionObserver(element, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
threshold = _ref.threshold,
root = _ref.root,
rootMargin = _ref.rootMargin;
var _useState = (0, _react.useState)(null),
entries = _useState[0],
setEntry = _useState[1];
var observer = (0, _useStableMemo.default)(function () {
return typeof IntersectionObserver !== 'undefined' && new IntersectionObserver(function (entries) {
return setEntry(entries);
}, {
threshold: threshold,
root: root,
rootMargin: rootMargin
});
}, [root, rootMargin, threshold && JSON.stringify(threshold)]);
(0, _useIsomorphicEffect.default)(function () {
if (!element || !observer) return;
observer.observe(element);
return function () {
observer.unobserve(element);
};
}, [observer, element]);
return entries || [];
}
\ No newline at end of file
/**
* Creates a `setInterval` that is properly cleaned up when a component unmounted
*
* ```tsx
* function Timer() {
* const [timer, setTimer] = useState(0)
* useInterval(() => setTimer(i => i + 1), 1000)
*
* return <span>{timer} seconds past</span>
* }
* ```
*
* @param fn an function run on each interval
* @param ms The milliseconds duration of the interval
*/
declare function useInterval(fn: () => void, ms: number): void;
/**
* Creates a pausable `setInterval` that is properly cleaned up when a component unmounted
*
* ```tsx
* const [paused, setPaused] = useState(false)
* const [timer, setTimer] = useState(0)
*
* useInterval(() => setTimer(i => i + 1), 1000, paused)
*
* return (
* <span>
* {timer} seconds past
*
* <button onClick={() => setPaused(p => !p)}>{paused ? 'Play' : 'Pause' }</button>
* </span>
* )
* ```
*
* @param fn an function run on each interval
* @param ms The milliseconds duration of the interval
* @param paused Whether or not the interval is currently running
*/
declare function useInterval(fn: () => void, ms: number, paused: boolean): void;
/**
* Creates a pausable `setInterval` that _fires_ immediately and is
* properly cleaned up when a component unmounted
*
* ```tsx
* const [timer, setTimer] = useState(-1)
* useInterval(() => setTimer(i => i + 1), 1000, false, true)
*
* // will update to 0 on the first effect
* return <span>{timer} seconds past</span>
* ```
*
* @param fn an function run on each interval
* @param ms The milliseconds duration of the interval
* @param paused Whether or not the interval is currently running
* @param runImmediately Whether to run the function immediately on mount or unpause
* rather than waiting for the first interval to elapse
*
*/
declare function useInterval(fn: () => void, ms: number, paused: boolean, runImmediately: boolean): void;
export default useInterval;
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _react = require("react");
var _useCommittedRef = _interopRequireDefault(require("./useCommittedRef"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function useInterval(fn, ms, paused, runImmediately) {
if (paused === void 0) {
paused = false;
}
if (runImmediately === void 0) {
runImmediately = false;
}
var handle;
var fnRef = (0, _useCommittedRef.default)(fn); // this ref is necessary b/c useEffect will sometimes miss a paused toggle
// orphaning a setTimeout chain in the aether, so relying on it's refresh logic is not reliable.
var pausedRef = (0, _useCommittedRef.default)(paused);
var tick = function tick() {
if (pausedRef.current) return;
fnRef.current();
schedule(); // eslint-disable-line no-use-before-define
};
var schedule = function schedule() {
clearTimeout(handle);
handle = setTimeout(tick, ms);
};
(0, _react.useEffect)(function () {
if (runImmediately) {
tick();
} else {
schedule();
}
return function () {
return clearTimeout(handle);
};
}, [paused, runImmediately]);
}
var _default = useInterval;
exports.default = _default;
\ No newline at end of file
import { useEffect } from 'react';
declare const _default: typeof useEffect;
/**
* Is `useLayoutEffect` in a DOM or React Native environment, otherwise resolves to useEffect
* Only useful to avoid the console warning.
*
* PREFER `useEffect` UNLESS YOU KNOW WHAT YOU ARE DOING.
*
* @category effects
*/
export default _default;
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _react = require("react");
var isReactNative = typeof global !== 'undefined' && // @ts-ignore
global.navigator && // @ts-ignore
global.navigator.product === 'ReactNative';
var isDOM = typeof document !== 'undefined';
/**
* Is `useLayoutEffect` in a DOM or React Native environment, otherwise resolves to useEffect
* Only useful to avoid the console warning.
*
* PREFER `useEffect` UNLESS YOU KNOW WHAT YOU ARE DOING.
*
* @category effects
*/
var _default = isDOM || isReactNative ? _react.useLayoutEffect : _react.useEffect;
exports.default = _default;
\ No newline at end of file
export declare class ObservableMap<K, V> extends Map<K, V> {
private readonly listener;
constructor(listener: (map: ObservableMap<K, V>) => void, init?: Iterable<Readonly<[K, V]>>);
set(key: K, value: V): this;
delete(key: K): boolean;
clear(): void;
}
/**
* Create and return a [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) that triggers rerenders when it's updated.
*
* ```tsx
* const customerAges = useMap<number>([
* ['john', 24],
* ['betsy', 25]
* ]);
*
* return (
* <>
* {Array.from(ids, ([name, age]) => (
* <div>
* {name}: {age}. <button onClick={() => ids.delete(name)}>X</button>
* </div>
* )}
* </>
* )
* ```
*
* @param init initial Map entries
*/
declare function useMap<K, V>(init?: Iterable<Readonly<[K, V]>>): ObservableMap<K, V>;
export default useMap;
"use strict";
exports.__esModule = true;
exports.default = exports.ObservableMap = void 0;
var _useForceUpdate = _interopRequireDefault(require("./useForceUpdate"));
var _useStableMemo = _interopRequireDefault(require("./useStableMemo"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var ObservableMap =
/*#__PURE__*/
function (_Map) {
_inheritsLoose(ObservableMap, _Map);
function ObservableMap(listener, init) {
var _this;
_this = _Map.call(this, init) || this;
_this.listener = listener;
return _this;
}
var _proto = ObservableMap.prototype;
_proto.set = function set(key, value) {
_Map.prototype.set.call(this, key, value); // When initializing the Map, the base Map calls this.set() before the
// listener is assigned so it will be undefined
if (this.listener) this.listener(this);
return this;
};
_proto.delete = function _delete(key) {
var result = _Map.prototype.delete.call(this, key);
this.listener(this);
return result;
};
_proto.clear = function clear() {
_Map.prototype.clear.call(this);
this.listener(this);
};
return ObservableMap;
}(
/*#__PURE__*/
_wrapNativeSuper(Map));
/**
* Create and return a [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) that triggers rerenders when it's updated.
*
* ```tsx
* const customerAges = useMap<number>([
* ['john', 24],
* ['betsy', 25]
* ]);
*
* return (
* <>
* {Array.from(ids, ([name, age]) => (
* <div>
* {name}: {age}. <button onClick={() => ids.delete(name)}>X</button>
* </div>
* )}
* </>
* )
* ```
*
* @param init initial Map entries
*/
exports.ObservableMap = ObservableMap;
function useMap(init) {
var forceUpdate = (0, _useForceUpdate.default)();
return (0, _useStableMemo.default)(function () {
return new ObservableMap(forceUpdate, init);
}, []);
}
var _default = useMap;
exports.default = _default;
\ No newline at end of file
/**
* Match a media query and get updates as the match changes. The media string is
* passed directly to `window.matchMedia` and run as a Layout Effect, so initial
* matches are returned before the browser has a chance to paint.
*
* ```tsx
* function Page() {
* const isWide = useMediaQuery('min-width: 1000px')
*
* return isWide ? "very wide" : 'not so wide'
* }
* ```
*
* Media query lists are also reused globally, hook calls for the same query
* will only create a matcher once under the hood.
*
* @param query A media query
*/
export default function useMediaQuery(query: string | null): boolean;
"use strict";
exports.__esModule = true;
exports.default = useMediaQuery;
var _useIsomorphicEffect = _interopRequireDefault(require("./useIsomorphicEffect"));
var _react = require("react");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isBool = function isBool(a) {
return typeof a === 'boolean';
};
var matchers = new Map();
var getMatcher = function getMatcher(query) {
if (!query || typeof window == 'undefined') return undefined;
var mql = matchers.get(query);
if (!mql) {
mql = window.matchMedia(query);
mql.refCount = 0;
matchers.set(mql.media, mql);
}
return mql;
};
/**
* Match a media query and get updates as the match changes. The media string is
* passed directly to `window.matchMedia` and run as a Layout Effect, so initial
* matches are returned before the browser has a chance to paint.
*
* ```tsx
* function Page() {
* const isWide = useMediaQuery('min-width: 1000px')
*
* return isWide ? "very wide" : 'not so wide'
* }
* ```
*
* Media query lists are also reused globally, hook calls for the same query
* will only create a matcher once under the hood.
*
* @param query A media query
*/
function useMediaQuery(query) {
var mql = getMatcher(query);
var _useState = (0, _react.useState)(function () {
return mql ? mql.matches : false;
}),
matches = _useState[0],
setMatches = _useState[1];
(0, _useIsomorphicEffect.default)(function () {
var mql = getMatcher(query);
if (!mql) {
return setMatches(false);
}
var handleChange = function handleChange() {
setMatches(mql.matches);
};
mql.refCount++;
mql.addListener(handleChange);
handleChange();
return function () {
mql.removeListener(handleChange);
mql.refCount--;
if (mql.refCount <= 0) {
matchers.delete(mql.media);
}
mql = undefined;
};
}, [query]);
return matches;
}
\ No newline at end of file
declare type Updater<TState> = (state: TState) => Partial<TState> | null;
/**
* Updates state, partial updates are merged into existing state values
*/
export declare type MergeStateSetter<TState> = (update: Updater<TState> | Partial<TState> | null) => void;
/**
* Mimics a React class component's state model, of having a single unified
* `state` object and an updater that merges updates into the existing state, as
* opposed to replacing it.
*
* ```js
* const [state, setState] = useMergeState({ name: 'Betsy', age: 24 })
*
* setState({ name: 'Johan' }) // { name: 'Johan', age: 24 }
*
* setState(state => ({ age: state.age + 10 })) // { name: 'Johan', age: 34 }
* ```
*
* @param initialState The initial state object
*/
export default function useMergeState<TState extends {}>(initialState: TState | (() => TState)): [TState, MergeStateSetter<TState>];
export {};
"use strict";
exports.__esModule = true;
exports.default = useMergeState;
var _react = require("react");
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); }
/**
* Mimics a React class component's state model, of having a single unified
* `state` object and an updater that merges updates into the existing state, as
* opposed to replacing it.
*
* ```js
* const [state, setState] = useMergeState({ name: 'Betsy', age: 24 })
*
* setState({ name: 'Johan' }) // { name: 'Johan', age: 24 }
*
* setState(state => ({ age: state.age + 10 })) // { name: 'Johan', age: 34 }
* ```
*
* @param initialState The initial state object
*/
function useMergeState(initialState) {
var _useState = (0, _react.useState)(initialState),
state = _useState[0],
setState = _useState[1];
var updater = (0, _react.useCallback)(function (update) {
if (update === null) return;
if (typeof update === 'function') {
setState(function (state) {
var nextState = update(state);
return nextState == null ? state : _extends({}, state, {}, nextState);
});
} else {
setState(function (state) {
return _extends({}, state, {}, update);
});
}
}, [setState]);
return [state, updater];
}
\ No newline at end of file
import { MergeStateSetter } from './useMergeState';
declare type Mapper<TProps, TState> = (props: TProps, state: TState) => null | Partial<TState>;
export default function useMergeStateFromProps<TProps, TState>(props: TProps, gDSFP: Mapper<TProps, TState>, initialState: TState): [TState, MergeStateSetter<TState>];
export {};
"use strict";
exports.__esModule = true;
exports.default = useMergeStateFromProps;
var _useMergeState2 = _interopRequireDefault(require("./useMergeState"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function useMergeStateFromProps(props, gDSFP, initialState) {
var _useMergeState = (0, _useMergeState2.default)(initialState),
state = _useMergeState[0],
setState = _useMergeState[1];
var nextState = gDSFP(props, state);
if (nextState !== null) setState(nextState);
return [state, setState];
}
\ No newline at end of file
/// <reference types="react" />
declare type CallbackRef<T> = (ref: T | null) => void;
declare type Ref<T> = React.MutableRefObject<T> | CallbackRef<T>;
export declare function mergeRefs<T>(refA?: Ref<T> | null, refB?: Ref<T> | null): (value: T | null) => void;
/**
* Create and returns a single callback ref composed from two other Refs.
*
* ```tsx
* const Button = React.forwardRef((props, ref) => {
* const [element, attachRef] = useCallbackRef<HTMLButtonElement>();
* const mergedRef = useMergedRefs(ref, attachRef);
*
* return <button ref={mergedRef} {...props}/>
* })
* ```
*
* @param refA A Callback or mutable Ref
* @param refB A Callback or mutable Ref
* @category refs
*/
declare function useMergedRefs<T>(refA?: Ref<T> | null, refB?: Ref<T> | null): (value: T | null) => void;
export default useMergedRefs;
"use strict";
exports.__esModule = true;
exports.mergeRefs = mergeRefs;
exports.default = void 0;
var _react = require("react");
var toFnRef = function toFnRef(ref) {
return !ref || typeof ref === 'function' ? ref : function (value) {
ref.current = value;
};
};
function mergeRefs(refA, refB) {
var a = toFnRef(refA);
var b = toFnRef(refB);
return function (value) {
if (a) a(value);
if (b) b(value);
};
}
/**
* Create and returns a single callback ref composed from two other Refs.
*
* ```tsx
* const Button = React.forwardRef((props, ref) => {
* const [element, attachRef] = useCallbackRef<HTMLButtonElement>();
* const mergedRef = useMergedRefs(ref, attachRef);
*
* return <button ref={mergedRef} {...props}/>
* })
* ```
*
* @param refA A Callback or mutable Ref
* @param refB A Callback or mutable Ref
* @category refs
*/
function useMergedRefs(refA, refB) {
return (0, _react.useMemo)(function () {
return mergeRefs(refA, refB);
}, [refA, refB]);
}
var _default = useMergedRefs;
exports.default = _default;
\ 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