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

first commit

parent 81c6da4b
import { useState } from 'react';
import useStableMemo from './useStableMemo';
import useEffect from './useIsomorphicEffect';
/**
* 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(element, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
threshold = _ref.threshold,
root = _ref.root,
rootMargin = _ref.rootMargin;
var _useState = useState(null),
entries = _useState[0],
setEntry = _useState[1];
var observer = useStableMemo(function () {
return typeof IntersectionObserver !== 'undefined' && new IntersectionObserver(function (entries) {
return setEntry(entries);
}, {
threshold: threshold,
root: root,
rootMargin: rootMargin
});
}, [root, rootMargin, threshold && JSON.stringify(threshold)]);
useEffect(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;
import { useEffect } from 'react';
import useCommittedRef from './useCommittedRef';
/**
* 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
*/
function useInterval(fn, ms, paused, runImmediately) {
if (paused === void 0) {
paused = false;
}
if (runImmediately === void 0) {
runImmediately = false;
}
var handle;
var fnRef = useCommittedRef(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 = useCommittedRef(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);
};
useEffect(function () {
if (runImmediately) {
tick();
} else {
schedule();
}
return function () {
return clearTimeout(handle);
};
}, [paused, runImmediately]);
}
export default useInterval;
\ 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;
import { useEffect, useLayoutEffect } from '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
*/
export default isDOM || isReactNative ? useLayoutEffect : useEffect;
\ 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;
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); }
import useForceUpdate from './useForceUpdate';
import useStableMemo from './useStableMemo';
export 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
*/
function useMap(init) {
var forceUpdate = useForceUpdate();
return useStableMemo(function () {
return new ObservableMap(forceUpdate, init);
}, []);
}
export default useMap;
\ 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;
import useEffect from './useIsomorphicEffect';
import { useState } from 'react';
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
*/
export default function useMediaQuery(query) {
var mql = getMatcher(query);
var _useState = useState(function () {
return mql ? mql.matches : false;
}),
matches = _useState[0],
setMatches = _useState[1];
useEffect(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 {};
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); }
import { useCallback, useState } from 'react';
/**
* 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(initialState) {
var _useState = useState(initialState),
state = _useState[0],
setState = _useState[1];
var updater = 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 {};
import useMergeState from './useMergeState';
export default function useMergeStateFromProps(props, gDSFP, initialState) {
var _useMergeState = useMergeState(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;
import { useMemo } from 'react';
var toFnRef = function toFnRef(ref) {
return !ref || typeof ref === 'function' ? ref : function (value) {
ref.current = value;
};
};
export 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 useMemo(function () {
return mergeRefs(refA, refB);
}, [refA, refB]);
}
export default useMergedRefs;
\ No newline at end of file
import { EffectCallback } from 'react';
/**
* Run's an effect on mount, and is cleaned up on unmount. Generally
* useful for interop with non-react plugins or components
*
* ```ts
* useMountEffect(() => {
* const plugin = $.myPlugin(ref.current)
*
* return () => {
* plugin.destroy()
* }
* })
* ```
* @param effect An effect to run on mount
*
* @category effects
*/
declare function useMountEffect(effect: EffectCallback): void;
export default useMountEffect;
import { useEffect } from 'react';
/**
* Run's an effect on mount, and is cleaned up on unmount. Generally
* useful for interop with non-react plugins or components
*
* ```ts
* useMountEffect(() => {
* const plugin = $.myPlugin(ref.current)
*
* return () => {
* plugin.destroy()
* }
* })
* ```
* @param effect An effect to run on mount
*
* @category effects
*/
function useMountEffect(effect) {
return useEffect(effect, []);
}
export default useMountEffect;
\ No newline at end of file
/**
* Track whether a component is current mounted. Generally less preferable than
* properlly canceling effects so they don't run after a component is unmounted,
* but helpful in cases where that isn't feasible, such as a `Promise` resolution.
*
* @returns a function that returns the current isMounted state of the component
*
* ```ts
* const [data, setData] = useState(null)
* const isMounted = useMounted()
*
* useEffect(() => {
* fetchdata().then((newData) => {
* if (isMounted()) {
* setData(newData);
* }
* })
* })
* ```
*/
export default function useMounted(): () => boolean;
import { useRef, useEffect } from 'react';
/**
* Track whether a component is current mounted. Generally less preferable than
* properlly canceling effects so they don't run after a component is unmounted,
* but helpful in cases where that isn't feasible, such as a `Promise` resolution.
*
* @returns a function that returns the current isMounted state of the component
*
* ```ts
* const [data, setData] = useState(null)
* const isMounted = useMounted()
*
* useEffect(() => {
* fetchdata().then((newData) => {
* if (isMounted()) {
* setData(newData);
* }
* })
* })
* ```
*/
export default function useMounted() {
var mounted = useRef(true);
var isMounted = useRef(function () {
return mounted.current;
});
useEffect(function () {
return function () {
mounted.current = false;
};
}, []);
return isMounted.current;
}
\ No newline at end of file
/**
* Observe mutations on a DOM node or tree of DOM nodes.
* Depends on the `MutationObserver` api.
*
* ```ts
* const [element, attachRef] = useCallbackRef(null);
*
* useMutationObserver(element, { subtree: true }, (records) => {
*
* });
*
* return (
* <div ref={attachRef} />
* )
* ```
*
* @param element The DOM element to observe
* @param config The observer configuration
* @param callback A callback fired when a mutation occurs
*/
declare function useMutationObserver(element: Element | null | undefined, config: MutationObserverInit, callback: MutationCallback): void;
export default useMutationObserver;
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