UNPKG

@reactive-vscode/vueuse

Version:

Useful VueUse utilities for VSCode extension development

1,528 lines 100 kB
import { customRef, toValue, shallowRef, watchEffect, readonly, watch, effectScope, unref, computed, ref, shallowReadonly, isRef, getCurrentScope, hasInjectionContext, inject, provide, toRefs as toRefs$1, reactive, toRef as toRef$1, onBeforeMount, nextTick, onBeforeUnmount, onScopeDispose, onUnmounted, isReactive, isReadonly, markRaw } from "@reactive-vscode/reactivity"; function getCurrentInstance() { return null; } function computedEager(fn, options) { var _options$flush; const result = shallowRef(); watchEffect(() => { result.value = fn(); }, { ...options, flush: (_options$flush = options === null || options === void 0 ? void 0 : options.flush) !== null && _options$flush !== void 0 ? _options$flush : "sync" }); return readonly(result); } const eagerComputed = computedEager; function computedWithControl(source, fn, options = {}) { let v = void 0; let track; let trigger; let dirty = true; const update = () => { dirty = true; trigger(); }; watch(source, update, { flush: "sync", ...options }); const get$1 = typeof fn === "function" ? fn : fn.get; const set$1 = typeof fn === "function" ? void 0 : fn.set; const result = customRef((_track, _trigger) => { track = _track; trigger = _trigger; return { get() { if (dirty) { v = get$1(v); dirty = false; } track(); return v; }, set(v$1) { set$1 === null || set$1 === void 0 || set$1(v$1); } }; }); result.trigger = update; return result; } const controlledComputed = computedWithControl; function tryOnScopeDispose(fn, failSilently) { if (getCurrentScope()) { onScopeDispose(fn, failSilently); return true; } return false; } // @__NO_SIDE_EFFECTS__ function createEventHook() { const fns = /* @__PURE__ */ new Set(); const off = (fn) => { fns.delete(fn); }; const clear = () => { fns.clear(); }; const on = (fn) => { fns.add(fn); const offFn = () => off(fn); tryOnScopeDispose(offFn); return { off: offFn }; }; const trigger = (...args) => { return Promise.all(Array.from(fns).map((fn) => fn(...args))); }; return { on, off, trigger, clear }; } // @__NO_SIDE_EFFECTS__ function createGlobalState(stateFactory) { let initialized = false; let state; const scope = effectScope(true); return ((...args) => { if (!initialized) { state = scope.run(() => stateFactory(...args)); initialized = true; } return state; }); } const localProvidedStateMap = /* @__PURE__ */ new WeakMap(); const injectLocal = /* @__NO_SIDE_EFFECTS__ */ (...args) => { var _getCurrentInstance; const key = args[0]; const instance = (_getCurrentInstance = getCurrentInstance()) === null || _getCurrentInstance === void 0 ? void 0 : _getCurrentInstance.proxy; const owner = instance !== null && instance !== void 0 ? instance : getCurrentScope(); if (owner == null && !hasInjectionContext()) throw new Error("injectLocal must be called in setup"); if (owner && localProvidedStateMap.has(owner) && key in localProvidedStateMap.get(owner)) return localProvidedStateMap.get(owner)[key]; return inject(...args); }; function provideLocal(key, value) { var _getCurrentInstance; const instance = (_getCurrentInstance = getCurrentInstance()) === null || _getCurrentInstance === void 0 ? void 0 : _getCurrentInstance.proxy; const owner = instance !== null && instance !== void 0 ? instance : getCurrentScope(); if (owner == null) throw new Error("provideLocal must be called in setup"); if (!localProvidedStateMap.has(owner)) localProvidedStateMap.set(owner, /* @__PURE__ */ Object.create(null)); const localProvidedState = localProvidedStateMap.get(owner); localProvidedState[key] = value; return provide(key, value); } // @__NO_SIDE_EFFECTS__ function createInjectionState(composable, options) { const key = (options === null || options === void 0 ? void 0 : options.injectionKey) || Symbol(composable.name || "InjectionState"); const defaultValue = options === null || options === void 0 ? void 0 : options.defaultValue; const useProvidingState = (...args) => { const state = composable(...args); provideLocal(key, state); return state; }; const useInjectedState = () => /* @__PURE__ */ injectLocal(key, defaultValue); return [useProvidingState, useInjectedState]; } // @__NO_SIDE_EFFECTS__ function createRef(value, deep) { if (deep === true) return ref(value); else return shallowRef(value); } const isClient = typeof window !== "undefined" && typeof document !== "undefined"; const isWorker = typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope; const isDef = (val) => typeof val !== "undefined"; const notNullish = (val) => val != null; const assert = (condition, ...infos) => { if (!condition) console.warn(...infos); }; const toString = Object.prototype.toString; const isObject = (val) => toString.call(val) === "[object Object]"; const now = () => Date.now(); const timestamp = () => +Date.now(); const clamp = (n, min, max) => Math.min(max, Math.max(min, n)); const noop = () => { }; const rand = (min, max) => { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; }; const hasOwn = (val, key) => Object.prototype.hasOwnProperty.call(val, key); function toRef(...args) { if (args.length !== 1) return toRef$1(...args); const r = args[0]; return typeof r === "function" ? readonly(customRef(() => ({ get: r, set: noop }))) : ref(r); } function createFilterWrapper(filter, fn) { function wrapper(...args) { return new Promise((resolve, reject) => { Promise.resolve(filter(() => fn.apply(this, args), { fn, thisArg: this, args })).then(resolve).catch(reject); }); } return wrapper; } const bypassFilter = (invoke$1) => { return invoke$1(); }; function debounceFilter(ms, options = {}) { let timer; let maxTimer; let lastRejector = noop; const _clearTimeout = (timer$1) => { clearTimeout(timer$1); lastRejector(); lastRejector = noop; }; let lastInvoker; const filter = (invoke$1) => { const duration = toValue(ms); const maxDuration = toValue(options.maxWait); if (timer) _clearTimeout(timer); if (duration <= 0 || maxDuration !== void 0 && maxDuration <= 0) { if (maxTimer) { _clearTimeout(maxTimer); maxTimer = void 0; } return Promise.resolve(invoke$1()); } return new Promise((resolve, reject) => { lastRejector = options.rejectOnCancel ? reject : resolve; lastInvoker = invoke$1; if (maxDuration && !maxTimer) maxTimer = setTimeout(() => { if (timer) _clearTimeout(timer); maxTimer = void 0; resolve(lastInvoker()); }, maxDuration); timer = setTimeout(() => { if (maxTimer) _clearTimeout(maxTimer); maxTimer = void 0; resolve(invoke$1()); }, duration); }); }; return filter; } function throttleFilter(...args) { let lastExec = 0; let timer; let isLeading = true; let lastRejector = noop; let lastValue; let ms; let trailing; let leading; let rejectOnCancel; if (!isRef(args[0]) && typeof args[0] === "object") ({ delay: ms, trailing = true, leading = true, rejectOnCancel = false } = args[0]); else [ms, trailing = true, leading = true, rejectOnCancel = false] = args; const clear = () => { if (timer) { clearTimeout(timer); timer = void 0; lastRejector(); lastRejector = noop; } }; const filter = (_invoke) => { const duration = toValue(ms); const elapsed = Date.now() - lastExec; const invoke$1 = () => { return lastValue = _invoke(); }; clear(); if (duration <= 0) { lastExec = Date.now(); return invoke$1(); } if (elapsed > duration) { lastExec = Date.now(); if (leading || !isLeading) invoke$1(); } else if (trailing) lastValue = new Promise((resolve, reject) => { lastRejector = rejectOnCancel ? reject : resolve; timer = setTimeout(() => { lastExec = Date.now(); isLeading = true; resolve(invoke$1()); clear(); }, Math.max(0, duration - elapsed)); }); if (!leading && !timer) timer = setTimeout(() => isLeading = true, duration); isLeading = false; return lastValue; }; return filter; } function pausableFilter(extendFilter = bypassFilter, options = {}) { const { initialState = "active" } = options; const isActive = toRef(initialState === "active"); function pause() { isActive.value = false; } function resume() { isActive.value = true; } const eventFilter = (...args) => { if (isActive.value) extendFilter(...args); }; return { isActive: readonly(isActive), pause, resume, eventFilter }; } function promiseTimeout(ms, throwOnTimeout = false, reason = "Timeout") { return new Promise((resolve, reject) => { if (throwOnTimeout) setTimeout(() => reject(reason), ms); else setTimeout(resolve, ms); }); } function identity(arg) { return arg; } function createSingletonPromise(fn) { let _promise; function wrapper() { if (!_promise) _promise = fn(); return _promise; } wrapper.reset = async () => { const _prev = _promise; _promise = void 0; if (_prev) await _prev; }; return wrapper; } function invoke(fn) { return fn(); } function containsProp(obj, ...props) { return props.some((k) => k in obj); } function increaseWithUnit(target, delta) { var _target$match; if (typeof target === "number") return target + delta; const value = ((_target$match = target.match(/^-?\d+\.?\d*/)) === null || _target$match === void 0 ? void 0 : _target$match[0]) || ""; const unit = target.slice(value.length); const result = Number.parseFloat(value) + delta; if (Number.isNaN(result)) return target; return result + unit; } function pxValue(px) { return px.endsWith("rem") ? Number.parseFloat(px) * 16 : Number.parseFloat(px); } function objectPick(obj, keys, omitUndefined = false) { return keys.reduce((n, k) => { if (k in obj) { if (!omitUndefined || obj[k] !== void 0) n[k] = obj[k]; } return n; }, {}); } function objectOmit(obj, keys, omitUndefined = false) { return Object.fromEntries(Object.entries(obj).filter(([key, value]) => { return (!omitUndefined || value !== void 0) && !keys.includes(key); })); } function objectEntries(obj) { return Object.entries(obj); } function toArray(value) { return Array.isArray(value) ? value : [value]; } function cacheStringFunction(fn) { const cache = /* @__PURE__ */ Object.create(null); return ((str) => { return cache[str] || (cache[str] = fn(str)); }); } const hyphenateRE = /\B([A-Z])/g; const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, "-$1").toLowerCase()); const camelizeRE = /-(\w)/g; const camelize = cacheStringFunction((str) => { return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ""); }); function getLifeCycleTarget(target) { return target || getCurrentInstance(); } // @__NO_SIDE_EFFECTS__ function createSharedComposable(composable) { if (!isClient) return composable; let subscribers = 0; let state; let scope; const dispose = () => { subscribers -= 1; if (scope && subscribers <= 0) { scope.stop(); state = void 0; scope = void 0; } }; return ((...args) => { subscribers += 1; if (!scope) { scope = effectScope(true); state = scope.run(() => composable(...args)); } tryOnScopeDispose(dispose); return state; }); } function extendRef(ref$1, extend, { enumerable = false, unwrap = true } = {}) { for (const [key, value] of Object.entries(extend)) { if (key === "value") continue; if (isRef(value) && unwrap) Object.defineProperty(ref$1, key, { get() { return value.value; }, set(v) { value.value = v; }, enumerable }); else Object.defineProperty(ref$1, key, { value, enumerable }); } return ref$1; } function get(obj, key) { if (key == null) return unref(obj); return unref(obj)[key]; } function isDefined(v) { return unref(v) != null; } // @__NO_SIDE_EFFECTS__ function makeDestructurable(obj, arr) { if (typeof Symbol !== "undefined") { const clone = { ...obj }; Object.defineProperty(clone, Symbol.iterator, { enumerable: false, value() { let index = 0; return { next: () => ({ value: arr[index++], done: index > arr.length }) }; } }); return clone; } else return Object.assign([...arr], obj); } // @__NO_SIDE_EFFECTS__ function reactify(fn, options) { const unrefFn = (options === null || options === void 0 ? void 0 : options.computedGetter) === false ? unref : toValue; return function(...args) { return computed(() => fn.apply(this, args.map((i) => unrefFn(i)))); }; } const createReactiveFn = reactify; // @__NO_SIDE_EFFECTS__ function reactifyObject(obj, optionsOrKeys = {}) { let keys = []; let options; if (Array.isArray(optionsOrKeys)) keys = optionsOrKeys; else { options = optionsOrKeys; const { includeOwnProperties = true } = optionsOrKeys; keys.push(...Object.keys(obj)); if (includeOwnProperties) keys.push(...Object.getOwnPropertyNames(obj)); } return Object.fromEntries(keys.map((key) => { const value = obj[key]; return [key, typeof value === "function" ? /* @__PURE__ */ reactify(value.bind(obj), options) : value]; })); } function toReactive(objectRef) { if (!isRef(objectRef)) return reactive(objectRef); return reactive(new Proxy({}, { get(_, p, receiver) { return unref(Reflect.get(objectRef.value, p, receiver)); }, set(_, p, value) { if (isRef(objectRef.value[p]) && !isRef(value)) objectRef.value[p].value = value; else objectRef.value[p] = value; return true; }, deleteProperty(_, p) { return Reflect.deleteProperty(objectRef.value, p); }, has(_, p) { return Reflect.has(objectRef.value, p); }, ownKeys() { return Object.keys(objectRef.value); }, getOwnPropertyDescriptor() { return { enumerable: true, configurable: true }; } })); } function reactiveComputed(fn) { return toReactive(computed(fn)); } function reactiveOmit(obj, ...keys) { const flatKeys = keys.flat(); const predicate = flatKeys[0]; return reactiveComputed(() => typeof predicate === "function" ? Object.fromEntries(Object.entries(toRefs$1(obj)).filter(([k, v]) => !predicate(toValue(v), k))) : Object.fromEntries(Object.entries(toRefs$1(obj)).filter((e) => !flatKeys.includes(e[0])))); } function reactivePick(obj, ...keys) { const flatKeys = keys.flat(); const predicate = flatKeys[0]; return reactiveComputed(() => typeof predicate === "function" ? Object.fromEntries(Object.entries(toRefs$1(obj)).filter(([k, v]) => predicate(toValue(v), k))) : Object.fromEntries(flatKeys.map((k) => [k, toRef(obj, k)]))); } function refAutoReset(defaultValue, afterMs = 1e4) { return customRef((track, trigger) => { let value = toValue(defaultValue); let timer; const resetAfter = () => setTimeout(() => { value = toValue(defaultValue); trigger(); }, toValue(afterMs)); tryOnScopeDispose(() => { clearTimeout(timer); }); return { get() { track(); return value; }, set(newValue) { value = newValue; trigger(); clearTimeout(timer); timer = resetAfter(); } }; }); } const autoResetRef = refAutoReset; // @__NO_SIDE_EFFECTS__ function useDebounceFn(fn, ms = 200, options = {}) { return createFilterWrapper(debounceFilter(ms, options), fn); } function refDebounced(value, ms = 200, options = {}) { const debounced = ref(toValue(value)); const updater = /* @__PURE__ */ useDebounceFn(() => { debounced.value = value.value; }, ms, options); watch(value, () => updater()); return shallowReadonly(debounced); } const debouncedRef = refDebounced; const useDebounce = refDebounced; // @__NO_SIDE_EFFECTS__ function refDefault(source, defaultValue) { return computed({ get() { var _source$value; return (_source$value = source.value) !== null && _source$value !== void 0 ? _source$value : defaultValue; }, set(value) { source.value = value; } }); } function refManualReset(defaultValue) { let value = toValue(defaultValue); let trigger; const reset = () => { value = toValue(defaultValue); trigger(); }; const refValue = customRef((track, _trigger) => { trigger = _trigger; return { get() { track(); return value; }, set(newValue) { value = newValue; trigger(); } }; }); refValue.reset = reset; return refValue; } // @__NO_SIDE_EFFECTS__ function useThrottleFn(fn, ms = 200, trailing = false, leading = true, rejectOnCancel = false) { return createFilterWrapper(throttleFilter(ms, trailing, leading, rejectOnCancel), fn); } function refThrottled(value, delay = 200, trailing = true, leading = true) { if (delay <= 0) return value; const throttled = ref(toValue(value)); const updater = /* @__PURE__ */ useThrottleFn(() => { throttled.value = value.value; }, delay, trailing, leading); watch(value, () => updater()); return throttled; } const throttledRef = refThrottled; const useThrottle = refThrottled; // @__NO_SIDE_EFFECTS__ function refWithControl(initial, options = {}) { let source = initial; let track; let trigger; const ref$1 = customRef((_track, _trigger) => { track = _track; trigger = _trigger; return { get() { return get$1(); }, set(v) { set$1(v); } }; }); function get$1(tracking = true) { if (tracking) track(); return source; } function set$1(value, triggering = true) { var _options$onBeforeChan, _options$onChanged; if (value === source) return; const old = source; if (((_options$onBeforeChan = options.onBeforeChange) === null || _options$onBeforeChan === void 0 ? void 0 : _options$onBeforeChan.call(options, value, old)) === false) return; source = value; (_options$onChanged = options.onChanged) === null || _options$onChanged === void 0 || _options$onChanged.call(options, value, old); if (triggering) trigger(); } const untrackedGet = () => get$1(false); const silentSet = (v) => set$1(v, false); const peek = () => get$1(false); const lay = (v) => set$1(v, false); return extendRef(ref$1, { get: get$1, set: set$1, untrackedGet, silentSet, peek, lay }, { enumerable: true }); } const controlledRef = refWithControl; function set(...args) { if (args.length === 2) { const [ref$1, value] = args; ref$1.value = value; } if (args.length === 3) { const [target, key, value] = args; target[key] = value; } } function watchWithFilter(source, cb, options = {}) { const { eventFilter = bypassFilter, ...watchOptions } = options; return watch(source, createFilterWrapper(eventFilter, cb), watchOptions); } function watchPausable(source, cb, options = {}) { const { eventFilter: filter, initialState = "active", ...watchOptions } = options; const { eventFilter, pause, resume, isActive } = pausableFilter(filter, { initialState }); return { stop: watchWithFilter(source, cb, { ...watchOptions, eventFilter }), pause, resume, isActive }; } const pausableWatch = watchPausable; function syncRef(left, right, ...[options]) { const { flush = "sync", deep = false, immediate = true, direction = "both", transform = {} } = options || {}; const watchers = []; const transformLTR = "ltr" in transform && transform.ltr || ((v) => v); const transformRTL = "rtl" in transform && transform.rtl || ((v) => v); if (direction === "both" || direction === "ltr") watchers.push(pausableWatch(left, (newValue) => { watchers.forEach((w) => w.pause()); right.value = transformLTR(newValue); watchers.forEach((w) => w.resume()); }, { flush, deep, immediate })); if (direction === "both" || direction === "rtl") watchers.push(pausableWatch(right, (newValue) => { watchers.forEach((w) => w.pause()); left.value = transformRTL(newValue); watchers.forEach((w) => w.resume()); }, { flush, deep, immediate })); const stop = () => { watchers.forEach((w) => w.stop()); }; return stop; } function syncRefs(source, targets, options = {}) { const { flush = "sync", deep = false, immediate = true } = options; const targetsArray = toArray(targets); return watch(source, (newValue) => targetsArray.forEach((target) => target.value = newValue), { flush, deep, immediate }); } function toRefs(objectRef, options = {}) { if (!isRef(objectRef)) return toRefs$1(objectRef); const result = Array.isArray(objectRef.value) ? Array.from({ length: objectRef.value.length }) : {}; for (const key in objectRef.value) result[key] = customRef(() => ({ get() { return objectRef.value[key]; }, set(v) { var _toValue; if ((_toValue = toValue(options.replaceRef)) !== null && _toValue !== void 0 ? _toValue : true) if (Array.isArray(objectRef.value)) { const copy = [...objectRef.value]; copy[key] = v; objectRef.value = copy; } else { const newObject = { ...objectRef.value, [key]: v }; Object.setPrototypeOf(newObject, Object.getPrototypeOf(objectRef.value)); objectRef.value = newObject; } else objectRef.value[key] = v; } })); return result; } function tryOnBeforeMount(fn, sync = true, target) { if (getLifeCycleTarget(target)) onBeforeMount(fn, target); else if (sync) fn(); else nextTick(fn); } function tryOnBeforeUnmount(fn, target) { if (getLifeCycleTarget(target)) onBeforeUnmount(fn, target); } function tryOnMounted(fn, sync = true, target) { if (getLifeCycleTarget(target)) ; else if (sync) fn(); else nextTick(fn); } function tryOnUnmounted(fn, target) { if (getLifeCycleTarget(target)) onUnmounted(fn, target); } function createUntil(r, isNot = false) { function toMatch(condition, { flush = "sync", deep = false, timeout, throwOnTimeout } = {}) { let stop = null; const promises = [new Promise((resolve) => { stop = watch(r, (v) => { if (condition(v) !== isNot) { if (stop) stop(); else nextTick(() => stop === null || stop === void 0 ? void 0 : stop()); resolve(v); } }, { flush, deep, immediate: true }); })]; if (timeout != null) promises.push(promiseTimeout(timeout, throwOnTimeout).then(() => toValue(r)).finally(() => stop === null || stop === void 0 ? void 0 : stop())); return Promise.race(promises); } function toBe(value, options) { if (!isRef(value)) return toMatch((v) => v === value, options); const { flush = "sync", deep = false, timeout, throwOnTimeout } = options !== null && options !== void 0 ? options : {}; let stop = null; const promises = [new Promise((resolve) => { stop = watch([r, value], ([v1, v2]) => { if (isNot !== (v1 === v2)) { if (stop) stop(); else nextTick(() => stop === null || stop === void 0 ? void 0 : stop()); resolve(v1); } }, { flush, deep, immediate: true }); })]; if (timeout != null) promises.push(promiseTimeout(timeout, throwOnTimeout).then(() => toValue(r)).finally(() => { stop === null || stop === void 0 || stop(); return toValue(r); })); return Promise.race(promises); } function toBeTruthy(options) { return toMatch((v) => Boolean(v), options); } function toBeNull(options) { return toBe(null, options); } function toBeUndefined(options) { return toBe(void 0, options); } function toBeNaN(options) { return toMatch(Number.isNaN, options); } function toContains(value, options) { return toMatch((v) => { const array = Array.from(v); return array.includes(value) || array.includes(toValue(value)); }, options); } function changed(options) { return changedTimes(1, options); } function changedTimes(n = 1, options) { let count = -1; return toMatch(() => { count += 1; return count >= n; }, options); } if (Array.isArray(toValue(r))) return { toMatch, toContains, changed, changedTimes, get not() { return createUntil(r, !isNot); } }; else return { toMatch, toBe, toBeTruthy, toBeNull, toBeNaN, toBeUndefined, changed, changedTimes, get not() { return createUntil(r, !isNot); } }; } function until(r) { return createUntil(r); } function defaultComparator(value, othVal) { return value === othVal; } // @__NO_SIDE_EFFECTS__ function useArrayDifference(...args) { var _args$, _args$2; const list = args[0]; const values = args[1]; let compareFn = (_args$ = args[2]) !== null && _args$ !== void 0 ? _args$ : defaultComparator; const { symmetric = false } = (_args$2 = args[3]) !== null && _args$2 !== void 0 ? _args$2 : {}; if (typeof compareFn === "string") { const key = compareFn; compareFn = (value, othVal) => value[key] === othVal[key]; } const diff1 = computed(() => toValue(list).filter((x) => toValue(values).findIndex((y) => compareFn(x, y)) === -1)); if (symmetric) { const diff2 = computed(() => toValue(values).filter((x) => toValue(list).findIndex((y) => compareFn(x, y)) === -1)); return computed(() => symmetric ? [...toValue(diff1), ...toValue(diff2)] : toValue(diff1)); } else return diff1; } // @__NO_SIDE_EFFECTS__ function useArrayEvery(list, fn) { return computed(() => toValue(list).every((element, index, array) => fn(toValue(element), index, array))); } // @__NO_SIDE_EFFECTS__ function useArrayFilter(list, fn) { return computed(() => toValue(list).map((i) => toValue(i)).filter(fn)); } // @__NO_SIDE_EFFECTS__ function useArrayFind(list, fn) { return computed(() => toValue(toValue(list).find((element, index, array) => fn(toValue(element), index, array)))); } // @__NO_SIDE_EFFECTS__ function useArrayFindIndex(list, fn) { return computed(() => toValue(list).findIndex((element, index, array) => fn(toValue(element), index, array))); } function findLast(arr, cb) { let index = arr.length; while (index-- > 0) if (cb(arr[index], index, arr)) return arr[index]; } // @__NO_SIDE_EFFECTS__ function useArrayFindLast(list, fn) { return computed(() => toValue(!Array.prototype.findLast ? findLast(toValue(list), (element, index, array) => fn(toValue(element), index, array)) : toValue(list).findLast((element, index, array) => fn(toValue(element), index, array)))); } function isArrayIncludesOptions(obj) { return isObject(obj) && containsProp(obj, "formIndex", "comparator"); } // @__NO_SIDE_EFFECTS__ function useArrayIncludes(...args) { var _comparator; const list = args[0]; const value = args[1]; let comparator = args[2]; let formIndex = 0; if (isArrayIncludesOptions(comparator)) { var _comparator$fromIndex; formIndex = (_comparator$fromIndex = comparator.fromIndex) !== null && _comparator$fromIndex !== void 0 ? _comparator$fromIndex : 0; comparator = comparator.comparator; } if (typeof comparator === "string") { const key = comparator; comparator = (element, value$1) => element[key] === toValue(value$1); } comparator = (_comparator = comparator) !== null && _comparator !== void 0 ? _comparator : ((element, value$1) => element === toValue(value$1)); return computed(() => toValue(list).slice(formIndex).some((element, index, array) => comparator(toValue(element), toValue(value), index, toValue(array)))); } // @__NO_SIDE_EFFECTS__ function useArrayJoin(list, separator) { return computed(() => toValue(list).map((i) => toValue(i)).join(toValue(separator))); } // @__NO_SIDE_EFFECTS__ function useArrayMap(list, fn) { return computed(() => toValue(list).map((i) => toValue(i)).map(fn)); } // @__NO_SIDE_EFFECTS__ function useArrayReduce(list, reducer, ...args) { const reduceCallback = (sum, value, index) => reducer(toValue(sum), toValue(value), index); return computed(() => { const resolved = toValue(list); return args.length ? resolved.reduce(reduceCallback, typeof args[0] === "function" ? toValue(args[0]()) : toValue(args[0])) : resolved.reduce(reduceCallback); }); } // @__NO_SIDE_EFFECTS__ function useArraySome(list, fn) { return computed(() => toValue(list).some((element, index, array) => fn(toValue(element), index, array))); } function uniq(array) { return Array.from(new Set(array)); } function uniqueElementsBy(array, fn) { return array.reduce((acc, v) => { if (!acc.some((x) => fn(v, x, array))) acc.push(v); return acc; }, []); } // @__NO_SIDE_EFFECTS__ function useArrayUnique(list, compareFn) { return computed(() => { const resolvedList = toValue(list).map((element) => toValue(element)); return compareFn ? uniqueElementsBy(resolvedList, compareFn) : uniq(resolvedList); }); } function useCounter(initialValue = 0, options = {}) { let _initialValue = unref(initialValue); const count = shallowRef(initialValue); const { max = Number.POSITIVE_INFINITY, min = Number.NEGATIVE_INFINITY } = options; const inc = (delta = 1) => count.value = Math.max(Math.min(max, count.value + delta), min); const dec = (delta = 1) => count.value = Math.min(Math.max(min, count.value - delta), max); const get$1 = () => count.value; const set$1 = (val) => count.value = Math.max(min, Math.min(max, val)); const reset = (val = _initialValue) => { _initialValue = val; return set$1(val); }; return { count: shallowReadonly(count), inc, dec, get: get$1, set: set$1, reset }; } const REGEX_PARSE = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[T\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/i; const REGEX_FORMAT = /[YMDHhms]o|\[([^\]]+)\]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a{1,2}|A{1,2}|m{1,2}|s{1,2}|Z{1,2}|z{1,4}|SSS/g; function defaultMeridiem(hours, minutes, isLowercase, hasPeriod) { let m = hours < 12 ? "AM" : "PM"; if (hasPeriod) m = m.split("").reduce((acc, curr) => acc += `${curr}.`, ""); return isLowercase ? m.toLowerCase() : m; } function formatOrdinal(num) { const suffixes = [ "th", "st", "nd", "rd" ]; const v = num % 100; return num + (suffixes[(v - 20) % 10] || suffixes[v] || suffixes[0]); } function formatDate(date, formatStr, options = {}) { var _options$customMeridi; const years = date.getFullYear(); const month = date.getMonth(); const days = date.getDate(); const hours = date.getHours(); const minutes = date.getMinutes(); const seconds = date.getSeconds(); const milliseconds = date.getMilliseconds(); const day = date.getDay(); const meridiem = (_options$customMeridi = options.customMeridiem) !== null && _options$customMeridi !== void 0 ? _options$customMeridi : defaultMeridiem; const stripTimeZone = (dateString) => { var _dateString$split$; return (_dateString$split$ = dateString.split(" ")[1]) !== null && _dateString$split$ !== void 0 ? _dateString$split$ : ""; }; const matches = { Yo: () => formatOrdinal(years), YY: () => String(years).slice(-2), YYYY: () => years, M: () => month + 1, Mo: () => formatOrdinal(month + 1), MM: () => `${month + 1}`.padStart(2, "0"), MMM: () => date.toLocaleDateString(toValue(options.locales), { month: "short" }), MMMM: () => date.toLocaleDateString(toValue(options.locales), { month: "long" }), D: () => String(days), Do: () => formatOrdinal(days), DD: () => `${days}`.padStart(2, "0"), H: () => String(hours), Ho: () => formatOrdinal(hours), HH: () => `${hours}`.padStart(2, "0"), h: () => `${hours % 12 || 12}`.padStart(1, "0"), ho: () => formatOrdinal(hours % 12 || 12), hh: () => `${hours % 12 || 12}`.padStart(2, "0"), m: () => String(minutes), mo: () => formatOrdinal(minutes), mm: () => `${minutes}`.padStart(2, "0"), s: () => String(seconds), so: () => formatOrdinal(seconds), ss: () => `${seconds}`.padStart(2, "0"), SSS: () => `${milliseconds}`.padStart(3, "0"), d: () => day, dd: () => date.toLocaleDateString(toValue(options.locales), { weekday: "narrow" }), ddd: () => date.toLocaleDateString(toValue(options.locales), { weekday: "short" }), dddd: () => date.toLocaleDateString(toValue(options.locales), { weekday: "long" }), A: () => meridiem(hours, minutes), AA: () => meridiem(hours, minutes, false, true), a: () => meridiem(hours, minutes, true), aa: () => meridiem(hours, minutes, true, true), z: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: "shortOffset" })), zz: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: "shortOffset" })), zzz: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: "shortOffset" })), zzzz: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: "longOffset" })) }; return formatStr.replace(REGEX_FORMAT, (match, $1) => { var _ref, _matches$match; return (_ref = $1 !== null && $1 !== void 0 ? $1 : (_matches$match = matches[match]) === null || _matches$match === void 0 ? void 0 : _matches$match.call(matches)) !== null && _ref !== void 0 ? _ref : match; }); } function normalizeDate(date) { if (date === null) return /* @__PURE__ */ new Date(NaN); if (date === void 0) return /* @__PURE__ */ new Date(); if (date instanceof Date) return new Date(date); if (typeof date === "string" && !/Z$/i.test(date)) { const d = date.match(REGEX_PARSE); if (d) { const m = d[2] - 1 || 0; const ms = (d[7] || "0").substring(0, 3); return new Date(d[1], m, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, ms); } } return new Date(date); } // @__NO_SIDE_EFFECTS__ function useDateFormat(date, formatStr = "HH:mm:ss", options = {}) { return computed(() => formatDate(normalizeDate(toValue(date)), toValue(formatStr), options)); } function useIntervalFn(cb, interval = 1e3, options = {}) { const { immediate = true, immediateCallback = false } = options; let timer = null; const isActive = shallowRef(false); function clean() { if (timer) { clearInterval(timer); timer = null; } } function pause() { isActive.value = false; clean(); } function resume() { const intervalValue = toValue(interval); if (intervalValue <= 0) return; isActive.value = true; if (immediateCallback) cb(); clean(); if (isActive.value) timer = setInterval(cb, intervalValue); } if (immediate && isClient) resume(); if (isRef(interval) || typeof interval === "function") tryOnScopeDispose(watch(interval, () => { if (isActive.value && isClient) resume(); })); tryOnScopeDispose(pause); return { isActive: shallowReadonly(isActive), pause, resume }; } function useInterval(interval = 1e3, options = {}) { const { controls: exposeControls = false, immediate = true, callback } = options; const counter = shallowRef(0); const update = () => counter.value += 1; const reset = () => { counter.value = 0; }; const controls = useIntervalFn(callback ? () => { update(); callback(counter.value); } : update, interval, { immediate }); if (exposeControls) return { counter: shallowReadonly(counter), reset, ...controls }; else return shallowReadonly(counter); } function useLastChanged(source, options = {}) { var _options$initialValue; const ms = shallowRef((_options$initialValue = options.initialValue) !== null && _options$initialValue !== void 0 ? _options$initialValue : null); watch(source, () => ms.value = timestamp(), options); return shallowReadonly(ms); } function useTimeoutFn(cb, interval, options = {}) { const { immediate = true, immediateCallback = false } = options; const isPending = shallowRef(false); let timer; function clear() { if (timer) { clearTimeout(timer); timer = void 0; } } function stop() { isPending.value = false; clear(); } function start(...args) { if (immediateCallback) cb(); clear(); isPending.value = true; timer = setTimeout(() => { isPending.value = false; timer = void 0; cb(...args); }, toValue(interval)); } if (immediate) { isPending.value = true; if (isClient) start(); } tryOnScopeDispose(stop); return { isPending: shallowReadonly(isPending), start, stop }; } function useTimeout(interval = 1e3, options = {}) { const { controls: exposeControls = false, callback } = options; const controls = useTimeoutFn(callback !== null && callback !== void 0 ? callback : noop, interval, options); const ready = computed(() => !controls.isPending.value); if (exposeControls) return { ready, ...controls }; else return ready; } // @__NO_SIDE_EFFECTS__ function useToNumber(value, options = {}) { const { method = "parseFloat", radix, nanToZero } = options; return computed(() => { let resolved = toValue(value); if (typeof method === "function") resolved = method(resolved); else if (typeof resolved === "string") resolved = Number[method](resolved, radix); if (nanToZero && Number.isNaN(resolved)) resolved = 0; return resolved; }); } // @__NO_SIDE_EFFECTS__ function useToString(value) { return computed(() => `${toValue(value)}`); } // @__NO_SIDE_EFFECTS__ function useToggle(initialValue = false, options = {}) { const { truthyValue = true, falsyValue = false } = options; const valueIsRef = isRef(initialValue); const _value = shallowRef(initialValue); function toggle(value) { if (arguments.length) { _value.value = value; return _value.value; } else { const truthy = toValue(truthyValue); _value.value = _value.value === truthy ? toValue(falsyValue) : truthy; return _value.value; } } if (valueIsRef) return toggle; else return [_value, toggle]; } function watchArray(source, cb, options) { let oldList = (options === null || options === void 0 ? void 0 : options.immediate) ? [] : [...typeof source === "function" ? source() : Array.isArray(source) ? source : toValue(source)]; return watch(source, (newList, _, onCleanup) => { const oldListRemains = Array.from({ length: oldList.length }); const added = []; for (const obj of newList) { let found = false; for (let i = 0; i < oldList.length; i++) if (!oldListRemains[i] && obj === oldList[i]) { oldListRemains[i] = true; found = true; break; } if (!found) added.push(obj); } const removed = oldList.filter((_$1, i) => !oldListRemains[i]); cb(newList, oldList, added, removed, onCleanup); oldList = [...newList]; }, options); } function watchAtMost(source, cb, options) { const { count, ...watchOptions } = options; const current = shallowRef(0); const { stop, resume, pause } = watchWithFilter(source, (...args) => { current.value += 1; if (current.value >= toValue(count)) nextTick(() => stop()); cb(...args); }, watchOptions); return { count: current, stop, resume, pause }; } function watchDebounced(source, cb, options = {}) { const { debounce = 0, maxWait = void 0, ...watchOptions } = options; return watchWithFilter(source, cb, { ...watchOptions, eventFilter: debounceFilter(debounce, { maxWait }) }); } const debouncedWatch = watchDebounced; function watchDeep(source, cb, options) { return watch(source, cb, { ...options, deep: true }); } function watchIgnorable(source, cb, options = {}) { const { eventFilter = bypassFilter, ...watchOptions } = options; const filteredCb = createFilterWrapper(eventFilter, cb); let ignoreUpdates; let ignorePrevAsyncUpdates; let stop; if (watchOptions.flush === "sync") { let ignore = false; ignorePrevAsyncUpdates = () => { }; ignoreUpdates = (updater) => { ignore = true; updater(); ignore = false; }; stop = watch(source, (...args) => { if (!ignore) filteredCb(...args); }, watchOptions); } else { const disposables = []; let ignoreCounter = 0; let syncCounter = 0; ignorePrevAsyncUpdates = () => { ignoreCounter = syncCounter; }; disposables.push(watch(source, () => { syncCounter++; }, { ...watchOptions, flush: "sync" })); ignoreUpdates = (updater) => { const syncCounterPrev = syncCounter; updater(); ignoreCounter += syncCounter - syncCounterPrev; }; disposables.push(watch(source, (...args) => { const ignore = ignoreCounter > 0 && ignoreCounter === syncCounter; ignoreCounter = 0; syncCounter = 0; if (ignore) return; filteredCb(...args); }, watchOptions)); stop = () => { disposables.forEach((fn) => fn()); }; } return { stop, ignoreUpdates, ignorePrevAsyncUpdates }; } const ignorableWatch = watchIgnorable; function watchImmediate(source, cb, options) { return watch(source, cb, { ...options, immediate: true }); } function watchOnce(source, cb, options) { return watch(source, cb, { ...options, once: true }); } function watchThrottled(source, cb, options = {}) { const { throttle = 0, trailing = true, leading = true, ...watchOptions } = options; return watchWithFilter(source, cb, { ...watchOptions, eventFilter: throttleFilter(throttle, trailing, leading) }); } const throttledWatch = watchThrottled; function watchTriggerable(source, cb, options = {}) { let cleanupFn; function onEffect() { if (!cleanupFn) return; const fn = cleanupFn; cleanupFn = void 0; fn(); } function onCleanup(callback) { cleanupFn = callback; } const _cb = (value, oldValue) => { onEffect(); return cb(value, oldValue, onCleanup); }; const res = watchIgnorable(source, _cb, options); const { ignoreUpdates } = res; const trigger = () => { let res$1; ignoreUpdates(() => { res$1 = _cb(getWatchSources(source), getOldValue(source)); }); return res$1; }; return { ...res, trigger }; } function getWatchSources(sources) { if (isReactive(sources)) return sources; if (Array.isArray(sources)) return sources.map((item) => toValue(item)); return toValue(sources); } function getOldValue(source) { return Array.isArray(source) ? source.map(() => void 0) : void 0; } function whenever(source, cb, options) { const stop = watch(source, (v, ov, onInvalidate) => { if (v) { if (options === null || options === void 0 ? void 0 : options.once) nextTick(() => stop()); cb(v, ov, onInvalidate); } }, { ...options, once: false }); return stop; } function computedAsync(evaluationCallback, initialState, optionsOrRef) { var _globalThis$reportErr; let options; if (isRef(optionsOrRef)) options = { evaluating: optionsOrRef }; else options = optionsOrRef || {}; const { lazy = false, flush = "sync", evaluating = void 0, shallow = true, onError = (_globalThis$reportErr = globalThis.reportError) !== null && _globalThis$reportErr !== void 0 ? _globalThis$reportErr : noop } = options; const started = shallowRef(!lazy); const current = shallow ? shallowRef(initialState) : ref(initialState); let counter = 0; watchEffect(async (onInvalidate) => { if (!started.value) return; counter++; const counterAtBeginning = counter; let hasFinished = false; if (evaluating) Promise.resolve().then(() => { evaluating.value = true; }); try { const result = await evaluationCallback((cancelCallback) => { onInvalidate(() => { if (evaluating) evaluating.value = false; if (!hasFinished) cancelCallback(); }); }); if (counterAtBeginning === counter) current.value = result; } catch (e) { onError(e); } finally { if (evaluating && counterAtBeginning === counter) evaluating.value = false; hasFinished = true; } }, { flush }); if (lazy) return computed(() => { started.value = true; return current.value; }); else return current; } const asyncComputed = computedAsync; // @__NO_SIDE_EFFECTS__ function createUnrefFn(fn) { return function(...args) { return fn.apply(this, args.map((i) => toValue(i))); }; } const defaultWindow = isClient ? window : void 0; function unrefElement(elRef) { var _$el; const plain = toValue(elRef); return (_$el = plain === null || plain === void 0 ? void 0 : plain.$el) !== null && _$el !== void 0 ? _$el : plain; } function useEventListener(...args) { const register = (el, event, listener, options) => { el.addEventListener(event, listener, options); return () => el.removeEventListener(event, listener, options); }; const firstParamTargets = computed(() => { const test = toArray(toValue(args[0])).filter((e) => e != null); return test.every((e) => typeof e !== "string") ? test : void 0; }); return watchImmediate(() => { var _firstParamTargets$va, _firstParamTargets$va2; return [ (_firstParamTargets$va = (_firstParamTargets$va2 = firstParamTargets.value) === null || _firstParamTargets$va2 === void 0 ? void 0 : _firstParamTargets$va2.map((e) => unrefElement(e))) !== null && _firstParamTargets$va !== void 0 ? _firstParamTargets$va : [defaultWindow].filter((e) => e != null), toArray(toValue(firstParamTargets.value ? args[1] : args[0])), toArray(unref(firstParamTargets.value ? args[2] : args[1])), toValue(firstParamTargets.value ? args[3] : args[2]) ]; }, ([raw_targets, raw_events, raw_listeners, raw_options], _, onCleanup) => { if (!(raw_targets === null || raw_targets === void 0 ? void 0 : raw_targets.length) || !(raw_events === null || raw_events === void 0 ? void 0 : raw_events.length) || !(raw_listeners === null || raw_listeners === void 0 ? void 0 : raw_listeners.length)) return; const optionsClone = isObject(raw_options) ? { ...raw_options } : raw_options; const cleanups = raw_targets.flatMap((el) => raw_events.flatMap((event) => raw_listeners.map((listener) => register(el, event, listener, optionsClone)))); onCleanup(() => { cleanups.forEach((fn) => fn()); }); }, { flush: "post" }); } // @__NO_SIDE_EFFECTS__ function useMounted() { const isMounted = shallowRef(false); return isMounted; } // @__NO_SIDE_EFFECTS__ function useSupported(callback) { const isMounted = /* @__PURE__ */ useMounted(); return computed(() => { isMounted.value; return Boolean(callback()); }); } function useRafFn(fn, options = {}) { const { immediate = true, fpsLimit = void 0, window: window$1 = defaultWindow, once = false } = options; const isActive = shallowRef(false); const intervalLimit = computed(() => { return fpsLimit ? 1e3 / toValue(fpsLimit) : null; }); let previousFrameTimestamp = 0; let rafId = null; function loop(timestamp$1) { if (!isActive.value || !window$1) return; if (!previousFrameTimestamp) previousFrameTimestamp = timestamp$1; const delta = timestamp$1 - previousFrameTimestamp; if (intervalLimit.value && delta < intervalLimit.value) { rafId = window$1.requestAnimationFrame(loop); return; } previousFrameTimestamp = timestamp$1; fn({ delta, timestamp: timestamp$1 }); if (once) { isActive.value = false; rafId = null; return; } rafId = window$1.requestAnimationFrame(loop); } function resume() { if (!isActive.value && window$1) { isActive.value = true; previousFrameTimestamp = 0; rafId = window$1.requestAnimationFrame(loop); } } function pause() { isActive.value = false; if (rafId != null && window$1) { window$1.cancelAnimationFrame(rafId); rafId = null; } } if (immediate) resume(); tryOnScopeDispose(pause); return { isActive: readonly(isActive), pause, resume }; } function useAsyncQueue(tasks, options) { const { interrupt = true, onError = noop, onFinished = noop, signal } = options || {}; const promiseState = { aborted: "aborted", fulfilled: "fulfilled", pending: "pending", rejected: "rejected" }; const result = reactive(Array.from(Array.from({ length: tasks.length }), () => ({ state: promiseState.pending, data: null }))); const activeIndex = shallowRef(-1); if (!tasks || tasks.length === 0) { onFinished(); return { activeIndex, result }; } function updateResult(state, res) { activeIndex.value++; result[activeIndex.value].data = res; result[activeIndex.value].state = state; } tasks.reduce((prev, curr) => { return prev.then((prevRes) => { var _result$activeIndex$v; if (signal === null || signal === void 0 ? void 0 : signal.aborted) { updateResult(promiseState.aborted, /* @__PURE__ */ new Error("aborted")); return; } if (((_result$activeIndex$v = result[activeIndex.value]) === null || _result$activeIndex$v === void 0 ? void 0 : _result$activeIndex$v.state) === promiseState.rejected && interrupt) { onFinished(); return; } const done = curr(prevRes).then((currentRes) => { updateResult(promiseState.fulfilled, currentRes); if (activeIndex.value === tasks.length - 1) onFinished(); return curre