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

first commit

parent 81c6da4b
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;
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _react = require("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 (0, _react.useEffect)(effect, []);
}
var _default = useMountEffect;
exports.default = _default;
\ 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;
"use strict";
exports.__esModule = true;
exports.default = useMounted;
var _react = require("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);
* }
* })
* })
* ```
*/
function useMounted() {
var mounted = (0, _react.useRef)(true);
var isMounted = (0, _react.useRef)(function () {
return mounted.current;
});
(0, _react.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;
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _useCustomEffect = _interopRequireDefault(require("./useCustomEffect"));
var _isEqual = _interopRequireDefault(require("lodash/isEqual"));
var _useImmediateUpdateEffect = _interopRequireDefault(require("./useImmediateUpdateEffect"));
var _useEventCallback = _interopRequireDefault(require("./useEventCallback"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isDepsEqual(_ref, _ref2) {
var nextElement = _ref[0],
nextConfig = _ref[1];
var prevElement = _ref2[0],
prevConfig = _ref2[1];
return nextElement === prevElement && (0, _isEqual.default)(nextConfig, prevConfig);
}
/**
* 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
*/
function useMutationObserver(element, config, callback) {
var fn = (0, _useEventCallback.default)(callback);
(0, _useCustomEffect.default)(function () {
if (!element) return; // The behavior around reusing mutation observers is confusing
// observing again _should_ disable the last listener but doesn't
// seem to always be the case, maybe just in JSDOM? In any case the cost
// to redeclaring it is gonna be fairly low anyway, so make it simple
var observer = new MutationObserver(fn);
observer.observe(element, config);
return function () {
observer.disconnect();
};
}, [element, config], {
isEqual: isDepsEqual,
// Intentionally done in render, otherwise observer will miss any
// changes made to the DOM during this update
effectHook: _useImmediateUpdateEffect.default
});
}
var _default = useMutationObserver;
exports.default = _default;
\ No newline at end of file
/**
* Store the last of some value. Tracked via a `Ref` only updating it
* after the component renders.
*
* Helpful if you need to compare a prop value to it's previous value during render.
*
* ```ts
* function Component(props) {
* const lastProps = usePrevious(props)
*
* if (lastProps.foo !== props.foo)
* resetValueFromProps(props.foo)
* }
* ```
*
* @param value the value to track
*/
export default function usePrevious<T>(value: T): T | null;
"use strict";
exports.__esModule = true;
exports.default = usePrevious;
var _react = require("react");
/**
* Store the last of some value. Tracked via a `Ref` only updating it
* after the component renders.
*
* Helpful if you need to compare a prop value to it's previous value during render.
*
* ```ts
* function Component(props) {
* const lastProps = usePrevious(props)
*
* if (lastProps.foo !== props.foo)
* resetValueFromProps(props.foo)
* }
* ```
*
* @param value the value to track
*/
function usePrevious(value) {
var ref = (0, _react.useRef)(null);
(0, _react.useEffect)(function () {
ref.current = value;
});
return ref.current;
}
\ No newline at end of file
declare function useRafInterval(fn: () => void, ms: number): void;
export default useRafInterval;
"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 useRafInterval(fn, ms, paused) {
if (paused === void 0) {
paused = false;
}
var handle;
var start = new Date().getTime();
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);
function loop() {
var current = new Date().getTime();
var delta = current - start;
if (pausedRef.current) return;
if (delta >= ms && fnRef.current) {
fnRef.current();
start = new Date().getTime();
}
cancelAnimationFrame(handle);
handle = requestAnimationFrame(loop);
}
(0, _react.useEffect)(function () {
handle = requestAnimationFrame(loop);
return function () {
return cancelAnimationFrame(handle);
};
}, []);
}
var _default = useRafInterval;
exports.default = _default;
\ No newline at end of file
/// <reference types="react" />
/**
* Exactly the same as `useRef` except that the initial value is set via a
* factroy function. Useful when the default is relatively costly to construct.
*
* ```ts
* const ref = useRefWithInitialValueFactory<ExpensiveValue>(() => constructExpensiveValue())
*
* ```
*
* @param initialValueFactory A factory function returning the ref's default value
* @category refs
*/
export default function useRefWithInitialValueFactory<T>(initialValueFactory: () => T): import("react").MutableRefObject<T>;
"use strict";
exports.__esModule = true;
exports.default = useRefWithInitialValueFactory;
var _react = require("react");
var dft = Symbol('default value sigil');
/**
* Exactly the same as `useRef` except that the initial value is set via a
* factroy function. Useful when the default is relatively costly to construct.
*
* ```ts
* const ref = useRefWithInitialValueFactory<ExpensiveValue>(() => constructExpensiveValue())
*
* ```
*
* @param initialValueFactory A factory function returning the ref's default value
* @category refs
*/
function useRefWithInitialValueFactory(initialValueFactory) {
var ref = (0, _react.useRef)(dft);
if (ref.current === dft) {
ref.current = initialValueFactory();
}
return ref;
}
\ No newline at end of file
export interface Rect {
width: number;
height: number;
x?: number;
y?: number;
}
/**
* Efficiently observe size changes on an element. Depends on the `ResizeObserver` api,
* and polyfills are needed in older browsers.
*
* ```ts
* const [ref, attachRef] = useCallbackRef(null);
*
* const rect = useResizeObserver(ref);
*
* return (
* <div ref={attachRef}>
* {JSON.stringify(rect)}
* </div>
* )
* ```
*
* @param element The DOM element to observe
*/
export default function useResizeObserver<TElement extends Element>(element: TElement | null | undefined): Rect | null;
"use strict";
exports.__esModule = true;
exports.default = useResizeObserver;
var _react = require("react");
var _useIsomorphicEffect = _interopRequireDefault(require("./useIsomorphicEffect"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var targetMap = new WeakMap();
var resizeObserver;
function getResizeObserver() {
// eslint-disable-next-line no-return-assign
return resizeObserver = resizeObserver || new window.ResizeObserver(function (entries) {
entries.forEach(function (entry) {
var handler = targetMap.get(entry.target);
if (handler) handler(entry.contentRect);
});
});
}
/**
* Efficiently observe size changes on an element. Depends on the `ResizeObserver` api,
* and polyfills are needed in older browsers.
*
* ```ts
* const [ref, attachRef] = useCallbackRef(null);
*
* const rect = useResizeObserver(ref);
*
* return (
* <div ref={attachRef}>
* {JSON.stringify(rect)}
* </div>
* )
* ```
*
* @param element The DOM element to observe
*/
function useResizeObserver(element) {
var _useState = (0, _react.useState)(null),
rect = _useState[0],
setRect = _useState[1];
(0, _useIsomorphicEffect.default)(function () {
if (!element) return;
getResizeObserver().observe(element);
setRect(element.getBoundingClientRect());
targetMap.set(element, function (rect) {
setRect(rect);
});
return function () {
targetMap.delete(element);
};
}, [element]);
return rect;
}
\ No newline at end of file
import { Dispatch, SetStateAction } from 'react';
import { AsyncSetState } from './useStateAsync';
declare type StateSetter<TState> = Dispatch<SetStateAction<TState>>;
/**
* `useSafeState` takes the return value of a `useState` hook and wraps the
* setter to prevent updates onces the component has unmounted. Can used
* with `useMergeState` and `useStateAsync` as well
*
* @param state The return value of a useStateHook
*
* ```ts
* const [show, setShow] = useSafeState(useState(true));
* ```
*/
declare function useSafeState<TState>(state: [TState, AsyncSetState<TState>]): [TState, (stateUpdate: React.SetStateAction<TState>) => Promise<void>];
declare function useSafeState<TState>(state: [TState, StateSetter<TState>]): [TState, StateSetter<TState>];
export default useSafeState;
"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 useSafeState(state) {
var isMounted = (0, _useMounted.default)();
return [state[0], (0, _react.useCallback)(function (nextState) {
if (!isMounted()) return;
return state[1](nextState);
}, [isMounted, state[1]])];
}
var _default = useSafeState;
exports.default = _default;
\ No newline at end of file
export declare class ObservableSet<V> extends Set<V> {
private readonly listener;
constructor(listener: (map: ObservableSet<V>) => void, init?: Iterable<V>);
add(value: V): this;
delete(value: V): boolean;
clear(): void;
}
/**
* Create and return a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) that triggers rerenders when it's updated.
*
* ```ts
* const ids = useSet<number>([1,2,3,4]);
*
* return (
* <>
* {Array.from(ids, id => (
* <div>
* id: {id}. <button onClick={() => ids.delete(id)}>X</button>
* </div>
* )}
* </>
* )
* ```
*
* @param init initial Set values
*/
declare function useSet<V>(init?: Iterable<V>): ObservableSet<V>;
export default useSet;
"use strict";
exports.__esModule = true;
exports.default = exports.ObservableSet = 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 ObservableSet =
/*#__PURE__*/
function (_Set) {
_inheritsLoose(ObservableSet, _Set);
function ObservableSet(listener, init) {
var _this;
_this = _Set.call(this, init) || this;
_this.listener = listener;
return _this;
}
var _proto = ObservableSet.prototype;
_proto.add = function add(value) {
_Set.prototype.add.call(this, value); // When initializing the Set, the base Set calls this.add() before the
// listener is assigned so it will be undefined
if (this.listener) this.listener(this);
return this;
};
_proto.delete = function _delete(value) {
var result = _Set.prototype.delete.call(this, value);
this.listener(this);
return result;
};
_proto.clear = function clear() {
_Set.prototype.clear.call(this);
this.listener(this);
};
return ObservableSet;
}(
/*#__PURE__*/
_wrapNativeSuper(Set));
/**
* Create and return a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) that triggers rerenders when it's updated.
*
* ```ts
* const ids = useSet<number>([1,2,3,4]);
*
* return (
* <>
* {Array.from(ids, id => (
* <div>
* id: {id}. <button onClick={() => ids.delete(id)}>X</button>
* </div>
* )}
* </>
* )
* ```
*
* @param init initial Set values
*/
exports.ObservableSet = ObservableSet;
function useSet(init) {
var forceUpdate = (0, _useForceUpdate.default)();
return (0, _useStableMemo.default)(function () {
return new ObservableSet(forceUpdate, init);
}, []);
}
var _default = useSet;
exports.default = _default;
\ No newline at end of file
import { DependencyList } from 'react';
/**
* Identical to `useMemo` _except_ that it provides a semantic guarantee that
* values will not be invalidated unless the dependencies change. This is unlike
* the built in `useMemo` which may discard memoized values for performance reasons.
*
* @param factory A function that returns a value to be memoized
* @param deps A dependency array
*/
export default function useStableMemo<T>(factory: () => T, deps?: DependencyList): T;
"use strict";
exports.__esModule = true;
exports.default = useStableMemo;
var _react = require("react");
function isEqual(a, b) {
if (a.length !== b.length) return false;
for (var i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/**
* Identical to `useMemo` _except_ that it provides a semantic guarantee that
* values will not be invalidated unless the dependencies change. This is unlike
* the built in `useMemo` which may discard memoized values for performance reasons.
*
* @param factory A function that returns a value to be memoized
* @param deps A dependency array
*/
function useStableMemo(factory, deps) {
var isValid = true;
var valueRef = (0, _react.useRef)(); // initial hook call
if (!valueRef.current) {
valueRef.current = {
deps: deps,
result: factory()
}; // subsequent calls
} else {
isValid = !!(deps && valueRef.current.deps && isEqual(deps, valueRef.current.deps));
}
var cache = isValid ? valueRef.current : {
deps: deps,
result: factory()
}; // must update immediately so any sync renders here don't cause an infinite loop
valueRef.current = cache;
return cache.result;
}
\ 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