Object.defineProperty(exports, '__esModule', { value: true }); var React = require('react'); var lodashEs = require('lodash-es'); var Cookies = require('js-cookie'); var screenfull = require('screenfull'); var index_js = require('use-sync-external-store/shim/index.js'); var fetchEventSource = require('@microsoft/fetch-event-source'); function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } var React__default = /*#__PURE__*/_interopDefault(React); var Cookies__default = /*#__PURE__*/_interopDefault(Cookies); var screenfull__default = /*#__PURE__*/_interopDefault(screenfull); const useLatest = (value)=>{ const ref = React.useRef(value); ref.current = value; return ref; }; var _window_navigator, _window; function isFunction(val) { return typeof val === 'function'; } function isString(val) { return typeof val === 'string'; } const isDev = process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test'; const isBrowser = typeof window !== 'undefined'; const isNavigator = typeof navigator !== 'undefined'; function noop() {} const isIOS = isBrowser && ((_window = window) == null ? void 0 : (_window_navigator = _window.navigator) == null ? void 0 : _window_navigator.userAgent) && /iP(?:ad|hone|od)/.test(window.navigator.userAgent); function on(obj, ...args) { if (obj && obj.addEventListener) { obj.addEventListener(...args); } } function off(obj, ...args) { if (obj && obj.removeEventListener) { obj.removeEventListener(...args); } } const defaultWindow = isBrowser ? window : undefined; const defaultOptions$1 = {}; function defaultOnError(e) { console.error(e); } function getTargetElement(target, defaultElement) { if (!isBrowser) { return undefined; } if (!target) { return defaultElement; } let targetElement; if (isFunction(target)) { targetElement = target(); } else if ('current' in target) { targetElement = target.current; } else { targetElement = target; } return targetElement; } const useCustomCompareEffect = (effect, deps, depsEqual)=>{ if (process.env.NODE_ENV !== 'production') { if (!Array.isArray(deps) || !deps.length) { console.warn('`useCustomCompareEffect` should not be used with no dependencies. Use React.useEffect instead.'); } if (typeof depsEqual !== 'function') { console.warn('`useCustomCompareEffect` should be used with depsEqual callback for comparing deps list'); } } const ref = React.useRef(undefined); if (!ref.current || !depsEqual(deps, ref.current)) { ref.current = deps; } // eslint-disable-next-line react-hooks/exhaustive-deps React.useEffect(effect, ref.current); }; const useDeepCompareEffect = (effect, deps)=>{ if (process.env.NODE_ENV !== 'production') { if (!Array.isArray(deps) || !deps.length) { console.warn('`useDeepCompareEffect` should not be used with no dependencies. Use React.useEffect instead.'); } } useCustomCompareEffect(effect, deps, lodashEs.isEqual); }; function useEventListener(eventName, handler, element, options = defaultOptions$1) { const savedHandler = useLatest(handler); useDeepCompareEffect(()=>{ const targetElement = getTargetElement(element, defaultWindow); if (!(targetElement && targetElement.addEventListener)) { return; } const eventListener = (event)=>savedHandler.current(event); on(targetElement, eventName, eventListener, options); return ()=>{ if (!(targetElement && targetElement.removeEventListener)) { return; } off(targetElement, eventName, eventListener); }; }, [ eventName, element, options ]); } const useMount = (fn)=>{ if (isDev) { if (!isFunction(fn)) { console.error(`useMount: parameter \`fn\` expected to be a function, but got "${typeof fn}".`); } } React.useEffect(()=>{ fn == null ? void 0 : fn(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); }; const useActiveElement = ()=>{ const [active, setActive] = React.useState(null); const listener = React.useCallback(()=>{ var _window; setActive((_window = window) == null ? void 0 : _window.document.activeElement); }, []); useEventListener('blur', listener, ()=>window, true); useEventListener('focus', listener, ()=>window, true); useMount(()=>{ var _window; setActive((_window = window) == null ? void 0 : _window.document.activeElement); }); return active; }; function useMountedState() { const mountedRef = React.useRef(false); const get = React.useCallback(()=>mountedRef.current, []); React.useEffect(()=>{ mountedRef.current = true; return ()=>{ mountedRef.current = false; }; }, []); return get; } function asyncGeneratorStep$7(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _async_to_generator$7(fn) { return function() { var self = this, args = arguments; return new Promise(function(resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep$7(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep$7(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } const useAsyncEffect = (effect, cleanup = noop, deps)=>{ const mounted = useMountedState(); React.useEffect(()=>{ const execute = /*#__PURE__*/ _async_to_generator$7(function*() { if (!mounted()) { return; } yield effect(); }); execute(); return ()=>{ cleanup(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, deps); }; const listerOptions = { passive: true }; const useClickOutside = (target, handler, enabled = true)=>{ const savedHandler = useLatest(handler); const listener = (event)=>{ if (!enabled) { return; } const element = getTargetElement(target); if (!element) { return; } const elements = event.composedPath(); if (element === event.target || elements.includes(element)) { return; } savedHandler.current(event); }; useEventListener('mousedown', listener, defaultWindow, listerOptions); useEventListener('touchstart', listener, defaultWindow, listerOptions); }; function getInitialState$5(key, defaultValue) { // Prevent a React hydration mismatch when a default value is provided. if (defaultValue !== undefined) { return defaultValue; } if (isBrowser) { return Cookies__default.default.get(key); } if (process.env.NODE_ENV !== 'production') { console.warn('`useCookie` When server side rendering, defaultValue should be defined to prevent a hydration mismatches.'); } return ''; } const useCookie = (key, options = defaultOptions$1, defaultValue)=>{ const [cookieValue, setCookieValue] = React.useState(getInitialState$5(key, defaultValue)); React.useEffect(()=>{ const getStoredValue = ()=>{ const raw = Cookies__default.default.get(key); if (raw !== undefined && raw !== null) { return raw; } else { if (defaultValue === undefined) { Cookies__default.default.remove(key); } else { Cookies__default.default.set(key, defaultValue, options); } return defaultValue; } }; setCookieValue(getStoredValue()); // eslint-disable-next-line react-hooks/exhaustive-deps }, [ defaultValue, key, JSON.stringify(options) ]); const updateCookie = React.useCallback((newValue)=>{ const value = isFunction(newValue) ? newValue(cookieValue) : newValue; if (value === undefined) { Cookies__default.default.remove(key); } else { Cookies__default.default.set(key, value, options); } setCookieValue(value); }, // eslint-disable-next-line react-hooks/exhaustive-deps [ key, cookieValue, JSON.stringify(options) ]); const refreshCookie = React.useCallback(()=>{ const cookieValue = Cookies__default.default.get(key); if (isString(cookieValue)) { setCookieValue(cookieValue); } }, [ key ]); return [ cookieValue, updateCookie, refreshCookie ]; }; const useIsomorphicLayoutEffect = isBrowser ? React.useLayoutEffect : React.useEffect; /** * keep function reference immutable */ const useEvent = (fn)=>{ if (isDev) { if (!isFunction(fn)) { console.error(`useEvent expected parameter is a function, got ${typeof fn}`); } } const handlerRef = React.useRef(fn); useIsomorphicLayoutEffect(()=>{ handlerRef.current = fn; }, [ fn ]); return React.useCallback((...args)=>{ const fn = handlerRef.current; return fn(...args); }, []); }; const useInterval = (callback, delay, options = defaultOptions$1)=>{ const { immediate, controls } = options; const savedCallback = useLatest(callback); const isActive = React.useRef(false); const timer = React.useRef(null); const clean = ()=>{ timer.current && clearInterval(timer.current); }; const resume = useEvent(()=>{ isActive.current = true; timer.current = setInterval(()=>savedCallback.current(), delay || 0); }); const pause = useEvent(()=>{ isActive.current = false; clean(); }); React.useEffect(()=>{ if (immediate) { savedCallback.current(); } if (controls) { return; } if (delay !== null) { resume(); return ()=>{ clean(); }; } return undefined; // eslint-disable-next-line react-hooks/exhaustive-deps }, [ delay, immediate ]); return { isActive, pause, resume }; }; function padZero(time) { return `${time}`.length < 2 ? `0${time}` : `${time}`; } function getHMSTime(timeDiff) { if (timeDiff <= 0) { return [ '00', '00', '00' ]; } if (timeDiff > 100 * 3600) { return [ '99', '59', '59' ]; } const hour = Math.floor(timeDiff / 3600); const minute = Math.floor((timeDiff - hour * 3600) / 60); const second = timeDiff - hour * 3600 - minute * 60; return [ padZero(hour), padZero(minute), padZero(second) ]; } const useCountDown = (time, format = getHMSTime, callback)=>{ const [remainTime, setRemainTime] = React.useState(time); const [delay, setDelay] = React.useState(1000); useInterval(()=>{ if (remainTime <= 0) { setDelay(null); return; } setRemainTime(remainTime - 1); }, delay); React.useEffect(()=>{ if (time > 0 && remainTime <= 0) { callback && callback(); } }, [ callback, remainTime, time ]); const [hour, minute, secoud] = format(remainTime); return [ hour, minute, secoud ]; }; const useCounter = (initialValue = 0, max = null, min = null)=>{ // avoid exec init code every render const initFunc = ()=>{ let init = typeof initialValue === 'function' ? initialValue() : initialValue; typeof init !== 'number' && console.error(`initialValue has to be a number, got ${typeof initialValue}`); if (typeof min === 'number') { init = Math.max(init, min); } else if (min !== null) { console.error(`min has to be a number, got ${typeof min}`); } if (typeof max === 'number') { init = Math.min(init, max); } else if (max !== null) { console.error(`max has to be a number, got ${typeof max}`); } return init; }; const [value, setValue] = React.useState(initFunc); const set = useEvent((newState)=>{ setValue((v)=>{ let nextValue = typeof newState === 'function' ? newState(v) : newState; if (typeof min === 'number') { nextValue = Math.max(nextValue, min); } if (typeof max === 'number') { nextValue = Math.min(nextValue, max); } return nextValue; }); }); const inc = (delta = 1)=>{ set((value)=>value + delta); }; const dec = (delta = 1)=>{ set((value)=>value - delta); }; const reset = ()=>{ set(initFunc); }; return [ value, set, inc, dec, reset ]; }; const defaultOptions = { observe: false }; function getInitialState$4(defaultValue) { // Prevent a React hydration mismatch when a default value is provided. if (defaultValue !== undefined) { return defaultValue; } if (isBrowser) { return ''; } if (process.env.NODE_ENV !== 'production') { console.warn('`useCssVar` When server side rendering, defaultValue should be defined to prevent a hydration mismatches.'); } return ''; } const useCssVar = (prop, target, defaultValue, options = defaultOptions)=>{ const { observe } = options; const [variable, setVariable] = React.useState(getInitialState$4(defaultValue)); const observerRef = React.useRef(); const set = React.useCallback((v)=>{ const element = getTargetElement(target); if (element == null ? void 0 : element.style) { element == null ? void 0 : element.style.setProperty(prop, v); setVariable(v); } }, [ prop, target ]); const updateCssVar = React.useCallback(()=>{ const element = getTargetElement(target); if (element) { var _window_getComputedStyle_getPropertyValue; const value = (_window_getComputedStyle_getPropertyValue = window.getComputedStyle(element).getPropertyValue(prop)) == null ? void 0 : _window_getComputedStyle_getPropertyValue.trim(); setVariable(value); } }, [ target, prop ]); React.useEffect(()=>{ var _window_getComputedStyle_getPropertyValue; const element = getTargetElement(target); if (!element) { return; } const value = (_window_getComputedStyle_getPropertyValue = window.getComputedStyle(element).getPropertyValue(prop)) == null ? void 0 : _window_getComputedStyle_getPropertyValue.trim(); /** if var don't has value and defaultValue exist */ if (!value && defaultValue) { set(defaultValue); } else { updateCssVar(); } if (!observe) { return; } observerRef.current = new MutationObserver(updateCssVar); observerRef.current.observe(element, { attributeFilter: [ 'style', 'class' ] }); return ()=>{ if (observerRef.current) { observerRef.current.disconnect(); } }; }, [ observe, target, updateCssVar, set, defaultValue, prop ]); return [ variable, set ]; }; const useCycleList = (list, i = 0)=>{ const [index, setIndex] = React.useState(i); const set = (i)=>{ const length = list.length; const nextIndex = ((index + i) % length + length) % length; setIndex(nextIndex); }; const next = (i = 1)=>{ set(i); }; const prev = (i = 1)=>{ set(-i); }; return [ list[index], next, prev ]; }; function guessSerializerType(rawInit) { return rawInit == null || rawInit === undefined ? 'any' : rawInit instanceof Set ? 'set' : rawInit instanceof Map ? 'map' : rawInit instanceof Date ? 'date' : typeof rawInit === 'boolean' ? 'boolean' : typeof rawInit === 'string' ? 'string' : typeof rawInit === 'object' ? 'object' : Array.isArray(rawInit) ? 'object' : !Number.isNaN(rawInit) ? 'number' : 'any'; } const StorageSerializers = { boolean: { read: (v)=>v === 'true', write: (v)=>String(v) }, object: { read: (v)=>JSON.parse(v), write: (v)=>JSON.stringify(v) }, number: { read: (v)=>Number.parseFloat(v), write: (v)=>String(v) }, any: { read: (v)=>v, write: (v)=>String(v) }, string: { read: (v)=>v, write: (v)=>String(v) }, map: { read: (v)=>new Map(JSON.parse(v)), write: (v)=>JSON.stringify(Array.from(v.entries())) }, set: { read: (v)=>new Set(JSON.parse(v)), write: (v)=>JSON.stringify(Array.from(v)) }, date: { read: (v)=>new Date(v), write: (v)=>v.toISOString() } }; function getInitialState$3(key, defaultValue, storage, serializer, onError) { // Prevent a React hydration mismatch when a default value is provided. if (defaultValue !== undefined) { return defaultValue; } if (isBrowser) { try { const raw = storage == null ? void 0 : storage.getItem(key); if (raw !== undefined && raw !== null) { return serializer == null ? void 0 : serializer.read(raw); } return null; } catch (error) { onError == null ? void 0 : onError(error); } } // A default value has not been provided, and you are rendering on the server, warn of a possible hydration mismatch when defaulting to false. if (process.env.NODE_ENV !== 'production') { console.warn('`createStorage` When server side rendering, defaultValue should be defined to prevent a hydration mismatches.'); } return null; } function useStorage(key, defaultValue, getStorage = ()=>isBrowser ? sessionStorage : undefined, options = defaultOptions$1) { let storage; const { onError = defaultOnError, effectStorageValue, mountStorageValue, listenToStorageChanges = true } = options; const storageValue = mountStorageValue != null ? mountStorageValue : effectStorageValue; try { storage = getStorage(); } catch (err) { onError(err); } const type = guessSerializerType(defaultValue); var _options_serializer; const serializer = (_options_serializer = options.serializer) != null ? _options_serializer : StorageSerializers[type]; const [state, setState] = React.useState(getInitialState$3(key, defaultValue, storage, serializer, onError)); useDeepCompareEffect(()=>{ var _ref; const data = (_ref = storageValue ? isFunction(storageValue) ? storageValue() : storageValue : defaultValue) != null ? _ref : null; const getStoredValue = ()=>{ try { const raw = storage == null ? void 0 : storage.getItem(key); if (raw !== undefined && raw !== null) { return serializer.read(raw); } else { storage == null ? void 0 : storage.setItem(key, serializer.write(data)); return data; } } catch (e) { onError(e); } }; setState(getStoredValue()); }, [ key, serializer, storage, onError, storageValue ]); const updateState = useEvent((valOrFunc)=>{ const currentState = isFunction(valOrFunc) ? valOrFunc(state) : valOrFunc; setState(currentState); if (currentState === null) { storage == null ? void 0 : storage.removeItem(key); } else { try { storage == null ? void 0 : storage.setItem(key, serializer.write(currentState)); } catch (e) { onError(e); } } }); const listener = useEvent(()=>{ try { const raw = storage == null ? void 0 : storage.getItem(key); if (raw !== undefined && raw !== null) { updateState(serializer.read(raw)); } else { updateState(null); } } catch (e) { onError(e); } }); React.useEffect(()=>{ if (listenToStorageChanges) { window.addEventListener('storage', listener); return ()=>window.removeEventListener('storage', listener); } return ()=>{}; }, [ listenToStorageChanges, listener ]); return [ state, updateState ]; } const useDarkMode = (options)=>{ const { selector = 'html', attribute = 'class', classNameDark = '', classNameLight = '', storageKey = 'reactuses-color-scheme', storage = ()=>isBrowser ? localStorage : undefined, defaultValue = false } = options; const value = ()=>{ return window.matchMedia('(prefers-color-scheme: dark)').matches; }; const [dark, setDark] = useStorage(storageKey, defaultValue, storage, { mountStorageValue: value }); React.useEffect(()=>{ var _window; const element = (_window = window) == null ? void 0 : _window.document.querySelector(selector); if (!element) { return; } if (attribute === 'class') { dark && classNameDark && element.classList.add(classNameDark); !dark && classNameLight && element.classList.add(classNameLight); } else { dark && classNameDark && element.setAttribute(attribute, classNameDark); !dark && classNameLight && element.setAttribute(attribute, classNameLight); } return ()=>{ if (!element) { return; } if (attribute === 'class') { dark && classNameDark && element.classList.remove(classNameDark); !dark && classNameLight && element.classList.remove(classNameLight); } else { dark && classNameDark && element.removeAttribute(attribute); !dark && classNameLight && element.removeAttribute(attribute); } }; }, [ attribute, classNameDark, classNameLight, dark, selector ]); return [ dark, ()=>setDark((dark)=>!dark), setDark ]; }; function useUnmount(fn) { if (isDev) { if (!isFunction(fn)) { console.error(`useUnmount expected parameter is a function, got ${typeof fn}`); } } const fnRef = useLatest(fn); React.useEffect(()=>()=>{ fnRef.current(); }, [ fnRef ]); } const useDebounceFn = (fn, wait, options)=>{ if (isDev) { if (!isFunction(fn)) { console.error(`useDebounceFn expected parameter is a function, got ${typeof fn}`); } } const fnRef = useLatest(fn); const debounced = React.useMemo(()=>lodashEs.debounce((...args)=>{ return fnRef.current(...args); }, wait, options), // eslint-disable-next-line react-hooks/exhaustive-deps [ JSON.stringify(options), wait ]); useUnmount(()=>{ debounced.cancel(); }); return { run: debounced, cancel: debounced.cancel, flush: debounced.flush }; }; const useDebounce = (value, wait, options)=>{ const [debounced, setDebounced] = React.useState(value); const { run } = useDebounceFn(()=>{ setDebounced(value); }, wait, options); React.useEffect(()=>{ run(); }, [ run, value ]); return debounced; }; function getInitialState$2(defaultValue) { // Prevent a React hydration mismatch when a default value is provided. if (defaultValue !== undefined) { return defaultValue; } if (isBrowser) { return document.visibilityState; } if (process.env.NODE_ENV !== 'production') { console.warn('`useDocumentVisibility` When server side rendering, defaultValue should be defined to prevent a hydration mismatches.'); } return 'visible'; } function useDocumentVisibility(defaultValue) { const [visible, setVisible] = React.useState(getInitialState$2(defaultValue)); useEventListener('visibilitychange', ()=>{ setVisible(document.visibilityState); }, ()=>document); React.useEffect(()=>{ setVisible(document.visibilityState); }, []); return visible; } const useDoubleClick = ({ target, latency = 300, onSingleClick = ()=>{}, onDoubleClick = ()=>{} })=>{ const handle = React.useCallback((onSingleClick, onDoubleClick)=>{ let count = 0; return (e)=>{ // prevent ios double click slide if (e.type === 'touchend') { e.stopPropagation(); e.preventDefault(); } count += 1; setTimeout(()=>{ if (count === 1) { onSingleClick(e); } else if (count === 2) { onDoubleClick(e); } count = 0; }, latency); }; }, [ latency ]); const handleClick = handle(onSingleClick, onDoubleClick); const handleTouchEnd = handle(onSingleClick, onDoubleClick); useEventListener('click', handleClick, target); useEventListener('touchend', handleTouchEnd, target, { passive: false }); }; function isScrollX(node) { if (!node) { return false; } return getComputedStyle(node).overflowX === 'auto' || getComputedStyle(node).overflowX === 'scroll'; } function isScrollY(node) { if (!node) { return false; } return getComputedStyle(node).overflowY === 'auto' || getComputedStyle(node).overflowY === 'scroll'; } const useDraggable = (target, options = {})=>{ const { draggingElement, containerElement } = options; var _options_handle; const draggingHandle = (_options_handle = options.handle) != null ? _options_handle : target; var _options_initialValue; const [position, setPositon] = React.useState((_options_initialValue = options.initialValue) != null ? _options_initialValue : { x: 0, y: 0 }); useDeepCompareEffect(()=>{ var _options_initialValue; setPositon((_options_initialValue = options.initialValue) != null ? _options_initialValue : { x: 0, y: 0 }); }, [ options.initialValue ]); const [pressedDelta, setPressedDelta] = React.useState(); const filterEvent = (e)=>{ if (options.pointerTypes) { return options.pointerTypes.includes(e.pointerType); } return true; }; const handleEvent = (e)=>{ if (options.preventDefault) { e.preventDefault(); } if (options.stopPropagation) { e.stopPropagation(); } }; const start = (e)=>{ var _container_getBoundingClientRect; const element = getTargetElement(target); if (!filterEvent(e) || !element) { return; } if (options.exact && e.target !== element) { return; } const container = getTargetElement(containerElement); const containerRect = container == null ? void 0 : (_container_getBoundingClientRect = container.getBoundingClientRect) == null ? void 0 : _container_getBoundingClientRect.call(container); const targetRect = element.getBoundingClientRect(); const pos = { x: e.clientX - (container && containerRect ? targetRect.left - (containerRect == null ? void 0 : containerRect.left) + container.scrollLeft : targetRect.left), y: e.clientY - (container && containerRect ? targetRect.top - containerRect.top + container.scrollTop : targetRect.top) }; if ((options.onStart == null ? void 0 : options.onStart.call(options, pos, e)) === false) { return; } setPressedDelta(pos); handleEvent(e); }; const move = (e)=>{ const element = getTargetElement(target); if (!filterEvent(e) || !element) { return; } if (!pressedDelta) { return; } const container = getTargetElement(containerElement); const targetRect = element.getBoundingClientRect(); let { x, y } = position; x = e.clientX - pressedDelta.x; y = e.clientY - pressedDelta.y; if (container) { const containerWidth = isScrollX(container) ? container.scrollWidth : container.clientWidth; const containerHeight = isScrollY(container) ? container.scrollHeight : container.clientHeight; x = Math.min(Math.max(0, x), containerWidth - targetRect.width); y = Math.min(Math.max(0, y), containerHeight - targetRect.height); } setPositon({ x, y }); options.onMove == null ? void 0 : options.onMove.call(options, position, e); handleEvent(e); }; const end = (e)=>{ if (!filterEvent(e)) { return; } if (!pressedDelta) { return; } setPressedDelta(undefined); options.onEnd == null ? void 0 : options.onEnd.call(options, position, e); handleEvent(e); }; useEventListener('pointerdown', start, draggingHandle, true); useEventListener('pointermove', move, draggingElement, true); useEventListener('pointerup', end, draggingElement, true); return [ position.x, position.y, !!pressedDelta, setPositon ]; }; const useDropZone = (target, onDrop)=>{ const [over, setOver] = React.useState(false); const counter = React.useRef(0); useEventListener('dragenter', (event)=>{ event.preventDefault(); counter.current += 1; setOver(true); }, target); useEventListener('dragover', (event)=>{ event.preventDefault(); }, target); useEventListener('dragleave', (event)=>{ event.preventDefault(); counter.current -= 1; if (counter.current === 0) { setOver(false); } }, target); useEventListener('drop', (event)=>{ var _event_dataTransfer; event.preventDefault(); counter.current = 0; setOver(false); var _event_dataTransfer_files; const files = Array.from((_event_dataTransfer_files = (_event_dataTransfer = event.dataTransfer) == null ? void 0 : _event_dataTransfer.files) != null ? _event_dataTransfer_files : []); onDrop == null ? void 0 : onDrop(files.length === 0 ? null : files); }, target); return over; }; const useResizeObserver = (target, callback, options = defaultOptions$1)=>{ const savedCallback = useLatest(callback); const observerRef = React.useRef(); const stop = React.useCallback(()=>{ if (observerRef.current) { observerRef.current.disconnect(); } }, []); useDeepCompareEffect(()=>{ const element = getTargetElement(target); if (!element) { return; } observerRef.current = new ResizeObserver(savedCallback.current); observerRef.current.observe(element, options); return stop; }, [ savedCallback, stop, target, options ]); return stop; }; const useElementBounding = (target, options = defaultOptions$1)=>{ const { reset = true, windowResize = true, windowScroll = true, immediate = true } = options; const [height, setHeight] = React.useState(0); const [bottom, setBottom] = React.useState(0); const [left, setLeft] = React.useState(0); const [right, setRight] = React.useState(0); const [top, setTop] = React.useState(0); const [width, setWidth] = React.useState(0); const [x, setX] = React.useState(0); const [y, setY] = React.useState(0); const update = useEvent(()=>{ const element = getTargetElement(target); if (!element) { if (reset) { setHeight(0); setBottom(0); setLeft(0); setRight(0); setTop(0); setWidth(0); setX(0); setY(0); } return; } const rect = element.getBoundingClientRect(); setHeight(rect.height); setBottom(rect.bottom); setLeft(rect.left); setRight(rect.right); setTop(rect.top); setWidth(rect.width); setX(rect.x); setY(rect.y); }); useResizeObserver(target, update); React.useEffect(()=>{ if (immediate) { update(); } }, [ immediate, update ]); React.useEffect(()=>{ if (windowScroll) { window.addEventListener('scroll', update, { passive: true }); } if (windowResize) { window.addEventListener('resize', update, { passive: true }); } return ()=>{ if (windowScroll) { window.removeEventListener('scroll', update); } if (windowResize) { window.removeEventListener('resize', update); } }; }, [ update, windowResize, windowScroll ]); return { height, bottom, left, right, top, width, x, y, update }; }; const useElementSize = (target, options = defaultOptions$1)=>{ const { box = 'content-box' } = options; const [width, setWidth] = React.useState(0); const [height, setHeight] = React.useState(0); useResizeObserver(target, ([entry])=>{ const boxSize = box === 'border-box' ? entry.borderBoxSize : box === 'content-box' ? entry.contentBoxSize : entry.devicePixelContentBoxSize; if (boxSize) { setWidth(boxSize.reduce((acc, { inlineSize })=>acc + inlineSize, 0)); setHeight(boxSize.reduce((acc, { blockSize })=>acc + blockSize, 0)); } else { // fallback setWidth(entry.contentRect.width); setHeight(entry.contentRect.height); } }, options); return [ width, height ]; }; const useIntersectionObserver = (target, callback, options = defaultOptions$1)=>{ const savedCallback = useLatest(callback); const observerRef = React.useRef(); const stop = React.useCallback(()=>{ if (observerRef.current) { observerRef.current.disconnect(); } }, []); useDeepCompareEffect(()=>{ const element = getTargetElement(target); if (!element) { return; } observerRef.current = new IntersectionObserver(savedCallback.current, options); observerRef.current.observe(element); return stop; }, [ options ]); return stop; }; const useElementVisibility = (target, options = defaultOptions$1)=>{ const [visible, setVisible] = React.useState(false); const callback = React.useCallback((entries)=>{ const rect = entries[0].boundingClientRect; setVisible(rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth) && rect.bottom >= 0 && rect.right >= 0); }, []); const stop = useIntersectionObserver(target, callback, options); return [ visible, stop ]; }; function useEventEmitter() { const listeners = React.useRef([]); const _disposed = React.useRef(false); const _event = React.useRef((listener)=>{ listeners.current.push(listener); const disposable = { dispose: ()=>{ if (!_disposed.current) { for(let i = 0; i < listeners.current.length; i++){ if (listeners.current[i] === listener) { listeners.current.splice(i, 1); return; } } } } }; return disposable; }); const fire = (arg1, arg2)=>{ const queue = []; for(let i = 0; i < listeners.current.length; i++){ queue.push(listeners.current[i]); } for(let i = 0; i < queue.length; i++){ queue[i].call(undefined, arg1, arg2); } }; const dispose = ()=>{ if (listeners.current.length !== 0) { listeners.current.length = 0; } _disposed.current = true; }; return [ _event.current, fire, dispose ]; } function useSupported(callback, sync = false) { const [supported, setSupported] = React.useState(false); const effect = sync ? useIsomorphicLayoutEffect : React.useEffect; effect(()=>{ setSupported(Boolean(callback())); }, []); return supported; } function asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _async_to_generator$6(fn) { return function() { var self = this, args = arguments; return new Promise(function(resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } const useEyeDropper = ()=>{ const isSupported = useSupported(()=>typeof window !== 'undefined' && 'EyeDropper' in window, true); const open = React.useCallback(/*#__PURE__*/ _async_to_generator$6(function*(options = {}) { if (!isSupported) { return { sRGBHex: '' }; } const eyeDropper = new window.EyeDropper(); return eyeDropper.open(options); }), [ isSupported ]); return [ isSupported, open ]; }; function useFavicon(href, baseUrl = '', rel = 'icon') { React.useEffect(()=>{ const url = `${baseUrl}${href}`; const element = document.head.querySelectorAll(`link[rel*="${rel}"]`); element.forEach((el)=>el.href = url); if (element.length === 0) { const link = document.createElement('link'); link.rel = rel; link.href = url; document.getElementsByTagName('head')[0].appendChild(link); } }, [ baseUrl, href, rel ]); } function asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _async_to_generator$5(fn) { return function() { var self = this, args = arguments; return new Promise(function(resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _extends$3() { _extends$3 = 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$3.apply(this, arguments); } const DEFAULT_OPTIONS = { multiple: true, accept: '*' }; const useFileDialog = (options = defaultOptions$1)=>{ const [files, setFiles] = React.useState(null); const inputRef = React.useRef(); const fileOpenPromiseRef = React.useRef(null); const resolveFileOpenPromiseRef = React.useRef(); const initFn = React.useCallback(()=>{ if (typeof document === 'undefined') { return undefined; } const input = document.createElement('input'); input.type = 'file'; input.onchange = (event)=>{ const result = event.target; setFiles(result.files); resolveFileOpenPromiseRef.current == null ? void 0 : resolveFileOpenPromiseRef.current.call(resolveFileOpenPromiseRef, result.files); }; return input; }, []); inputRef.current = initFn(); const open = /*#__PURE__*/ _async_to_generator$5(function*(localOptions) { if (!inputRef.current) { return; } const _options = _extends$3({}, DEFAULT_OPTIONS, options, localOptions); inputRef.current.multiple = _options.multiple; inputRef.current.accept = _options.accept; inputRef.current.capture = _options.capture; fileOpenPromiseRef.current = new Promise((resolve)=>{ resolveFileOpenPromiseRef.current = resolve; }); inputRef.current.click(); return fileOpenPromiseRef.current; }); const reset = ()=>{ setFiles(null); resolveFileOpenPromiseRef.current == null ? void 0 : resolveFileOpenPromiseRef.current.call(resolveFileOpenPromiseRef, null); if (inputRef.current) { inputRef.current.value = ''; } }; return [ files, open, reset ]; }; const useFirstMountState = ()=>{ const isFirst = React.useRef(true); if (isFirst.current) { isFirst.current = false; return true; } return isFirst.current; }; const useFocus = (target, initialValue = false)=>{ const [focus, innerSetFocus] = React.useState(initialValue); useEventListener('focus', ()=>innerSetFocus(true), target); useEventListener('blur', ()=>innerSetFocus(false), target); const setFocus = (value)=>{ const element = getTargetElement(target); if (!element) { return; } if (!value) { element.blur(); } else if (value) { element.focus(); } }; useMount(()=>{ setFocus(focus); }); return [ focus, setFocus ]; }; const useRafFn = (callback, initiallyActive = true)=>{ const raf = React.useRef(null); const rafActivity = React.useRef(false); const rafCallback = useLatest(callback); const step = React.useCallback((time)=>{ if (rafActivity.current) { rafCallback.current(time); raf.current = requestAnimationFrame(step); } }, [ rafCallback ]); const result = React.useMemo(()=>[ ()=>{ // stop if (rafActivity.current) { rafActivity.current = false; raf.current && cancelAnimationFrame(raf.current); } }, ()=>{ // start if (!rafActivity.current) { rafActivity.current = true; raf.current = requestAnimationFrame(step); } }, ()=>rafActivity.current ], [ step ]); React.useEffect(()=>{ if (initiallyActive) { result[1](); } return result[0]; }, [ initiallyActive, result ]); return result; }; function useFps(options = defaultOptions$1) { const [fps, setFps] = React.useState(0); var _options_every; const every = (_options_every = options.every) != null ? _options_every : 10; const last = React.useRef(performance.now()); const ticks = React.useRef(0); useRafFn(()=>{ ticks.current += 1; if (ticks.current >= every) { const now = performance.now(); const diff = now - last.current; setFps(Math.round(1000 / (diff / ticks.current))); last.current = now; ticks.current = 0; } }); return fps; } const useFullscreen = (target, options = defaultOptions$1)=>{ const { onExit, onEnter } = options; const [state, setState] = React.useState(false); const onChange = ()=>{ if (screenfull__default.default.isEnabled) { const { isFullscreen } = screenfull__default.default; if (isFullscreen) { onEnter == null ? void 0 : onEnter(); } else { screenfull__default.default.off('change', onChange); onExit == null ? void 0 : onExit(); } setState(isFullscreen); } }; const enterFullscreen = ()=>{ const el = getTargetElement(target); if (!el) { return; } if (screenfull__default.default.isEnabled) { try { screenfull__default.default.request(el); screenfull__default.default.on('change', onChange); } catch (error) { console.error(error); } } }; const exitFullscreen = ()=>{ if (screenfull__default.default.isEnabled) { screenfull__default.default.exit(); } }; const toggleFullscreen = ()=>{ if (state) { exitFullscreen(); } else { enterFullscreen(); } }; useUnmount(()=>{ if (screenfull__default.default.isEnabled) { screenfull__default.default.off('change', onChange); } }); return [ state, { enterFullscreen: useEvent(enterFullscreen), exitFullscreen: useEvent(exitFullscreen), toggleFullscreen: useEvent(toggleFullscreen), isEnabled: screenfull__default.default.isEnabled } ]; }; const initCoord = { accuracy: 0, latitude: Number.POSITIVE_INFINITY, longitude: Number.POSITIVE_INFINITY, altitude: null, altitudeAccuracy: null, heading: null, speed: null }; const useGeolocation = (options = defaultOptions$1)=>{ const { enableHighAccuracy = true, maximumAge = 30000, timeout = 27000 } = options; const isSupported = useSupported(()=>navigator && 'geolocation' in navigator); const [coordinates, setCoordinates] = React.useState(initCoord); const [locatedAt, setLocatedAt] = React.useState(null); const [error, setError] = React.useState(null); const updatePosition = React.useCallback((position)=>{ setCoordinates(position.coords); setLocatedAt(position.timestamp); setError(null); }, []); const updateError = React.useCallback((err)=>{ setCoordinates(initCoord); setLocatedAt(null); setError(err); }, []); React.useEffect(()=>{ if (!isSupported) { return; } navigator.geolocation.getCurrentPosition(updatePosition, updateError); const watchId = navigator.geolocation.watchPosition(updatePosition, updateError, { enableHighAccuracy, maximumAge, timeout }); return ()=>{ if (watchId) { navigator.geolocation.clearWatch(watchId); } }; }, [ enableHighAccuracy, isSupported, maximumAge, timeout, updateError, updatePosition ]); return { coordinates, locatedAt, error, isSupported }; }; const useHover = (target)=>{ const [hovered, setHovered] = React.useState(false); const onMouseEnter = React.useCallback(()=>setHovered(true), []); const onMouseLeave = React.useCallback(()=>setHovered(false), []); useEventListener('mouseenter', onMouseEnter, target); useEventListener('mouseleave', onMouseLeave, target); return hovered; }; const defaultEvents$1 = [ 'mousemove', 'mousedown', 'resize', 'keydown', 'touchstart', 'wheel' ]; const oneMinute = 60e3; const useIdle = (ms = oneMinute, initialState = false, events = defaultEvents$1)=>{ const [state, setState] = React.useState(initialState); React.useEffect(()=>{ let mounted = true; let timeout; let localState = state; const set = (newState)=>{ if (mounted) { localState = newState; setState(newState); } }; const onEvent = lodashEs.throttle(()=>{ if (localState) { set(false); } clearTimeout(timeout); timeout = setTimeout(()=>set(true), ms); }, 50); const onVisibility = ()=>{ if (!document.hidden) { onEvent(); } }; for(let i = 0; i < events.length; i++){ on(window, events[i], onEvent); } on(document, 'visibilitychange', onVisibility); timeout = setTimeout(()=>set(true), ms); return ()=>{ mounted = false; for(let i = 0; i < events.length; i++){ off(window, events[i], onEvent); } off(document, 'visibilitychange', onVisibility); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [ ms, events ]); return state; }; function useThrottleFn(fn, wait, options) { if (isDev) { if (!isFunction(fn)) { console.error(`useThrottleFn expected parameter is a function, got ${typeof fn}`); } } const fnRef = useLatest(fn); const throttled = React.useMemo(()=>lodashEs.throttle((...args)=>{ return fnRef.current(...args); }, wait, options), // eslint-disable-next-line react-hooks/exhaustive-deps [ wait, JSON.stringify(options) ]); useUnmount(()=>{ throttled.cancel(); }); return { run: throttled, cancel: throttled.cancel, flush: throttled.flush }; } /** * We have to check if the scroll amount is close enough to some threshold in order to * more accurately calculate arrivedState. This is because scrollTop/scrollLeft are non-rounded * numbers, while scrollHeight/scrollWidth and clientHeight/clientWidth are rounded. * https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#determine_if_an_element_has_been_totally_scrolled */ const ARRIVED_STATE_THRESHOLD_PIXELS = 1; const defaultListerOptions = { capture: false, passive: true }; const useScroll = (target, options = defaultOptions$1)=>{ const { throttle = 0, idle = 200, onStop = noop, onScroll = noop, offset = { left: 0, right: 0, top: 0, bottom: 0 }, eventListenerOptions = defaultListerOptions } = options; const [x, setX] = React.useState(0); const [y, setY] = React.useState(0); const [isScrolling, setIsScrolling] = React.useState(false); const [arrivedState, setArrivedState] = React.useState({ left: true, right: false, top: true, bottom: false }); const [directions, setDirections] = React.useState({ left: false, right: false, top: false, bottom: false }); const { run: onScrollEnd } = useDebounceFn((e)=>{ setIsScrolling(false); setDirections({ left: false, right: false, top: false, bottom: false }); onStop(e); }, throttle + idle); const onScrollHandler = useEvent((e)=>{ const eventTarget = e.target === document ? e.target.documentElement : e.target; const scrollLeft = eventTarget.scrollLeft; let scrollTop = eventTarget.scrollTop; // patch for mobile compatible if (e.target === document && !scrollTop) scrollTop = document.body.scrollTop; setX(scrollLeft); setY(scrollTop); setDirections({ left: scrollLeft < x, right: scrollLeft > x, top: scrollTop < y, bottom: scrollTop > y }); setArrivedState({ left: scrollLeft <= 0 + (offset.left || 0), right: scrollLeft + eventTarget.clientWidth >= eventTarget.scrollWidth - (offset.right || 0) - ARRIVED_STATE_THRESHOLD_PIXELS, top: scrollTop <= 0 + (offset.top || 0), bottom: scrollTop + eventTarget.clientHeight >= eventTarget.scrollHeight - (offset.bottom || 0) - ARRIVED_STATE_THRESHOLD_PIXELS }); setIsScrolling(true); onScrollEnd(e); onScroll(e); }); const { run: throttleOnScroll } = useThrottleFn(onScrollHandler, throttle); useEventListener('scroll', throttle ? throttleOnScroll : onScrollHandler, target, eventListenerOptions); return [ x, y, isScrolling, arrivedState, directions ]; }; const createUpdateEffect = (hook)=>(effect, deps)=>{ const isFirstMount = useFirstMountState(); hook(()=>{ if (!isFirstMount) { return effect(); } }, deps); }; const useUpdateEffect = createUpdateEffect(React.useEffect); function asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _async_to_generator$4(fn) { return function() { var self = this, args = arguments; return new Promise(function(resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _extends$2() { _extends$2 = 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$2.apply(this, arguments); } const useInfiniteScroll = (target, onLoadMore, options = defaultOptions$1)=>{ const savedLoadMore = useLatest(onLoadMore); var _options_direction; const direction = (_options_direction = options.direction) != null ? _options_direction : 'bottom'; var _options_distance; const state = useScroll(target, _extends$2({}, options, { offset: _extends$2({ [direction]: (_options_distance = options.distance) != null ? _options_distance : 0 }, options.offset) })); const di = state[3][direction]; useUpdateEffect(()=>{ const element = getTargetElement(target); const fn = /*#__PURE__*/ _async_to_generator$4(function*() { var _element_scrollHeight, _element_scrollWidth; const previous = { height: (_element_scrollHeight = element == null ? void 0 : element.scrollHeight) != null ? _element_scrollHeight : 0, width: (_element_scrollWidth = element == null ? void 0 : element.scrollWidth) != null ? _element_scrollWidth : 0 }; yield savedLoadMore.current(state); if (options.preserveScrollPosition && element) { element.scrollTo({ top: element.scrollHeight - previous.height, left: element.scrollWidth - previous.width }); } }); fn(); }, [ di, options.preserveScrollPosition, target ]); }; const defaultEvents = [ 'mousedown', 'mouseup', 'keydown', 'keyup' ]; const useKeyModifier = (modifier, options = defaultOptions$1)=>{ const { events = defaultEvents, initial = false } = options; const [state, setState] = React.useState(initial); useMount(()=>{ events.forEach((listenEvent)=>{ on(document, listenEvent, (evt)=>{ if (typeof evt.getModifierState === 'function') { setState(evt.getModifierState(modifier)); } }); }); return ()=>{ events.forEach((listenerEvent)=>{ off(document, listenerEvent, (evt)=>{ if (typeof evt.getModifierState === 'function') { setState(evt.getModifierState(modifier)); } }); }); }; }); return state; }; function useLocalStorage(key, defaultValue, options = defaultOptions$1) { return useStorage(key, defaultValue, ()=>isBrowser ? localStorage : undefined, options); } function subscribe$1(callback) { window.addEventListener('popstate', callback); window.addEventListener('hashchange', callback); return ()=>{ window.removeEventListener('popstate', callback); window.removeEventListener('hashchange', callback); }; } const useLocationSelector = (selector, /** * @description server fallback * @default undefined */ fallback)=>{ return index_js.useSyncExternalStore(subscribe$1, ()=>selector(location), ()=>fallback); }; function isTouchEvent(ev) { return 'touches' in ev; } function preventDefault$1(ev) { if (!isTouchEvent(ev)) { return; } if (ev.touches.length < 2 && ev.preventDefault) { ev.preventDefault(); } } const useLongPress = (callback, { isPreventDefault = true, delay = 300 } = defaultOptions$1)=>{ const timeout = React.useRef(); const target = React.useRef(); const start = React.useCallback((event)=>{ // prevent ghost click on mobile devices if (isPreventDefault && event.target) { on(event.target, 'touchend', preventDefault$1, { passive: false }); target.current = event.target; } timeout.current = setTimeout(()=>callback(event), delay); }, [ callback, delay, isPreventDefault ]); const clear = React.useCallback(()=>{ // clearTimeout and removeEventListener timeout.current && clearTimeout(timeout.current); if (isPreventDefault && target.current) { off(target.current, 'touchend', preventDefault$1); } }, [ isPreventDefault ]); return { onMouseDown: (e)=>start(e), onTouchStart: (e)=>start(e), onMouseUp: clear, onMouseLeave: clear, onTouchEnd: clear }; }; const defaultState$1 = { x: 0, y: 0, width: 0, height: 0, top: 0, left: 0, bottom: 0, right: 0 }; const useMeasure = (target, options = defaultOptions$1)=>{ const [rect, setRect] = React.useState(defaultState$1); const stop = useResizeObserver(target, (entries)=>{ if (entries[0]) { const { x, y, width, height, top, left, bottom, right } = entries[0].contentRect; setRect({ x, y, width, height, top, left, bottom, right }); } }, options); return [ rect, stop ]; }; function asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _async_to_generator$3(fn) { return function() { var self = this, args = arguments; return new Promise(function(resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } const defaultConstints = { audio: true, video: true }; const useMediaDevices = (options = {})=>{ const { requestPermissions, constraints = defaultConstints } = options; const [state, setState] = React.useState({ devices: [] }); const isSupported = useSupported(()=>navigator && navigator.mediaDevices && navigator.mediaDevices.enumerateDevices); const permissionGranted = React.useRef(false); const stream = React.useRef(null); const onChange = React.useCallback(()=>{ navigator.mediaDevices.enumerateDevices().then((devices)=>{ if (stream.current) { stream.current.getTracks().forEach((t)=>t.stop()); stream.current = null; } setState({ devices: devices.map(({ deviceId, groupId, kind, label })=>({ deviceId, groupId, kind, label })) }); }).catch(noop); }, []); const ensurePermissions = React.useCallback(/*#__PURE__*/ _async_to_generator$3(function*() { if (!isSupported) { return false; } if (permissionGranted.current) { return true; } let state; try { state = (yield navigator.permissions.query({ name: 'camera' })).state; } catch (error) { state = 'prompt'; } if (state !== 'granted') { stream.current = yield navigator.mediaDevices.getUserMedia(constraints); onChange(); permissionGranted.current = true; } else { permissionGranted.current = false; } return permissionGranted.current; }), [ onChange, isSupported, constraints ]); React.useEffect(()=>{ if (!isSupported) { return; } if (requestPermissions) { ensurePermissions(); } on(navigator.mediaDevices, 'devicechange', onChange); onChange(); return ()=>{ off(navigator.mediaDevices, 'devicechange', onChange); }; }, [ onChange, isSupported, requestPermissions, ensurePermissions ]); return [ state, ensurePermissions ]; }; function getInitialState$1(query, defaultState) { // Prevent a React hydration mismatch when a default value is provided by not defaulting to window.matchMedia(query).matches. if (defaultState !== undefined) { return defaultState; } if (isBrowser) { return window.matchMedia(query).matches; } // A default value has not been provided, and you are rendering on the server, warn of a possible hydration mismatch when defaulting to false. if (process.env.NODE_ENV !== 'production') { console.warn('`useMediaQuery` When server side rendering, defaultState should be defined to prevent a hydration mismatches.'); } return false; } const useMediaQuery = (query, defaultState)=>{ const [state, setState] = React.useState(getInitialState$1(query, defaultState)); React.useEffect(()=>{ let mounted = true; const mql = window.matchMedia(query); const onChange = ()=>{ if (!mounted) { return; } setState(!!mql.matches); }; if ('addEventListener' in mql) { mql.addEventListener('change', onChange); } else { mql.addListener == null ? void 0 : mql.addListener.call(mql, onChange); } setState(mql.matches); return ()=>{ mounted = false; if ('removeEventListener' in mql) { mql.removeEventListener('change', onChange); } else { mql.removeListener == null ? void 0 : mql.removeListener.call(mql, onChange); } }; }, [ query ]); return state; }; function useRafState(initialState) { const frame = React.useRef(0); const [state, setState] = React.useState(initialState); const setRafState = React.useCallback((value)=>{ cancelAnimationFrame(frame.current); frame.current = requestAnimationFrame(()=>{ setState(value); }); }, []); useUnmount(()=>{ cancelAnimationFrame(frame.current); }); return [ state, setRafState ]; } const initState = { screenX: Number.NaN, screenY: Number.NaN, clientX: Number.NaN, clientY: Number.NaN, pageX: Number.NaN, pageY: Number.NaN, elementX: Number.NaN, elementY: Number.NaN, elementH: Number.NaN, elementW: Number.NaN, elementPosX: Number.NaN, elementPosY: Number.NaN }; const useMouse = (target)=>{ const [state, setState] = useRafState(initState); useEventListener('mousemove', (event)=>{ const { screenX, screenY, clientX, clientY, pageX, pageY } = event; const newState = { screenX, screenY, clientX, clientY, pageX, pageY, elementX: Number.NaN, elementY: Number.NaN, elementH: Number.NaN, elementW: Number.NaN, elementPosX: Number.NaN, elementPosY: Number.NaN }; const targetElement = getTargetElement(target); if (targetElement) { const { left, top, width, height } = targetElement.getBoundingClientRect(); newState.elementPosX = left + window.pageXOffset; newState.elementPosY = top + window.pageYOffset; newState.elementX = pageX - newState.elementPosX; newState.elementY = pageY - newState.elementPosY; newState.elementW = width; newState.elementH = height; } setState(newState); }, ()=>document); return state; }; const listenerOptions$2 = { passive: true }; const useMousePressed = (target, options = defaultOptions$1)=>{ const { touch = true, drag = true, initialValue = false } = options; const [pressed, setPressed] = React.useState(initialValue); const [sourceType, setSourceType] = React.useState(null); const element = getTargetElement(target); const onPressed = React.useCallback((srcType)=>()=>{ setPressed(true); setSourceType(srcType); }, []); const onReleased = React.useCallback(()=>{ setPressed(false); setSourceType(null); }, []); useEventListener('mousedown', onPressed('mouse'), target, listenerOptions$2); useEventListener('mouseleave', onReleased, ()=>window, listenerOptions$2); useEventListener('mouseup', onReleased, ()=>window, listenerOptions$2); React.useEffect(()=>{ if (drag) { element == null ? void 0 : element.addEventListener('dragstart', onPressed('mouse'), listenerOptions$2); element == null ? void 0 : element.addEventListener('drop', onReleased, listenerOptions$2); element == null ? void 0 : element.addEventListener('dragend', onReleased, listenerOptions$2); } if (touch) { element == null ? void 0 : element.addEventListener('touchstart', onPressed('touch'), listenerOptions$2); element == null ? void 0 : element.addEventListener('touchend', onReleased, listenerOptions$2); element == null ? void 0 : element.addEventListener('touchcancel', onReleased, listenerOptions$2); } return ()=>{ if (drag) { element == null ? void 0 : element.removeEventListener('dragstart', onPressed('mouse')); element == null ? void 0 : element.removeEventListener('drop', onReleased); element == null ? void 0 : element.removeEventListener('dragend', onReleased); } if (touch) { element == null ? void 0 : element.removeEventListener('touchstart', onPressed('touch')); element == null ? void 0 : element.removeEventListener('touchend', onReleased); element == null ? void 0 : element.removeEventListener('touchcancel', onReleased); } }; }, [ drag, onPressed, onReleased, touch, element ]); return [ pressed, sourceType ]; }; const useMutationObserver = (callback, target, options = defaultOptions$1)=>{ const callbackRef = useLatest(callback); const observerRef = React.useRef(); const stop = React.useCallback(()=>{ if (observerRef.current) { observerRef.current.disconnect(); } }, []); useDeepCompareEffect(()=>{ const element = getTargetElement(target); if (!element) { return; } observerRef.current = new MutationObserver(callbackRef.current); observerRef.current.observe(element, options); return stop; }, [ options ]); return stop; }; const nav = isNavigator ? navigator : undefined; const conn = nav && (nav.connection || nav.mozConnection || nav.webkitConnection); function getConnectionState(previousState) { const online = nav == null ? void 0 : nav.onLine; const previousOnline = previousState == null ? void 0 : previousState.online; return { online, previous: previousOnline, since: online !== previousOnline ? new Date() : previousState == null ? void 0 : previousState.since, downlink: conn == null ? void 0 : conn.downlink, downlinkMax: conn == null ? void 0 : conn.downlinkMax, effectiveType: conn == null ? void 0 : conn.effectiveType, rtt: conn == null ? void 0 : conn.rtt, saveData: conn == null ? void 0 : conn.saveData, type: conn == null ? void 0 : conn.type }; } const useNetwork = ()=>{ const [state, setState] = React.useState(getConnectionState); React.useEffect(()=>{ const handleStateChange = ()=>{ setState(getConnectionState); }; on(window, 'online', handleStateChange, { passive: true }); on(window, 'offline', handleStateChange, { passive: true }); if (conn) { on(conn, 'change', handleStateChange, { passive: true }); } return ()=>{ off(window, 'online', handleStateChange); off(window, 'offline', handleStateChange); if (conn) { off(conn, 'change', handleStateChange); } }; }, []); return state; }; const useObjectUrl = (object)=>{ const [url, setUrl] = React.useState(); React.useEffect(()=>{ if (object) { setUrl(URL.createObjectURL(object)); } return ()=>{ if (url) { URL.revokeObjectURL(url); } }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [ object ]); return url; }; const record = new WeakSet(); const createOnceEffect = (hook)=>(effect, deps)=>{ const onceWrapper = ()=>{ const shouldStart = !record.has(effect); if (shouldStart) { record.add(effect); return effect(); } }; hook(()=>{ return onceWrapper(); }, deps); }; const useOnceEffect = createOnceEffect(React.useEffect); const useOnceLayoutEffect = createOnceEffect(React.useLayoutEffect); const useOnline = ()=>{ const { online } = useNetwork(); return online; }; const defaultState = { angle: 0, type: 'landscape-primary' }; const useOrientation = (initialState = defaultState)=>{ const [state, setState] = React.useState(initialState); React.useEffect(()=>{ const screen = window.screen; let mounted = true; const onChange = ()=>{ if (mounted) { const { orientation } = screen; if (orientation) { const { angle, type } = orientation; setState({ angle, type }); } else if (window.orientation !== undefined) { setState({ angle: typeof window.orientation === 'number' ? window.orientation : 0, type: void 0 }); } } }; on(window, 'orientationchange', onChange); onChange(); return ()=>{ mounted = false; off(window, 'orientationchange', onChange); }; }, []); const lockOrientation = (type)=>{ if (isBrowser) { return; } if (!(window && 'screen' in window && 'orientation' in window.screen)) { return Promise.reject(new Error('Not supported')); } return window.screen.orientation.lock(type); }; const unlockOrientation = ()=>{ if (isBrowser) { return; } if (!(window && 'screen' in window && 'orientation' in window.screen)) { return; } return window.screen.orientation.unlock(); }; return [ state, lockOrientation, unlockOrientation ]; }; function usePageLeave() { const [isLeft, setIsLeft] = React.useState(false); const handler = (event)=>{ if (!window) return; event = event || window.event; // @ts-expect-error missing types const from = event.relatedTarget || event.toElement; setIsLeft(!from); }; useEventListener('mouseout', handler, ()=>window, { passive: true }); useEventListener('mouseleave', handler, ()=>document, { passive: true }); useEventListener('mouseenter', handler, ()=>document, { passive: true }); return isLeft; } const usePermission = (permissionDesc)=>{ const [state, setState] = React.useState(''); React.useEffect(()=>{ var _navigator_permissions; const desc = typeof permissionDesc === 'string' ? { name: permissionDesc } : permissionDesc; let mounted = true; let permissionStatus = null; const onChange = ()=>{ if (!mounted) { return; } setState(()=>{ var _permissionStatus_state; return (_permissionStatus_state = permissionStatus == null ? void 0 : permissionStatus.state) != null ? _permissionStatus_state : ''; }); }; (_navigator_permissions = navigator.permissions) == null ? void 0 : _navigator_permissions.query(desc).then((status)=>{ permissionStatus = status; on(permissionStatus, 'change', onChange); onChange(); }).catch(noop); return ()=>{ permissionStatus && off(permissionStatus, 'change', onChange); mounted = false; permissionStatus = null; }; }, [ permissionDesc ]); return state; }; const usePreferredColorScheme = (defaultState = 'no-preference')=>{ const isLight = useMediaQuery('(prefers-color-scheme: light)', false); const isDark = useMediaQuery('(prefers-color-scheme: dark)', false); return isDark ? 'dark' : isLight ? 'light' : defaultState; }; const usePreferredContrast = (defaultState = 'no-preference')=>{ const isMore = useMediaQuery('(prefexrs-contrast: more)', false); const isLess = useMediaQuery('(prefers-contrast: less)', false); const isCustom = useMediaQuery('(prefers-contrast: custom)', false); return isMore ? 'more' : isLess ? 'less' : isCustom ? 'custom' : defaultState; }; function usePreferredDark(defaultState) { return useMediaQuery('(prefers-color-scheme: dark)', defaultState); } function usePrevious(state) { const ref = React.useRef(); React.useEffect(()=>{ ref.current = state; }); return ref.current; } function useReducedMotion(defaultState) { return useMediaQuery('(prefers-reduced-motion: reduce)', defaultState); } const updateReducer = (num)=>(num + 1) % 1000000; function useUpdate() { const [, update] = React.useReducer(updateReducer, 0); return update; } const topVarName = '--reactuse-safe-area-top'; const rightVarName = '--reactuse-safe-area-right'; const bottomVarName = '--reactuse-safe-area-bottom'; const leftVarName = '--reactuse-safe-area-left'; const defaultElement = ()=>document.documentElement; function useScreenSafeArea() { const top = React.useRef(''); const right = React.useRef(''); const bottom = React.useRef(''); const left = React.useRef(''); const forceUpdate = useUpdate(); useCssVar(topVarName, defaultElement, 'env(safe-area-inset-top, 0px)'); useCssVar(rightVarName, defaultElement, 'env(safe-area-inset-right, 0px)'); useCssVar(bottomVarName, defaultElement, 'env(safe-area-inset-bottom, 0px)'); useCssVar(leftVarName, defaultElement, 'env(safe-area-inset-left, 0px)'); const { run: update } = useDebounceFn(()=>{ top.current = getValue(topVarName); right.current = getValue(rightVarName); bottom.current = getValue(bottomVarName); left.current = getValue(leftVarName); forceUpdate(); }); React.useEffect(()=>{ update(); }, [ update ]); useEventListener('resize', update); return [ top.current, right.current, bottom.current, left.current, update ]; } function getValue(position) { return getComputedStyle(document.documentElement).getPropertyValue(position); } const useScriptTag = (src, onLoaded = noop, options = defaultOptions$1)=>{ const { immediate = true, manual = false, type = 'text/javascript', async = true, crossOrigin, referrerPolicy, noModule, defer, attrs = {} } = options; const scriptTag = React.useRef(null); const _promise = React.useRef(null); const [status, setStatus] = React.useState(src ? 'loading' : 'idle'); /** * Load the script specified via `src`. * * @param waitForScriptLoad Whether if the Promise should resolve once the "load" event is emitted by the