index.js 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021
  1. import { computed, customRef, effectScope, getCurrentInstance, getCurrentScope, hasInjectionContext, inject, isReactive, isRef, nextTick, onBeforeMount, onBeforeUnmount, onMounted, onScopeDispose, onUnmounted, provide, reactive, readonly, ref, shallowReadonly, shallowRef, toRef as toRef$1, toRefs as toRefs$1, toValue, unref, watch, watchEffect } from "vue";
  2. //#region computedEager/index.ts
  3. /**
  4. *
  5. * @deprecated This function will be removed in future version.
  6. *
  7. * Note: If you are using Vue 3.4+, you can straight use computed instead.
  8. * Because in Vue 3.4+, if computed new value does not change,
  9. * computed, effect, watch, watchEffect, render dependencies will not be triggered.
  10. * refer: https://github.com/vuejs/core/pull/5912
  11. *
  12. * @param fn effect function
  13. * @param options WatchOptionsBase
  14. * @returns readonly shallowRef
  15. */
  16. function computedEager(fn, options) {
  17. var _options$flush;
  18. const result = shallowRef();
  19. watchEffect(() => {
  20. result.value = fn();
  21. }, {
  22. ...options,
  23. flush: (_options$flush = options === null || options === void 0 ? void 0 : options.flush) !== null && _options$flush !== void 0 ? _options$flush : "sync"
  24. });
  25. return readonly(result);
  26. }
  27. /** @deprecated use `computedEager` instead */
  28. const eagerComputed = computedEager;
  29. //#endregion
  30. //#region computedWithControl/index.ts
  31. /**
  32. * Explicitly define the deps of computed.
  33. *
  34. * @param source
  35. * @param fn
  36. */
  37. function computedWithControl(source, fn, options = {}) {
  38. let v = void 0;
  39. let track;
  40. let trigger;
  41. let dirty = true;
  42. const update = () => {
  43. dirty = true;
  44. trigger();
  45. };
  46. watch(source, update, {
  47. flush: "sync",
  48. ...options
  49. });
  50. const get = typeof fn === "function" ? fn : fn.get;
  51. const set = typeof fn === "function" ? void 0 : fn.set;
  52. const result = customRef((_track, _trigger) => {
  53. track = _track;
  54. trigger = _trigger;
  55. return {
  56. get() {
  57. if (dirty) {
  58. v = get(v);
  59. dirty = false;
  60. }
  61. track();
  62. return v;
  63. },
  64. set(v) {
  65. set === null || set === void 0 || set(v);
  66. }
  67. };
  68. });
  69. result.trigger = update;
  70. return result;
  71. }
  72. /** @deprecated use `computedWithControl` instead */
  73. const controlledComputed = computedWithControl;
  74. //#endregion
  75. //#region createDisposableDirective/index.ts
  76. /**
  77. * Utility for authoring disposable directives. Reactive effects created within `mounted` directive hook will be tracked and automatically disposed when directive is unmounted.
  78. *
  79. * @see https://vueuse.org/createDisposableDirective
  80. *
  81. * @__NO_SIDE_EFFECTS__
  82. */
  83. function createDisposableDirective(origin = {}) {
  84. function isFunc(fn) {
  85. return typeof fn === "function";
  86. }
  87. const normalisedOrigin = isFunc(origin) ? {
  88. mounted: origin,
  89. updated: origin
  90. } : origin;
  91. const { mounted, unmounted } = normalisedOrigin;
  92. if (!isFunc(mounted)) return origin;
  93. const scopeWeakMap = /* @__PURE__ */ new WeakMap();
  94. return {
  95. ...normalisedOrigin,
  96. mounted(el, binding, vNode, prevNode) {
  97. var _scopeWeakMap$get;
  98. const scope = (_scopeWeakMap$get = scopeWeakMap.get(el)) !== null && _scopeWeakMap$get !== void 0 ? _scopeWeakMap$get : effectScope();
  99. scopeWeakMap.set(el, scope);
  100. scope.run(() => {
  101. mounted === null || mounted === void 0 || mounted(el, binding, vNode, prevNode);
  102. });
  103. },
  104. unmounted(el, binding, vNode, prevNode) {
  105. var _scopeWeakMap$get2;
  106. (_scopeWeakMap$get2 = scopeWeakMap.get(el)) === null || _scopeWeakMap$get2 === void 0 || _scopeWeakMap$get2.stop();
  107. scopeWeakMap.delete(el);
  108. if (isFunc(unmounted)) unmounted(el, binding, vNode, prevNode);
  109. }
  110. };
  111. }
  112. //#endregion
  113. //#region tryOnScopeDispose/index.ts
  114. /**
  115. * Call onScopeDispose() if it's inside an effect scope lifecycle, if not, do nothing
  116. *
  117. * @param fn
  118. */
  119. function tryOnScopeDispose(fn, failSilently) {
  120. if (getCurrentScope()) {
  121. onScopeDispose(fn, failSilently);
  122. return true;
  123. }
  124. return false;
  125. }
  126. //#endregion
  127. //#region createEventHook/index.ts
  128. /**
  129. * Utility for creating event hooks
  130. *
  131. * @see https://vueuse.org/createEventHook
  132. *
  133. * @__NO_SIDE_EFFECTS__
  134. */
  135. function createEventHook() {
  136. const fns = /* @__PURE__ */ new Set();
  137. const off = (fn) => {
  138. fns.delete(fn);
  139. };
  140. const clear = () => {
  141. fns.clear();
  142. };
  143. const on = (fn) => {
  144. fns.add(fn);
  145. const offFn = () => off(fn);
  146. tryOnScopeDispose(offFn);
  147. return { off: offFn };
  148. };
  149. const trigger = (...args) => {
  150. return Promise.all(Array.from(fns).map((fn) => fn(...args)));
  151. };
  152. return {
  153. on,
  154. off,
  155. trigger,
  156. clear
  157. };
  158. }
  159. //#endregion
  160. //#region createGlobalState/index.ts
  161. /**
  162. * Keep states in the global scope to be reusable across Vue instances.
  163. *
  164. * @see https://vueuse.org/createGlobalState
  165. * @param stateFactory A factory function to create the state
  166. *
  167. * @__NO_SIDE_EFFECTS__
  168. */
  169. function createGlobalState(stateFactory) {
  170. let initialized = false;
  171. let state;
  172. const scope = effectScope(true);
  173. return ((...args) => {
  174. if (!initialized) {
  175. state = scope.run(() => stateFactory(...args));
  176. initialized = true;
  177. }
  178. return state;
  179. });
  180. }
  181. //#endregion
  182. //#region provideLocal/map.ts
  183. const localProvidedStateMap = /* @__PURE__ */ new WeakMap();
  184. //#endregion
  185. //#region injectLocal/index.ts
  186. /**
  187. * On the basis of `inject`, it is allowed to directly call inject to obtain the value after call provide in the same component.
  188. *
  189. * @example
  190. * ```ts
  191. * injectLocal('MyInjectionKey', 1)
  192. * const injectedValue = injectLocal('MyInjectionKey') // injectedValue === 1
  193. * ```
  194. *
  195. * @NO_SIDE_EFFECTS
  196. */
  197. const injectLocal = /* @__NO_SIDE_EFFECTS__ */ (...args) => {
  198. var _getCurrentInstance;
  199. const key = args[0];
  200. const instance = (_getCurrentInstance = getCurrentInstance()) === null || _getCurrentInstance === void 0 ? void 0 : _getCurrentInstance.proxy;
  201. const owner = instance !== null && instance !== void 0 ? instance : getCurrentScope();
  202. if (owner == null && !hasInjectionContext()) throw new Error("injectLocal must be called in setup");
  203. if (owner && localProvidedStateMap.has(owner) && key in localProvidedStateMap.get(owner)) return localProvidedStateMap.get(owner)[key];
  204. return inject(...args);
  205. };
  206. //#endregion
  207. //#region provideLocal/index.ts
  208. /**
  209. * On the basis of `provide`, it is allowed to directly call inject to obtain the value after call provide in the same component.
  210. *
  211. * @example
  212. * ```ts
  213. * provideLocal('MyInjectionKey', 1)
  214. * const injectedValue = injectLocal('MyInjectionKey') // injectedValue === 1
  215. * ```
  216. */
  217. function provideLocal(key, value) {
  218. var _getCurrentInstance;
  219. const instance = (_getCurrentInstance = getCurrentInstance()) === null || _getCurrentInstance === void 0 ? void 0 : _getCurrentInstance.proxy;
  220. const owner = instance !== null && instance !== void 0 ? instance : getCurrentScope();
  221. if (owner == null) throw new Error("provideLocal must be called in setup");
  222. if (!localProvidedStateMap.has(owner)) localProvidedStateMap.set(owner, Object.create(null));
  223. const localProvidedState = localProvidedStateMap.get(owner);
  224. localProvidedState[key] = value;
  225. return provide(key, value);
  226. }
  227. //#endregion
  228. //#region createInjectionState/index.ts
  229. /* @__NO_SIDE_EFFECTS__ */
  230. function createInjectionState(composable, options) {
  231. const key = (options === null || options === void 0 ? void 0 : options.injectionKey) || Symbol(composable.name || "InjectionState");
  232. const defaultValue = options === null || options === void 0 ? void 0 : options.defaultValue;
  233. const useProvidingState = (...args) => {
  234. const state = composable(...args);
  235. provideLocal(key, state);
  236. return state;
  237. };
  238. const useInjectedState = () => /* @__PURE__ */ injectLocal(key, defaultValue);
  239. return [useProvidingState, useInjectedState];
  240. }
  241. //#endregion
  242. //#region createRef/index.ts
  243. /**
  244. * Returns a `deepRef` or `shallowRef` depending on the `deep` param.
  245. *
  246. * @example createRef(1) // ShallowRef<number>
  247. * @example createRef(1, false) // ShallowRef<number>
  248. * @example createRef(1, true) // Ref<number>
  249. * @example createRef("string") // ShallowRef<string>
  250. * @example createRef<"A"|"B">("A", true) // Ref<"A"|"B">
  251. *
  252. * @param value
  253. * @param deep
  254. * @returns the `deepRef` or `shallowRef`
  255. *
  256. * @__NO_SIDE_EFFECTS__
  257. */
  258. function createRef(value, deep) {
  259. if (deep === true) return ref(value);
  260. else return shallowRef(value);
  261. }
  262. //#endregion
  263. //#region utils/is.ts
  264. const isClient = typeof window !== "undefined" && typeof document !== "undefined";
  265. const isWorker = typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope;
  266. const isDef = (val) => typeof val !== "undefined";
  267. const notNullish = (val) => val != null;
  268. const assert = (condition, ...infos) => {
  269. if (!condition) console.warn(...infos);
  270. };
  271. const toString = Object.prototype.toString;
  272. const isObject = (val) => toString.call(val) === "[object Object]";
  273. const now = () => Date.now();
  274. const timestamp = () => +Date.now();
  275. const clamp = (n, min, max) => Math.min(max, Math.max(min, n));
  276. const noop = () => {};
  277. const rand = (min, max) => {
  278. min = Math.ceil(min);
  279. max = Math.floor(max);
  280. return Math.floor(Math.random() * (max - min + 1)) + min;
  281. };
  282. const hasOwn = (val, key) => Object.hasOwn(val, key);
  283. const isIOS = /* #__PURE__ */ getIsIOS();
  284. function getIsIOS() {
  285. var _window, _window2, _window3;
  286. return isClient && !!((_window = window) === null || _window === void 0 || (_window = _window.navigator) === null || _window === void 0 ? void 0 : _window.userAgent) && (/iP(?:ad|hone|od)/.test(window.navigator.userAgent) || ((_window2 = window) === null || _window2 === void 0 || (_window2 = _window2.navigator) === null || _window2 === void 0 ? void 0 : _window2.maxTouchPoints) > 2 && /iPad|Macintosh/.test((_window3 = window) === null || _window3 === void 0 ? void 0 : _window3.navigator.userAgent));
  287. }
  288. //#endregion
  289. //#region toRef/index.ts
  290. function toRef(...args) {
  291. if (args.length !== 1) return toRef$1(...args);
  292. const r = args[0];
  293. return typeof r === "function" ? readonly(customRef(() => ({
  294. get: r,
  295. set: noop
  296. }))) : ref(r);
  297. }
  298. //#endregion
  299. //#region utils/filters.ts
  300. function createFilterWrapper(filter, fn) {
  301. function wrapper(...args) {
  302. return new Promise((resolve, reject) => {
  303. Promise.resolve(filter(() => fn.apply(this, args), {
  304. fn,
  305. thisArg: this,
  306. args
  307. })).then(resolve).catch(reject);
  308. });
  309. }
  310. if ("cancel" in filter) Object.assign(wrapper, {
  311. cancel: filter.cancel,
  312. flush: filter.flush,
  313. isPending: filter.isPending
  314. });
  315. return wrapper;
  316. }
  317. const bypassFilter = (invoke) => {
  318. return invoke();
  319. };
  320. /**
  321. * Create an EventFilter that debounce the events
  322. */
  323. function debounceFilter(ms, options = {}) {
  324. let timer;
  325. let maxTimer;
  326. let lastRejector = noop;
  327. let lastResolve = noop;
  328. const _pending = shallowRef(false);
  329. const _clearTimeout = (timer) => {
  330. clearTimeout(timer);
  331. lastRejector();
  332. lastRejector = noop;
  333. };
  334. let lastInvoker;
  335. const handler = (invoke) => {
  336. const duration = toValue(ms);
  337. const maxDuration = toValue(options.maxWait);
  338. if (timer) _clearTimeout(timer);
  339. if (duration <= 0 || maxDuration !== void 0 && maxDuration <= 0) {
  340. if (maxTimer) {
  341. _clearTimeout(maxTimer);
  342. maxTimer = void 0;
  343. }
  344. _pending.value = false;
  345. return Promise.resolve(invoke());
  346. }
  347. _pending.value = true;
  348. return new Promise((resolve, reject) => {
  349. lastRejector = options.rejectOnCancel ? reject : resolve;
  350. lastResolve = resolve;
  351. lastInvoker = invoke;
  352. if (maxDuration && !maxTimer) maxTimer = setTimeout(() => {
  353. if (timer) _clearTimeout(timer);
  354. maxTimer = void 0;
  355. _pending.value = false;
  356. resolve(lastInvoker());
  357. }, maxDuration);
  358. timer = setTimeout(() => {
  359. if (maxTimer) _clearTimeout(maxTimer);
  360. maxTimer = void 0;
  361. _pending.value = false;
  362. resolve(invoke());
  363. }, duration);
  364. });
  365. };
  366. return Object.assign(handler, {
  367. cancel: () => {
  368. if (timer) {
  369. _clearTimeout(timer);
  370. timer = void 0;
  371. }
  372. if (maxTimer) {
  373. _clearTimeout(maxTimer);
  374. maxTimer = void 0;
  375. }
  376. _pending.value = false;
  377. lastResolve = noop;
  378. },
  379. flush: () => {
  380. if (_pending.value) {
  381. if (timer) {
  382. clearTimeout(timer);
  383. timer = void 0;
  384. }
  385. if (maxTimer) {
  386. clearTimeout(maxTimer);
  387. maxTimer = void 0;
  388. }
  389. _pending.value = false;
  390. const resolve = lastResolve;
  391. lastRejector = noop;
  392. lastResolve = noop;
  393. resolve(lastInvoker());
  394. }
  395. },
  396. isPending: shallowReadonly(_pending)
  397. });
  398. }
  399. function throttleFilter(...args) {
  400. let lastExec = 0;
  401. let timer;
  402. let isLeading = true;
  403. let lastRejector = noop;
  404. let lastValue;
  405. let ms;
  406. let trailing;
  407. let leading;
  408. let rejectOnCancel;
  409. if (!isRef(args[0]) && typeof args[0] === "object") ({delay: ms, trailing = true, leading = true, rejectOnCancel = false} = args[0]);
  410. else [ms, trailing = true, leading = true, rejectOnCancel = false] = args;
  411. const clear = () => {
  412. if (timer) {
  413. clearTimeout(timer);
  414. timer = void 0;
  415. lastRejector();
  416. lastRejector = noop;
  417. }
  418. };
  419. const filter = (_invoke) => {
  420. const duration = toValue(ms);
  421. const elapsed = Date.now() - lastExec;
  422. const invoke = () => {
  423. return lastValue = _invoke();
  424. };
  425. clear();
  426. if (duration <= 0) {
  427. lastExec = Date.now();
  428. return invoke();
  429. }
  430. if (elapsed > duration) {
  431. lastExec = Date.now();
  432. if (leading || !isLeading) invoke();
  433. } else if (trailing) lastValue = new Promise((resolve, reject) => {
  434. lastRejector = rejectOnCancel ? reject : resolve;
  435. timer = setTimeout(() => {
  436. lastExec = Date.now();
  437. isLeading = true;
  438. resolve(invoke());
  439. clear();
  440. }, Math.max(0, duration - elapsed));
  441. });
  442. if (!leading && !timer) timer = setTimeout(() => isLeading = true, duration);
  443. isLeading = false;
  444. return lastValue;
  445. };
  446. return filter;
  447. }
  448. /**
  449. * EventFilter that gives extra controls to pause and resume the filter
  450. *
  451. * @param extendFilter Extra filter to apply when the PausableFilter is active, default to none
  452. * @param options Options to configure the filter
  453. */
  454. function pausableFilter(extendFilter = bypassFilter, options = {}) {
  455. const { initialState = "active" } = options;
  456. const isActive = toRef(initialState === "active");
  457. function pause() {
  458. isActive.value = false;
  459. }
  460. function resume() {
  461. isActive.value = true;
  462. }
  463. const eventFilter = (...args) => {
  464. if (isActive.value) extendFilter(...args);
  465. };
  466. return {
  467. isActive: shallowReadonly(isActive),
  468. pause,
  469. resume,
  470. eventFilter
  471. };
  472. }
  473. //#endregion
  474. //#region utils/general.ts
  475. function promiseTimeout(ms, throwOnTimeout = false, reason = "Timeout") {
  476. return new Promise((resolve, reject) => {
  477. if (throwOnTimeout) setTimeout(reject, ms, reason);
  478. else setTimeout(resolve, ms);
  479. });
  480. }
  481. function identity(arg) {
  482. return arg;
  483. }
  484. /**
  485. * Create singleton promise function
  486. *
  487. * @example
  488. * ```
  489. * const promise = createSingletonPromise(async () => { ... })
  490. *
  491. * await promise()
  492. * await promise() // all of them will be bind to a single promise instance
  493. * await promise() // and be resolved together
  494. * ```
  495. */
  496. function createSingletonPromise(fn) {
  497. let _promise;
  498. function wrapper() {
  499. if (!_promise) _promise = fn();
  500. return _promise;
  501. }
  502. wrapper.reset = async () => {
  503. const _prev = _promise;
  504. _promise = void 0;
  505. if (_prev) await _prev;
  506. };
  507. return wrapper;
  508. }
  509. function invoke(fn) {
  510. return fn();
  511. }
  512. function containsProp(obj, ...props) {
  513. return props.some((k) => k in obj);
  514. }
  515. function increaseWithUnit(target, delta) {
  516. var _target$match;
  517. if (typeof target === "number") return target + delta;
  518. const value = ((_target$match = target.match(/^-?\d+\.?\d*/)) === null || _target$match === void 0 ? void 0 : _target$match[0]) || "";
  519. const unit = target.slice(value.length);
  520. const result = Number.parseFloat(value) + delta;
  521. if (Number.isNaN(result)) return target;
  522. return result + unit;
  523. }
  524. /**
  525. * Get a px value for SSR use, do not rely on this method outside of SSR as REM unit is assumed at 16px, which might not be the case on the client
  526. */
  527. function pxValue(px) {
  528. return px.endsWith("rem") ? Number.parseFloat(px) * 16 : Number.parseFloat(px);
  529. }
  530. /**
  531. * Create a new subset object by giving keys
  532. */
  533. function objectPick(obj, keys, omitUndefined = false) {
  534. return keys.reduce((n, k) => {
  535. if (k in obj) {
  536. if (!omitUndefined || obj[k] !== void 0) n[k] = obj[k];
  537. }
  538. return n;
  539. }, {});
  540. }
  541. /**
  542. * Create a new subset object by omit giving keys
  543. */
  544. function objectOmit(obj, keys, omitUndefined = false) {
  545. return Object.fromEntries(Object.entries(obj).filter(([key, value]) => {
  546. return (!omitUndefined || value !== void 0) && !keys.includes(key);
  547. }));
  548. }
  549. function objectEntries(obj) {
  550. return Object.entries(obj);
  551. }
  552. function toArray(value) {
  553. return Array.isArray(value) ? value : [value];
  554. }
  555. //#endregion
  556. //#region utils/port.ts
  557. function cacheStringFunction(fn) {
  558. const cache = Object.create(null);
  559. return ((str) => {
  560. return cache[str] || (cache[str] = fn(str));
  561. });
  562. }
  563. const hyphenateRE = /\B([A-Z])/g;
  564. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, "-$1").toLowerCase());
  565. const camelizeRE = /-(\w)/g;
  566. const camelize = cacheStringFunction((str) => {
  567. return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : "");
  568. });
  569. //#endregion
  570. //#region utils/vue.ts
  571. function getLifeCycleTarget(target) {
  572. return target || getCurrentInstance();
  573. }
  574. //#endregion
  575. //#region createSharedComposable/index.ts
  576. /**
  577. * Make a composable function usable with multiple Vue instances.
  578. *
  579. * @see https://vueuse.org/createSharedComposable
  580. *
  581. * @__NO_SIDE_EFFECTS__
  582. */
  583. function createSharedComposable(composable) {
  584. if (!isClient) return composable;
  585. let subscribers = 0;
  586. let state;
  587. let scope;
  588. const dispose = () => {
  589. subscribers -= 1;
  590. if (scope && subscribers <= 0) {
  591. scope.stop();
  592. state = void 0;
  593. scope = void 0;
  594. }
  595. };
  596. return ((...args) => {
  597. subscribers += 1;
  598. if (!scope) {
  599. scope = effectScope(true);
  600. state = scope.run(() => composable(...args));
  601. }
  602. tryOnScopeDispose(dispose);
  603. return state;
  604. });
  605. }
  606. //#endregion
  607. //#region extendRef/index.ts
  608. function extendRef(ref, extend, { enumerable = false, unwrap = true } = {}) {
  609. for (const [key, value] of Object.entries(extend)) {
  610. if (key === "value") continue;
  611. if (isRef(value) && unwrap) Object.defineProperty(ref, key, {
  612. get() {
  613. return value.value;
  614. },
  615. set(v) {
  616. value.value = v;
  617. },
  618. enumerable
  619. });
  620. else Object.defineProperty(ref, key, {
  621. value,
  622. enumerable
  623. });
  624. }
  625. return ref;
  626. }
  627. //#endregion
  628. //#region get/index.ts
  629. function get(obj, key) {
  630. if (key == null) return unref(obj);
  631. return unref(obj)[key];
  632. }
  633. //#endregion
  634. //#region isDefined/index.ts
  635. function isDefined(v) {
  636. return unref(v) != null;
  637. }
  638. //#endregion
  639. //#region makeDestructurable/index.ts
  640. /* @__NO_SIDE_EFFECTS__ */
  641. function makeDestructurable(obj, arr) {
  642. if (typeof Symbol !== "undefined") {
  643. const clone = { ...obj };
  644. Object.defineProperty(clone, Symbol.iterator, {
  645. enumerable: false,
  646. value() {
  647. let index = 0;
  648. return { next: () => ({
  649. value: arr[index++],
  650. done: index > arr.length
  651. }) };
  652. }
  653. });
  654. return clone;
  655. } else return Object.assign([...arr], obj);
  656. }
  657. //#endregion
  658. //#region reactify/index.ts
  659. /**
  660. * Converts plain function into a reactive function.
  661. * The converted function accepts refs as it's arguments
  662. * and returns a ComputedRef, with proper typing.
  663. *
  664. * @param fn - Source function
  665. * @param options - Options
  666. *
  667. * @__NO_SIDE_EFFECTS__
  668. */
  669. function reactify(fn, options) {
  670. const unrefFn = (options === null || options === void 0 ? void 0 : options.computedGetter) === false ? unref : toValue;
  671. return function(...args) {
  672. return computed(() => fn.apply(this, args.map((i) => unrefFn(i))));
  673. };
  674. }
  675. /** @deprecated use `reactify` instead */
  676. const createReactiveFn = reactify;
  677. //#endregion
  678. //#region reactifyObject/index.ts
  679. /* @__NO_SIDE_EFFECTS__ */
  680. function reactifyObject(obj, optionsOrKeys = {}) {
  681. let keys = [];
  682. let options;
  683. if (Array.isArray(optionsOrKeys)) keys = optionsOrKeys;
  684. else {
  685. options = optionsOrKeys;
  686. const { includeOwnProperties = true } = optionsOrKeys;
  687. keys.push(...Object.keys(obj));
  688. if (includeOwnProperties) keys.push(...Object.getOwnPropertyNames(obj));
  689. }
  690. return Object.fromEntries(keys.map((key) => {
  691. const value = obj[key];
  692. return [key, typeof value === "function" ? reactify(value.bind(obj), options) : value];
  693. }));
  694. }
  695. //#endregion
  696. //#region toReactive/index.ts
  697. /**
  698. * Converts ref to reactive.
  699. *
  700. * @see https://vueuse.org/toReactive
  701. * @param objectRef A ref of object
  702. */
  703. function toReactive(objectRef) {
  704. if (!isRef(objectRef)) return reactive(objectRef);
  705. const proxy = new Proxy({}, {
  706. get(_, p, receiver) {
  707. return unref(Reflect.get(objectRef.value, p, receiver));
  708. },
  709. set(_, p, value) {
  710. if (isRef(objectRef.value[p]) && !isRef(value)) objectRef.value[p].value = value;
  711. else objectRef.value[p] = value;
  712. return true;
  713. },
  714. deleteProperty(_, p) {
  715. return Reflect.deleteProperty(objectRef.value, p);
  716. },
  717. has(_, p) {
  718. return Reflect.has(objectRef.value, p);
  719. },
  720. ownKeys() {
  721. return Object.keys(objectRef.value);
  722. },
  723. getOwnPropertyDescriptor() {
  724. return {
  725. enumerable: true,
  726. configurable: true
  727. };
  728. }
  729. });
  730. return reactive(proxy);
  731. }
  732. //#endregion
  733. //#region reactiveComputed/index.ts
  734. /**
  735. * Computed reactive object.
  736. */
  737. function reactiveComputed(fn) {
  738. return toReactive(computed(fn));
  739. }
  740. //#endregion
  741. //#region reactiveOmit/index.ts
  742. /**
  743. * Reactively omit fields from a reactive object
  744. *
  745. * @see https://vueuse.org/reactiveOmit
  746. */
  747. function reactiveOmit(obj, ...keys) {
  748. const flatKeys = keys.flat();
  749. const predicate = flatKeys[0];
  750. 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]))));
  751. }
  752. //#endregion
  753. //#region reactivePick/index.ts
  754. /**
  755. * Reactively pick fields from a reactive object
  756. *
  757. * @see https://vueuse.org/reactivePick
  758. */
  759. function reactivePick(obj, ...keys) {
  760. const flatKeys = keys.flat();
  761. const predicate = flatKeys[0];
  762. 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)])));
  763. }
  764. //#endregion
  765. //#region refAutoReset/index.ts
  766. /**
  767. * Create a ref which will be reset to the default value after some time.
  768. *
  769. * @see https://vueuse.org/refAutoReset
  770. * @param defaultValue The value which will be set.
  771. * @param afterMs A zero-or-greater delay in milliseconds.
  772. */
  773. function refAutoReset(defaultValue, afterMs = 1e4) {
  774. return customRef((track, trigger) => {
  775. let value = toValue(defaultValue);
  776. let timer;
  777. const resetAfter = () => setTimeout(() => {
  778. value = toValue(defaultValue);
  779. trigger();
  780. }, toValue(afterMs));
  781. tryOnScopeDispose(() => {
  782. clearTimeout(timer);
  783. });
  784. return {
  785. get() {
  786. track();
  787. return value;
  788. },
  789. set(newValue) {
  790. value = newValue;
  791. trigger();
  792. clearTimeout(timer);
  793. timer = resetAfter();
  794. }
  795. };
  796. });
  797. }
  798. /** @deprecated use `refAutoReset` instead */
  799. const autoResetRef = refAutoReset;
  800. //#endregion
  801. //#region useDebounceFn/index.ts
  802. /**
  803. * Debounce execution of a function.
  804. *
  805. * @see https://vueuse.org/useDebounceFn
  806. * @param fn A function to be executed after delay milliseconds debounced.
  807. * @param ms A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
  808. * @param options Options
  809. *
  810. * @return A new, debounced, function with isPending, cancel, and flush properties.
  811. */
  812. function useDebounceFn(fn, ms = 200, options = {}) {
  813. return createFilterWrapper(debounceFilter(ms, options), fn);
  814. }
  815. //#endregion
  816. //#region refDebounced/index.ts
  817. /**
  818. * Debounce updates of a ref.
  819. *
  820. * @return A new debounced ref.
  821. */
  822. function refDebounced(value, ms = 200, options = {}) {
  823. const debounced = ref(toValue(value));
  824. const updater = useDebounceFn(() => {
  825. debounced.value = value.value;
  826. }, ms, options);
  827. watch(value, () => updater());
  828. return shallowReadonly(debounced);
  829. }
  830. /** @deprecated use `refDebounced` instead */
  831. const debouncedRef = refDebounced;
  832. /** @deprecated use `refDebounced` instead */
  833. const useDebounce = refDebounced;
  834. //#endregion
  835. //#region refDefault/index.ts
  836. /**
  837. * Apply default value to a ref.
  838. *
  839. * @__NO_SIDE_EFFECTS__
  840. */
  841. function refDefault(source, defaultValue) {
  842. return computed({
  843. get() {
  844. var _source$value;
  845. return (_source$value = source.value) !== null && _source$value !== void 0 ? _source$value : defaultValue;
  846. },
  847. set(value) {
  848. source.value = value;
  849. }
  850. });
  851. }
  852. //#endregion
  853. //#region refManualReset/index.ts
  854. /**
  855. * Create a ref with manual reset functionality.
  856. *
  857. * @see https://vueuse.org/refManualReset
  858. * @param defaultValue The value which will be set.
  859. */
  860. function refManualReset(defaultValue) {
  861. let value = toValue(defaultValue);
  862. let trigger;
  863. const reset = () => {
  864. value = toValue(defaultValue);
  865. trigger();
  866. };
  867. const refValue = customRef((track, _trigger) => {
  868. trigger = _trigger;
  869. return {
  870. get() {
  871. track();
  872. return value;
  873. },
  874. set(newValue) {
  875. value = newValue;
  876. trigger();
  877. }
  878. };
  879. });
  880. refValue.reset = reset;
  881. return refValue;
  882. }
  883. //#endregion
  884. //#region useThrottleFn/index.ts
  885. /**
  886. * Throttle execution of a function. Especially useful for rate limiting
  887. * execution of handlers on events like resize and scroll.
  888. *
  889. * @param fn A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,
  890. * to `callback` when the throttled-function is executed.
  891. * @param ms A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
  892. * (default value: 200)
  893. *
  894. * @param [trailing] if true, call fn again after the time is up (default value: true)
  895. *
  896. * @param [leading] if true, call fn on the leading edge of the ms timeout (default value: true)
  897. *
  898. * @param [rejectOnCancel] if true, reject the last call if it's been cancel (default value: false)
  899. *
  900. * @return A new, throttled, function.
  901. *
  902. * @__NO_SIDE_EFFECTS__
  903. */
  904. function useThrottleFn(fn, ms = 200, trailing = true, leading = true, rejectOnCancel = false) {
  905. return createFilterWrapper(throttleFilter(ms, trailing, leading, rejectOnCancel), fn);
  906. }
  907. //#endregion
  908. //#region refThrottled/index.ts
  909. /**
  910. * Throttle execution of a function. Especially useful for rate limiting
  911. * execution of handlers on events like resize and scroll.
  912. *
  913. * @param value Ref value to be watched with throttle effect
  914. * @param delay A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
  915. * @param trailing if true, update the value again after the delay time is up
  916. * @param leading if true, update the value on the leading edge of the ms timeout
  917. */
  918. function refThrottled(value, delay = 200, trailing = true, leading = true) {
  919. if (delay <= 0) return value;
  920. const throttled = ref(toValue(value));
  921. const updater = useThrottleFn(() => {
  922. throttled.value = value.value;
  923. }, delay, trailing, leading);
  924. watch(value, () => updater());
  925. return throttled;
  926. }
  927. /** @deprecated use `refThrottled` instead */
  928. const throttledRef = refThrottled;
  929. /** @deprecated use `refThrottled` instead */
  930. const useThrottle = refThrottled;
  931. //#endregion
  932. //#region refWithControl/index.ts
  933. /**
  934. * Fine-grained controls over ref and its reactivity.
  935. *
  936. * @__NO_SIDE_EFFECTS__
  937. */
  938. function refWithControl(initial, options = {}) {
  939. let source = initial;
  940. let track;
  941. let trigger;
  942. const ref = customRef((_track, _trigger) => {
  943. track = _track;
  944. trigger = _trigger;
  945. return {
  946. get() {
  947. return get();
  948. },
  949. set(v) {
  950. set(v);
  951. }
  952. };
  953. });
  954. function get(tracking = true) {
  955. if (tracking) track();
  956. return source;
  957. }
  958. function set(value, triggering = true) {
  959. var _options$onBeforeChan, _options$onChanged;
  960. if (value === source) return;
  961. const old = source;
  962. if (((_options$onBeforeChan = options.onBeforeChange) === null || _options$onBeforeChan === void 0 ? void 0 : _options$onBeforeChan.call(options, value, old)) === false) return;
  963. source = value;
  964. (_options$onChanged = options.onChanged) === null || _options$onChanged === void 0 || _options$onChanged.call(options, value, old);
  965. if (triggering) trigger();
  966. }
  967. /**
  968. * Get the value without tracked in the reactivity system
  969. */
  970. const untrackedGet = () => get(false);
  971. /**
  972. * Set the value without triggering the reactivity system
  973. */
  974. const silentSet = (v) => set(v, false);
  975. /**
  976. * Get the value without tracked in the reactivity system.
  977. *
  978. * Alias for `untrackedGet()`
  979. */
  980. const peek = () => get(false);
  981. /**
  982. * Set the value without triggering the reactivity system
  983. *
  984. * Alias for `silentSet(v)`
  985. */
  986. const lay = (v) => set(v, false);
  987. return extendRef(ref, {
  988. get,
  989. set,
  990. untrackedGet,
  991. silentSet,
  992. peek,
  993. lay
  994. }, { enumerable: true });
  995. }
  996. /** @deprecated use `refWithControl` instead */
  997. const controlledRef = refWithControl;
  998. //#endregion
  999. //#region set/index.ts
  1000. /**
  1001. * Shorthand for `ref.value = x`
  1002. */
  1003. function set(...args) {
  1004. if (args.length === 2) {
  1005. const [ref, value] = args;
  1006. ref.value = value;
  1007. }
  1008. if (args.length === 3) {
  1009. const [target, key, value] = args;
  1010. target[key] = value;
  1011. }
  1012. }
  1013. //#endregion
  1014. //#region watchWithFilter/index.ts
  1015. function watchWithFilter(source, cb, options = {}) {
  1016. const { eventFilter = bypassFilter, ...watchOptions } = options;
  1017. return watch(source, createFilterWrapper(eventFilter, cb), watchOptions);
  1018. }
  1019. //#endregion
  1020. //#region watchPausable/index.ts
  1021. /** @deprecated Use Vue's built-in `watch` instead. This function will be removed in future version. */
  1022. function watchPausable(source, cb, options = {}) {
  1023. const { eventFilter: filter, initialState = "active", ...watchOptions } = options;
  1024. const { eventFilter, pause, resume, isActive } = pausableFilter(filter, { initialState });
  1025. return {
  1026. stop: watchWithFilter(source, cb, {
  1027. ...watchOptions,
  1028. eventFilter
  1029. }),
  1030. pause,
  1031. resume,
  1032. isActive
  1033. };
  1034. }
  1035. /** @deprecated Use Vue's built-in `watch` instead. This function will be removed in future version. */
  1036. const pausableWatch = watchPausable;
  1037. //#endregion
  1038. //#region syncRef/index.ts
  1039. /**
  1040. * Two-way refs synchronization.
  1041. * From the set theory perspective to restrict the option's type
  1042. * Check in the following order:
  1043. * 1. L = R
  1044. * 2. L ∩ R ≠ ∅
  1045. * 3. L ⊆ R
  1046. * 4. L ∩ R = ∅
  1047. */
  1048. function syncRef(left, right, ...[options]) {
  1049. const { flush = "sync", deep = false, immediate = true, direction = "both", transform = {} } = options || {};
  1050. const watchers = [];
  1051. const transformLTR = "ltr" in transform && transform.ltr || ((v) => v);
  1052. const transformRTL = "rtl" in transform && transform.rtl || ((v) => v);
  1053. if (direction === "both" || direction === "ltr") watchers.push(watchPausable(left, (newValue) => {
  1054. watchers.forEach((w) => w.pause());
  1055. right.value = transformLTR(newValue);
  1056. watchers.forEach((w) => w.resume());
  1057. }, {
  1058. flush,
  1059. deep,
  1060. immediate
  1061. }));
  1062. if (direction === "both" || direction === "rtl") watchers.push(watchPausable(right, (newValue) => {
  1063. watchers.forEach((w) => w.pause());
  1064. left.value = transformRTL(newValue);
  1065. watchers.forEach((w) => w.resume());
  1066. }, {
  1067. flush,
  1068. deep,
  1069. immediate
  1070. }));
  1071. const stop = () => {
  1072. watchers.forEach((w) => w.stop());
  1073. };
  1074. return stop;
  1075. }
  1076. //#endregion
  1077. //#region syncRefs/index.ts
  1078. /**
  1079. * Keep target ref(s) in sync with the source ref
  1080. *
  1081. * @param source source ref
  1082. * @param targets
  1083. */
  1084. function syncRefs(source, targets, options = {}) {
  1085. const { flush = "sync", deep = false, immediate = true } = options;
  1086. const targetsArray = toArray(targets);
  1087. return watch(source, (newValue) => targetsArray.forEach((target) => target.value = newValue), {
  1088. flush,
  1089. deep,
  1090. immediate
  1091. });
  1092. }
  1093. //#endregion
  1094. //#region toRefs/index.ts
  1095. /**
  1096. * Extended `toRefs` that also accepts refs of an object.
  1097. *
  1098. * @see https://vueuse.org/toRefs
  1099. * @param objectRef A ref or normal object or array.
  1100. * @param options Options
  1101. */
  1102. function toRefs(objectRef, options = {}) {
  1103. if (!isRef(objectRef)) return toRefs$1(objectRef);
  1104. const result = Array.isArray(objectRef.value) ? Array.from({ length: objectRef.value.length }) : {};
  1105. for (const key in objectRef.value) result[key] = customRef(() => ({
  1106. get() {
  1107. return objectRef.value[key];
  1108. },
  1109. set(v) {
  1110. var _toValue;
  1111. if ((_toValue = toValue(options.replaceRef)) !== null && _toValue !== void 0 ? _toValue : true) {
  1112. if (Array.isArray(objectRef.value)) {
  1113. const copy = [...objectRef.value];
  1114. copy[key] = v;
  1115. objectRef.value = copy;
  1116. } else {
  1117. const newObject = {
  1118. ...objectRef.value,
  1119. [key]: v
  1120. };
  1121. Object.setPrototypeOf(newObject, Object.getPrototypeOf(objectRef.value));
  1122. objectRef.value = newObject;
  1123. }
  1124. } else objectRef.value[key] = v;
  1125. }
  1126. }));
  1127. return result;
  1128. }
  1129. //#endregion
  1130. //#region tryOnBeforeMount/index.ts
  1131. /**
  1132. * Call onBeforeMount() if it's inside a component lifecycle, if not, just call the function
  1133. *
  1134. * @param fn
  1135. * @param sync if set to false, it will run in the nextTick() of Vue
  1136. * @param target
  1137. */
  1138. function tryOnBeforeMount(fn, sync = true, target) {
  1139. if (getLifeCycleTarget(target)) onBeforeMount(fn, target);
  1140. else if (sync) fn();
  1141. else nextTick(fn);
  1142. }
  1143. //#endregion
  1144. //#region tryOnBeforeUnmount/index.ts
  1145. /**
  1146. * Call onBeforeUnmount() if it's inside a component lifecycle, if not, do nothing
  1147. *
  1148. * @param fn
  1149. * @param target
  1150. */
  1151. function tryOnBeforeUnmount(fn, target) {
  1152. if (getLifeCycleTarget(target)) onBeforeUnmount(fn, target);
  1153. }
  1154. //#endregion
  1155. //#region tryOnMounted/index.ts
  1156. /**
  1157. * Call onMounted() if it's inside a component lifecycle, if not, just call the function
  1158. *
  1159. * @param fn
  1160. * @param sync if set to false, it will run in the nextTick() of Vue
  1161. * @param target
  1162. */
  1163. function tryOnMounted(fn, sync = true, target) {
  1164. if (getLifeCycleTarget(target)) onMounted(fn, target);
  1165. else if (sync) fn();
  1166. else nextTick(fn);
  1167. }
  1168. //#endregion
  1169. //#region tryOnUnmounted/index.ts
  1170. /**
  1171. * Call onUnmounted() if it's inside a component lifecycle, if not, do nothing
  1172. *
  1173. * @param fn
  1174. * @param target
  1175. */
  1176. function tryOnUnmounted(fn, target) {
  1177. if (getLifeCycleTarget(target)) onUnmounted(fn, target);
  1178. }
  1179. //#endregion
  1180. //#region until/index.ts
  1181. function createUntil(r, isNot = false) {
  1182. function toMatch(condition, { flush = "sync", deep = false, timeout, throwOnTimeout } = {}) {
  1183. let stop = null;
  1184. const promises = [new Promise((resolve) => {
  1185. stop = watch(r, (v) => {
  1186. if (condition(v) !== isNot) {
  1187. if (stop) stop();
  1188. else nextTick(() => stop === null || stop === void 0 ? void 0 : stop());
  1189. resolve(v);
  1190. }
  1191. }, {
  1192. flush,
  1193. deep,
  1194. immediate: true
  1195. });
  1196. })];
  1197. if (timeout != null) promises.push(promiseTimeout(timeout, throwOnTimeout).then(() => toValue(r)).finally(() => stop === null || stop === void 0 ? void 0 : stop()));
  1198. return Promise.race(promises);
  1199. }
  1200. function toBe(value, options) {
  1201. if (!isRef(value)) return toMatch((v) => v === value, options);
  1202. const { flush = "sync", deep = false, timeout, throwOnTimeout } = options !== null && options !== void 0 ? options : {};
  1203. let stop = null;
  1204. const promises = [new Promise((resolve) => {
  1205. stop = watch([r, value], ([v1, v2]) => {
  1206. if (isNot !== (v1 === v2)) {
  1207. if (stop) stop();
  1208. else nextTick(() => stop === null || stop === void 0 ? void 0 : stop());
  1209. resolve(v1);
  1210. }
  1211. }, {
  1212. flush,
  1213. deep,
  1214. immediate: true
  1215. });
  1216. })];
  1217. if (timeout != null) promises.push(promiseTimeout(timeout, throwOnTimeout).then(() => toValue(r)).finally(() => {
  1218. stop === null || stop === void 0 || stop();
  1219. return toValue(r);
  1220. }));
  1221. return Promise.race(promises);
  1222. }
  1223. function toBeTruthy(options) {
  1224. return toMatch((v) => Boolean(v), options);
  1225. }
  1226. function toBeNull(options) {
  1227. return toBe(null, options);
  1228. }
  1229. function toBeUndefined(options) {
  1230. return toBe(void 0, options);
  1231. }
  1232. function toBeNaN(options) {
  1233. return toMatch(Number.isNaN, options);
  1234. }
  1235. function toContains(value, options) {
  1236. return toMatch((v) => {
  1237. const array = Array.from(v);
  1238. return array.includes(value) || array.includes(toValue(value));
  1239. }, options);
  1240. }
  1241. function changed(options) {
  1242. return changedTimes(1, options);
  1243. }
  1244. function changedTimes(n = 1, options) {
  1245. let count = -1;
  1246. return toMatch(() => {
  1247. count += 1;
  1248. return count >= n;
  1249. }, options);
  1250. }
  1251. if (Array.isArray(toValue(r))) return {
  1252. toMatch,
  1253. toContains,
  1254. changed,
  1255. changedTimes,
  1256. get not() {
  1257. return createUntil(r, !isNot);
  1258. }
  1259. };
  1260. else return {
  1261. toMatch,
  1262. toBe,
  1263. toBeTruthy,
  1264. toBeNull,
  1265. toBeNaN,
  1266. toBeUndefined,
  1267. changed,
  1268. changedTimes,
  1269. get not() {
  1270. return createUntil(r, !isNot);
  1271. }
  1272. };
  1273. }
  1274. function until(r) {
  1275. return createUntil(r);
  1276. }
  1277. //#endregion
  1278. //#region useArrayDifference/index.ts
  1279. function defaultComparator(value, othVal) {
  1280. return value === othVal;
  1281. }
  1282. /**
  1283. * Reactive get array difference of two array
  1284. * @see https://vueuse.org/useArrayDifference
  1285. * @returns - the difference of two array
  1286. * @param args
  1287. *
  1288. * @__NO_SIDE_EFFECTS__
  1289. */
  1290. function useArrayDifference(...args) {
  1291. var _args$, _args$2;
  1292. const list = args[0];
  1293. const values = args[1];
  1294. let compareFn = (_args$ = args[2]) !== null && _args$ !== void 0 ? _args$ : defaultComparator;
  1295. const { symmetric = false } = (_args$2 = args[3]) !== null && _args$2 !== void 0 ? _args$2 : {};
  1296. if (typeof compareFn === "string") {
  1297. const key = compareFn;
  1298. compareFn = (value, othVal) => value[key] === othVal[key];
  1299. }
  1300. const diff1 = computed(() => toValue(list).filter((x) => toValue(values).findIndex((y) => compareFn(x, y)) === -1));
  1301. if (symmetric) {
  1302. const diff2 = computed(() => toValue(values).filter((x) => toValue(list).findIndex((y) => compareFn(x, y)) === -1));
  1303. return computed(() => symmetric ? [...toValue(diff1), ...toValue(diff2)] : toValue(diff1));
  1304. } else return diff1;
  1305. }
  1306. //#endregion
  1307. //#region useArrayEvery/index.ts
  1308. /**
  1309. * Reactive `Array.every`
  1310. *
  1311. * @see https://vueuse.org/useArrayEvery
  1312. * @param list - the array was called upon.
  1313. * @param fn - a function to test each element.
  1314. *
  1315. * @returns **true** if the `fn` function returns a **truthy** value for every element from the array. Otherwise, **false**.
  1316. *
  1317. * @__NO_SIDE_EFFECTS__
  1318. */
  1319. function useArrayEvery(list, fn) {
  1320. return computed(() => toValue(list).every((element, index, array) => fn(toValue(element), index, array)));
  1321. }
  1322. //#endregion
  1323. //#region useArrayFilter/index.ts
  1324. /* @__NO_SIDE_EFFECTS__ */
  1325. function useArrayFilter(list, fn) {
  1326. return computed(() => toValue(list).map((i) => toValue(i)).filter(fn));
  1327. }
  1328. //#endregion
  1329. //#region useArrayFind/index.ts
  1330. /**
  1331. * Reactive `Array.find`
  1332. *
  1333. * @see https://vueuse.org/useArrayFind
  1334. * @param list - the array was called upon.
  1335. * @param fn - a function to test each element.
  1336. *
  1337. * @returns the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
  1338. *
  1339. * @__NO_SIDE_EFFECTS__
  1340. */
  1341. function useArrayFind(list, fn) {
  1342. return computed(() => toValue(toValue(list).find((element, index, array) => fn(toValue(element), index, array))));
  1343. }
  1344. //#endregion
  1345. //#region useArrayFindIndex/index.ts
  1346. /**
  1347. * Reactive `Array.findIndex`
  1348. *
  1349. * @see https://vueuse.org/useArrayFindIndex
  1350. * @param list - the array was called upon.
  1351. * @param fn - a function to test each element.
  1352. *
  1353. * @returns the index of the first element in the array that passes the test. Otherwise, "-1".
  1354. *
  1355. * @__NO_SIDE_EFFECTS__
  1356. */
  1357. function useArrayFindIndex(list, fn) {
  1358. return computed(() => toValue(list).findIndex((element, index, array) => fn(toValue(element), index, array)));
  1359. }
  1360. //#endregion
  1361. //#region useArrayFindLast/index.ts
  1362. function findLast(arr, cb) {
  1363. let index = arr.length;
  1364. while (index-- > 0) if (cb(arr[index], index, arr)) return arr[index];
  1365. }
  1366. /**
  1367. * Reactive `Array.findLast`
  1368. *
  1369. * @see https://vueuse.org/useArrayFindLast
  1370. * @param list - the array was called upon.
  1371. * @param fn - a function to test each element.
  1372. *
  1373. * @returns the last element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
  1374. *
  1375. * @__NO_SIDE_EFFECTS__
  1376. */
  1377. function useArrayFindLast(list, fn) {
  1378. 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))));
  1379. }
  1380. //#endregion
  1381. //#region useArrayIncludes/index.ts
  1382. function isArrayIncludesOptions(obj) {
  1383. return isObject(obj) && containsProp(obj, "formIndex", "comparator");
  1384. }
  1385. /* @__NO_SIDE_EFFECTS__ */
  1386. function useArrayIncludes(...args) {
  1387. var _comparator;
  1388. const list = args[0];
  1389. const value = args[1];
  1390. let comparator = args[2];
  1391. let formIndex = 0;
  1392. if (isArrayIncludesOptions(comparator)) {
  1393. var _comparator$fromIndex;
  1394. formIndex = (_comparator$fromIndex = comparator.fromIndex) !== null && _comparator$fromIndex !== void 0 ? _comparator$fromIndex : 0;
  1395. comparator = comparator.comparator;
  1396. }
  1397. if (typeof comparator === "string") {
  1398. const key = comparator;
  1399. comparator = (element, value) => element[key] === toValue(value);
  1400. }
  1401. comparator = (_comparator = comparator) !== null && _comparator !== void 0 ? _comparator : ((element, value) => element === toValue(value));
  1402. return computed(() => toValue(list).slice(formIndex).some((element, index, array) => comparator(toValue(element), toValue(value), index, toValue(array))));
  1403. }
  1404. //#endregion
  1405. //#region useArrayJoin/index.ts
  1406. /**
  1407. * Reactive `Array.join`
  1408. *
  1409. * @see https://vueuse.org/useArrayJoin
  1410. * @param list - the array was called upon.
  1411. * @param separator - a string to separate each pair of adjacent elements of the array. If omitted, the array elements are separated with a comma (",").
  1412. *
  1413. * @returns a string with all array elements joined. If arr.length is 0, the empty string is returned.
  1414. *
  1415. * @__NO_SIDE_EFFECTS__
  1416. */
  1417. function useArrayJoin(list, separator) {
  1418. return computed(() => toValue(list).map((i) => toValue(i)).join(toValue(separator)));
  1419. }
  1420. //#endregion
  1421. //#region useArrayMap/index.ts
  1422. /**
  1423. * Reactive `Array.map`
  1424. *
  1425. * @see https://vueuse.org/useArrayMap
  1426. * @param list - the array was called upon.
  1427. * @param fn - a function that is called for every element of the given `list`. Each time `fn` executes, the returned value is added to the new array.
  1428. *
  1429. * @returns a new array with each element being the result of the callback function.
  1430. *
  1431. * @__NO_SIDE_EFFECTS__
  1432. */
  1433. function useArrayMap(list, fn) {
  1434. return computed(() => toValue(list).map((i) => toValue(i)).map(fn));
  1435. }
  1436. //#endregion
  1437. //#region useArrayReduce/index.ts
  1438. /* @__NO_SIDE_EFFECTS__ */
  1439. function useArrayReduce(list, reducer, ...args) {
  1440. const reduceCallback = (sum, value, index) => reducer(toValue(sum), toValue(value), index);
  1441. return computed(() => {
  1442. const resolved = toValue(list);
  1443. return args.length ? resolved.reduce(reduceCallback, typeof args[0] === "function" ? toValue(args[0]()) : toValue(args[0])) : resolved.reduce(reduceCallback);
  1444. });
  1445. }
  1446. //#endregion
  1447. //#region useArraySome/index.ts
  1448. /**
  1449. * Reactive `Array.some`
  1450. *
  1451. * @see https://vueuse.org/useArraySome
  1452. * @param list - the array was called upon.
  1453. * @param fn - a function to test each element.
  1454. *
  1455. * @returns **true** if the `fn` function returns a **truthy** value for any element from the array. Otherwise, **false**.
  1456. *
  1457. * @__NO_SIDE_EFFECTS__
  1458. */
  1459. function useArraySome(list, fn) {
  1460. return computed(() => toValue(list).some((element, index, array) => fn(toValue(element), index, array)));
  1461. }
  1462. //#endregion
  1463. //#region useArrayUnique/index.ts
  1464. function uniq(array) {
  1465. return Array.from(new Set(array));
  1466. }
  1467. function uniqueElementsBy(array, fn) {
  1468. return array.reduce((acc, v) => {
  1469. if (!acc.some((x) => fn(v, x, array))) acc.push(v);
  1470. return acc;
  1471. }, []);
  1472. }
  1473. /**
  1474. * reactive unique array
  1475. * @see https://vueuse.org/useArrayUnique
  1476. * @param list - the array was called upon.
  1477. * @param compareFn
  1478. * @returns A computed ref that returns a unique array of items.
  1479. *
  1480. * @__NO_SIDE_EFFECTS__
  1481. */
  1482. function useArrayUnique(list, compareFn) {
  1483. return computed(() => {
  1484. const resolvedList = toValue(list).map((element) => toValue(element));
  1485. return compareFn ? uniqueElementsBy(resolvedList, compareFn) : uniq(resolvedList);
  1486. });
  1487. }
  1488. //#endregion
  1489. //#region useCounter/index.ts
  1490. /**
  1491. * Basic counter with utility functions.
  1492. *
  1493. * @see https://vueuse.org/useCounter
  1494. * @param [initialValue]
  1495. * @param options
  1496. */
  1497. function useCounter(initialValue = 0, options = {}) {
  1498. let _initialValue = unref(initialValue);
  1499. const count = shallowRef(initialValue);
  1500. const { max = Number.POSITIVE_INFINITY, min = Number.NEGATIVE_INFINITY } = options;
  1501. const inc = (delta = 1) => count.value = Math.max(Math.min(max, count.value + delta), min);
  1502. const dec = (delta = 1) => count.value = Math.min(Math.max(min, count.value - delta), max);
  1503. const get = () => count.value;
  1504. const set = (val) => count.value = Math.max(min, Math.min(max, val));
  1505. const reset = (val = _initialValue) => {
  1506. _initialValue = val;
  1507. return set(val);
  1508. };
  1509. return {
  1510. count: shallowReadonly(count),
  1511. inc,
  1512. dec,
  1513. get,
  1514. set,
  1515. reset
  1516. };
  1517. }
  1518. //#endregion
  1519. //#region useDateFormat/index.ts
  1520. const REGEX_PARSE = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[T\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/i;
  1521. 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;
  1522. function defaultMeridiem(hours, minutes, isLowercase, hasPeriod) {
  1523. let m = hours < 12 ? "AM" : "PM";
  1524. if (hasPeriod) m = m.split("").reduce((acc, curr) => acc += `${curr}.`, "");
  1525. return isLowercase ? m.toLowerCase() : m;
  1526. }
  1527. function formatOrdinal(num) {
  1528. const suffixes = [
  1529. "th",
  1530. "st",
  1531. "nd",
  1532. "rd"
  1533. ];
  1534. const v = num % 100;
  1535. return num + (suffixes[(v - 20) % 10] || suffixes[v] || suffixes[0]);
  1536. }
  1537. function formatDate(date, formatStr, options = {}) {
  1538. var _options$customMeridi;
  1539. const years = date.getFullYear();
  1540. const month = date.getMonth();
  1541. const days = date.getDate();
  1542. const hours = date.getHours();
  1543. const minutes = date.getMinutes();
  1544. const seconds = date.getSeconds();
  1545. const milliseconds = date.getMilliseconds();
  1546. const day = date.getDay();
  1547. const meridiem = (_options$customMeridi = options.customMeridiem) !== null && _options$customMeridi !== void 0 ? _options$customMeridi : defaultMeridiem;
  1548. const stripTimeZone = (dateString) => {
  1549. var _dateString$split$;
  1550. return (_dateString$split$ = dateString.split(" ")[1]) !== null && _dateString$split$ !== void 0 ? _dateString$split$ : "";
  1551. };
  1552. const matches = {
  1553. Yo: () => formatOrdinal(years),
  1554. YY: () => String(years).slice(-2),
  1555. YYYY: () => years,
  1556. M: () => month + 1,
  1557. Mo: () => formatOrdinal(month + 1),
  1558. MM: () => `${month + 1}`.padStart(2, "0"),
  1559. MMM: () => date.toLocaleDateString(toValue(options.locales), { month: "short" }),
  1560. MMMM: () => date.toLocaleDateString(toValue(options.locales), { month: "long" }),
  1561. D: () => String(days),
  1562. Do: () => formatOrdinal(days),
  1563. DD: () => `${days}`.padStart(2, "0"),
  1564. H: () => String(hours),
  1565. Ho: () => formatOrdinal(hours),
  1566. HH: () => `${hours}`.padStart(2, "0"),
  1567. h: () => `${hours % 12 || 12}`.padStart(1, "0"),
  1568. ho: () => formatOrdinal(hours % 12 || 12),
  1569. hh: () => `${hours % 12 || 12}`.padStart(2, "0"),
  1570. m: () => String(minutes),
  1571. mo: () => formatOrdinal(minutes),
  1572. mm: () => `${minutes}`.padStart(2, "0"),
  1573. s: () => String(seconds),
  1574. so: () => formatOrdinal(seconds),
  1575. ss: () => `${seconds}`.padStart(2, "0"),
  1576. SSS: () => `${milliseconds}`.padStart(3, "0"),
  1577. d: () => day,
  1578. dd: () => date.toLocaleDateString(toValue(options.locales), { weekday: "narrow" }),
  1579. ddd: () => date.toLocaleDateString(toValue(options.locales), { weekday: "short" }),
  1580. dddd: () => date.toLocaleDateString(toValue(options.locales), { weekday: "long" }),
  1581. A: () => meridiem(hours, minutes),
  1582. AA: () => meridiem(hours, minutes, false, true),
  1583. a: () => meridiem(hours, minutes, true),
  1584. aa: () => meridiem(hours, minutes, true, true),
  1585. z: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: "shortOffset" })),
  1586. zz: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: "shortOffset" })),
  1587. zzz: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: "shortOffset" })),
  1588. zzzz: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: "longOffset" }))
  1589. };
  1590. return formatStr.replace(REGEX_FORMAT, (match, $1) => {
  1591. var _ref, _matches$match;
  1592. 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;
  1593. });
  1594. }
  1595. function normalizeDate(date) {
  1596. if (date === null) return /* @__PURE__ */ new Date(NaN);
  1597. if (date === void 0) return /* @__PURE__ */ new Date();
  1598. if (date instanceof Date) return new Date(date);
  1599. if (typeof date === "string" && !/Z$/i.test(date)) {
  1600. const d = date.match(REGEX_PARSE);
  1601. if (d) {
  1602. const m = d[2] - 1 || 0;
  1603. const ms = (d[7] || "0").substring(0, 3);
  1604. return new Date(d[1], m, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, ms);
  1605. }
  1606. }
  1607. return new Date(date);
  1608. }
  1609. /**
  1610. * Get the formatted date according to the string of tokens passed in.
  1611. *
  1612. * @see https://vueuse.org/useDateFormat
  1613. * @param date - The date to format, can either be a `Date` object, a timestamp, or a string
  1614. * @param formatStr - The combination of tokens to format the date
  1615. * @param options - UseDateFormatOptions
  1616. *
  1617. * @__NO_SIDE_EFFECTS__
  1618. */
  1619. function useDateFormat(date, formatStr = "HH:mm:ss", options = {}) {
  1620. return computed(() => formatDate(normalizeDate(toValue(date)), toValue(formatStr), options));
  1621. }
  1622. //#endregion
  1623. //#region useIntervalFn/index.ts
  1624. /**
  1625. * Wrapper for `setInterval` with controls
  1626. *
  1627. * @see https://vueuse.org/useIntervalFn
  1628. * @param cb
  1629. * @param interval
  1630. * @param options
  1631. */
  1632. function useIntervalFn(cb, interval = 1e3, options = {}) {
  1633. const { immediate = true, immediateCallback = false } = options;
  1634. let timer = null;
  1635. const isActive = shallowRef(false);
  1636. function clean() {
  1637. if (timer) {
  1638. clearInterval(timer);
  1639. timer = null;
  1640. }
  1641. }
  1642. function pause() {
  1643. isActive.value = false;
  1644. clean();
  1645. }
  1646. function resume() {
  1647. const intervalValue = toValue(interval);
  1648. if (intervalValue <= 0) return;
  1649. isActive.value = true;
  1650. if (immediateCallback) cb();
  1651. clean();
  1652. if (isActive.value) timer = setInterval(cb, intervalValue);
  1653. }
  1654. if (immediate && isClient) resume();
  1655. if (isRef(interval) || typeof interval === "function") tryOnScopeDispose(watch(interval, () => {
  1656. if (isActive.value && isClient) resume();
  1657. }));
  1658. tryOnScopeDispose(pause);
  1659. return {
  1660. isActive: shallowReadonly(isActive),
  1661. pause,
  1662. resume
  1663. };
  1664. }
  1665. //#endregion
  1666. //#region useInterval/index.ts
  1667. function useInterval(interval = 1e3, options = {}) {
  1668. const { controls: exposeControls = false, immediate = true, callback } = options;
  1669. const counter = shallowRef(0);
  1670. const update = () => counter.value += 1;
  1671. const reset = () => {
  1672. counter.value = 0;
  1673. };
  1674. const controls = useIntervalFn(callback ? () => {
  1675. update();
  1676. callback(counter.value);
  1677. } : update, interval, { immediate });
  1678. if (exposeControls) return {
  1679. counter: shallowReadonly(counter),
  1680. reset,
  1681. ...controls
  1682. };
  1683. else return shallowReadonly(counter);
  1684. }
  1685. //#endregion
  1686. //#region useLastChanged/index.ts
  1687. function useLastChanged(source, options = {}) {
  1688. var _options$initialValue;
  1689. const ms = shallowRef((_options$initialValue = options.initialValue) !== null && _options$initialValue !== void 0 ? _options$initialValue : null);
  1690. watch(source, () => ms.value = timestamp(), options);
  1691. return shallowReadonly(ms);
  1692. }
  1693. //#endregion
  1694. //#region useTimeoutFn/index.ts
  1695. /**
  1696. * Wrapper for `setTimeout` with controls.
  1697. *
  1698. * @param cb
  1699. * @param interval
  1700. * @param options
  1701. */
  1702. function useTimeoutFn(cb, interval, options = {}) {
  1703. const { immediate = true, immediateCallback = false } = options;
  1704. const isPending = shallowRef(false);
  1705. let timer;
  1706. function clear() {
  1707. if (timer) {
  1708. clearTimeout(timer);
  1709. timer = void 0;
  1710. }
  1711. }
  1712. function stop() {
  1713. isPending.value = false;
  1714. clear();
  1715. }
  1716. function start(...args) {
  1717. if (immediateCallback) cb();
  1718. clear();
  1719. isPending.value = true;
  1720. timer = setTimeout(() => {
  1721. isPending.value = false;
  1722. timer = void 0;
  1723. cb(...args);
  1724. }, toValue(interval));
  1725. }
  1726. if (immediate) {
  1727. isPending.value = true;
  1728. if (isClient) start();
  1729. }
  1730. tryOnScopeDispose(stop);
  1731. return {
  1732. isPending: shallowReadonly(isPending),
  1733. start,
  1734. stop
  1735. };
  1736. }
  1737. //#endregion
  1738. //#region useTimeout/index.ts
  1739. function useTimeout(interval = 1e3, options = {}) {
  1740. const { controls: exposeControls = false, callback } = options;
  1741. const controls = useTimeoutFn(callback !== null && callback !== void 0 ? callback : noop, interval, options);
  1742. const ready = computed(() => !controls.isPending.value);
  1743. if (exposeControls) return {
  1744. ready,
  1745. ...controls
  1746. };
  1747. else return ready;
  1748. }
  1749. //#endregion
  1750. //#region useToNumber/index.ts
  1751. /**
  1752. * Reactively convert a string ref to number.
  1753. *
  1754. * @__NO_SIDE_EFFECTS__
  1755. */
  1756. function useToNumber(value, options = {}) {
  1757. const { method = "parseFloat", radix, nanToZero } = options;
  1758. return computed(() => {
  1759. let resolved = toValue(value);
  1760. if (typeof method === "function") resolved = method(resolved);
  1761. else if (typeof resolved === "string") resolved = Number[method](resolved, radix);
  1762. if (nanToZero && Number.isNaN(resolved)) resolved = 0;
  1763. return resolved;
  1764. });
  1765. }
  1766. //#endregion
  1767. //#region useToString/index.ts
  1768. /**
  1769. * Reactively convert a ref to string.
  1770. *
  1771. * @see https://vueuse.org/useToString
  1772. *
  1773. * @__NO_SIDE_EFFECTS__
  1774. */
  1775. function useToString(value) {
  1776. return computed(() => `${toValue(value)}`);
  1777. }
  1778. //#endregion
  1779. //#region useToggle/index.ts
  1780. /**
  1781. * A boolean ref with a toggler
  1782. *
  1783. * @see https://vueuse.org/useToggle
  1784. * @param [initialValue]
  1785. * @param options
  1786. *
  1787. * @__NO_SIDE_EFFECTS__
  1788. */
  1789. function useToggle(initialValue = false, options = {}) {
  1790. const { truthyValue = true, falsyValue = false } = options;
  1791. const valueIsRef = isRef(initialValue);
  1792. const _value = shallowRef(initialValue);
  1793. function toggle(value) {
  1794. if (arguments.length) {
  1795. _value.value = value;
  1796. return _value.value;
  1797. } else {
  1798. const truthy = toValue(truthyValue);
  1799. _value.value = _value.value === truthy ? toValue(falsyValue) : truthy;
  1800. return _value.value;
  1801. }
  1802. }
  1803. if (valueIsRef) return toggle;
  1804. else return [_value, toggle];
  1805. }
  1806. //#endregion
  1807. //#region watchArray/index.ts
  1808. /**
  1809. * Watch for an array with additions and removals.
  1810. *
  1811. * @see https://vueuse.org/watchArray
  1812. */
  1813. function watchArray(source, cb, options) {
  1814. let oldList = (options === null || options === void 0 ? void 0 : options.immediate) ? [] : [...typeof source === "function" ? source() : Array.isArray(source) ? source : toValue(source)];
  1815. return watch(source, (newList, _, onCleanup) => {
  1816. const oldListRemains = Array.from({ length: oldList.length });
  1817. const added = [];
  1818. for (const obj of newList) {
  1819. let found = false;
  1820. for (let i = 0; i < oldList.length; i++) if (!oldListRemains[i] && obj === oldList[i]) {
  1821. oldListRemains[i] = true;
  1822. found = true;
  1823. break;
  1824. }
  1825. if (!found) added.push(obj);
  1826. }
  1827. const removed = oldList.filter((_, i) => !oldListRemains[i]);
  1828. cb(newList, oldList, added, removed, onCleanup);
  1829. oldList = [...newList];
  1830. }, options);
  1831. }
  1832. //#endregion
  1833. //#region watchAtMost/index.ts
  1834. function watchAtMost(source, cb, options) {
  1835. const { count, ...watchOptions } = options;
  1836. const current = shallowRef(0);
  1837. const { stop, resume, pause } = watchWithFilter(source, (...args) => {
  1838. current.value += 1;
  1839. if (current.value >= toValue(count)) nextTick(() => stop());
  1840. cb(...args);
  1841. }, watchOptions);
  1842. return {
  1843. count: current,
  1844. stop,
  1845. resume,
  1846. pause
  1847. };
  1848. }
  1849. //#endregion
  1850. //#region watchDebounced/index.ts
  1851. function watchDebounced(source, cb, options = {}) {
  1852. const { debounce = 0, maxWait = void 0, ...watchOptions } = options;
  1853. return watchWithFilter(source, cb, {
  1854. ...watchOptions,
  1855. eventFilter: debounceFilter(debounce, { maxWait })
  1856. });
  1857. }
  1858. /** @deprecated use `watchDebounced` instead */
  1859. const debouncedWatch = watchDebounced;
  1860. //#endregion
  1861. //#region watchDeep/index.ts
  1862. /**
  1863. * Shorthand for watching value with {deep: true}
  1864. *
  1865. * @see https://vueuse.org/watchDeep
  1866. */
  1867. function watchDeep(source, cb, options) {
  1868. return watch(source, cb, {
  1869. ...options,
  1870. deep: true
  1871. });
  1872. }
  1873. //#endregion
  1874. //#region watchIgnorable/index.ts
  1875. function watchIgnorable(source, cb, options = {}) {
  1876. const { eventFilter = bypassFilter, ...watchOptions } = options;
  1877. const filteredCb = createFilterWrapper(eventFilter, cb);
  1878. let ignoreUpdates;
  1879. let ignorePrevAsyncUpdates;
  1880. let stop;
  1881. if (watchOptions.flush === "sync") {
  1882. let ignore = false;
  1883. ignorePrevAsyncUpdates = () => {};
  1884. ignoreUpdates = (updater) => {
  1885. ignore = true;
  1886. updater();
  1887. ignore = false;
  1888. };
  1889. stop = watch(source, (...args) => {
  1890. if (!ignore) filteredCb(...args);
  1891. }, watchOptions);
  1892. } else {
  1893. const disposables = [];
  1894. let ignoreCounter = 0;
  1895. let syncCounter = 0;
  1896. ignorePrevAsyncUpdates = () => {
  1897. ignoreCounter = syncCounter;
  1898. };
  1899. disposables.push(watch(source, () => {
  1900. syncCounter++;
  1901. }, {
  1902. ...watchOptions,
  1903. flush: "sync"
  1904. }));
  1905. ignoreUpdates = (updater) => {
  1906. const syncCounterPrev = syncCounter;
  1907. updater();
  1908. ignoreCounter += syncCounter - syncCounterPrev;
  1909. };
  1910. disposables.push(watch(source, (...args) => {
  1911. const ignore = ignoreCounter > 0 && ignoreCounter === syncCounter;
  1912. ignoreCounter = 0;
  1913. syncCounter = 0;
  1914. if (ignore) return;
  1915. filteredCb(...args);
  1916. }, watchOptions));
  1917. stop = () => {
  1918. disposables.forEach((fn) => fn());
  1919. };
  1920. }
  1921. return {
  1922. stop,
  1923. ignoreUpdates,
  1924. ignorePrevAsyncUpdates
  1925. };
  1926. }
  1927. /** @deprecated use `watchIgnorable` instead */
  1928. const ignorableWatch = watchIgnorable;
  1929. //#endregion
  1930. //#region watchImmediate/index.ts
  1931. /**
  1932. * Shorthand for watching value with {immediate: true}
  1933. *
  1934. * @see https://vueuse.org/watchImmediate
  1935. */
  1936. function watchImmediate(source, cb, options) {
  1937. return watch(source, cb, {
  1938. ...options,
  1939. immediate: true
  1940. });
  1941. }
  1942. //#endregion
  1943. //#region watchOnce/index.ts
  1944. /**
  1945. * Shorthand for watching value with { once: true }
  1946. *
  1947. * @see https://vueuse.org/watchOnce
  1948. */
  1949. function watchOnce(source, cb, options) {
  1950. return watch(source, cb, {
  1951. ...options,
  1952. once: true
  1953. });
  1954. }
  1955. //#endregion
  1956. //#region watchThrottled/index.ts
  1957. function watchThrottled(source, cb, options = {}) {
  1958. const { throttle = 0, trailing = true, leading = true, ...watchOptions } = options;
  1959. return watchWithFilter(source, cb, {
  1960. ...watchOptions,
  1961. eventFilter: throttleFilter(throttle, trailing, leading)
  1962. });
  1963. }
  1964. /** @deprecated use `watchThrottled` instead */
  1965. const throttledWatch = watchThrottled;
  1966. //#endregion
  1967. //#region watchTriggerable/index.ts
  1968. function watchTriggerable(source, cb, options = {}) {
  1969. let cleanupFn;
  1970. function onEffect() {
  1971. if (!cleanupFn) return;
  1972. const fn = cleanupFn;
  1973. cleanupFn = void 0;
  1974. fn();
  1975. }
  1976. /** Register the function `cleanupFn` */
  1977. function onCleanup(callback) {
  1978. cleanupFn = callback;
  1979. }
  1980. const _cb = (value, oldValue) => {
  1981. onEffect();
  1982. return cb(value, oldValue, onCleanup);
  1983. };
  1984. const res = watchIgnorable(source, _cb, options);
  1985. const { ignoreUpdates } = res;
  1986. const trigger = () => {
  1987. let res;
  1988. ignoreUpdates(() => {
  1989. res = _cb(getWatchSources(source), getOldValue(source));
  1990. });
  1991. return res;
  1992. };
  1993. return {
  1994. ...res,
  1995. trigger
  1996. };
  1997. }
  1998. function getWatchSources(sources) {
  1999. if (isReactive(sources)) return sources;
  2000. if (Array.isArray(sources)) return sources.map((item) => toValue(item));
  2001. return toValue(sources);
  2002. }
  2003. function getOldValue(source) {
  2004. return Array.isArray(source) ? source.map(() => void 0) : void 0;
  2005. }
  2006. //#endregion
  2007. //#region whenever/index.ts
  2008. function whenever(source, cb, options) {
  2009. const stop = watch(source, (v, ov, onInvalidate) => {
  2010. if (v) {
  2011. if (options === null || options === void 0 ? void 0 : options.once) nextTick(() => stop());
  2012. cb(v, ov, onInvalidate);
  2013. }
  2014. }, {
  2015. ...options,
  2016. once: false
  2017. });
  2018. return stop;
  2019. }
  2020. //#endregion
  2021. export { assert, autoResetRef, bypassFilter, camelize, clamp, computedEager, computedWithControl, containsProp, controlledComputed, controlledRef, createDisposableDirective, createEventHook, createFilterWrapper, createGlobalState, createInjectionState, createReactiveFn, createRef, createSharedComposable, createSingletonPromise, debounceFilter, debouncedRef, debouncedWatch, eagerComputed, extendRef, formatDate, get, getLifeCycleTarget, hasOwn, hyphenate, identity, ignorableWatch, increaseWithUnit, injectLocal, invoke, isClient, isDef, isDefined, isIOS, isObject, isWorker, makeDestructurable, noop, normalizeDate, notNullish, now, objectEntries, objectOmit, objectPick, pausableFilter, pausableWatch, promiseTimeout, provideLocal, pxValue, rand, reactify, reactifyObject, reactiveComputed, reactiveOmit, reactivePick, refAutoReset, refDebounced, refDefault, refManualReset, refThrottled, refWithControl, set, syncRef, syncRefs, throttleFilter, throttledRef, throttledWatch, timestamp, toArray, toReactive, toRef, toRefs, tryOnBeforeMount, tryOnBeforeUnmount, tryOnMounted, tryOnScopeDispose, tryOnUnmounted, until, useArrayDifference, useArrayEvery, useArrayFilter, useArrayFind, useArrayFindIndex, useArrayFindLast, useArrayIncludes, useArrayJoin, useArrayMap, useArrayReduce, useArraySome, useArrayUnique, useCounter, useDateFormat, useDebounce, useDebounceFn, useInterval, useIntervalFn, useLastChanged, useThrottle, useThrottleFn, useTimeout, useTimeoutFn, useToNumber, useToString, useToggle, watchArray, watchAtMost, watchDebounced, watchDeep, watchIgnorable, watchImmediate, watchOnce, watchPausable, watchThrottled, watchTriggerable, watchWithFilter, whenever };