From 350ad5924054c993a2d126029ece03f8ec5053b7 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Thu, 7 Jul 2022 01:51:58 +0800 Subject: [PATCH 01/23] feat(all): use `MaybeComputedRef` --- packages/core/onKeyStroke/index.ts | 4 +- packages/core/unrefElement/index.ts | 9 +++-- packages/core/useBase64/index.ts | 28 +++++++------- packages/core/useClamp/index.ts | 12 +++--- packages/core/useCssVar/index.ts | 11 +++--- packages/core/useCycleList/index.ts | 3 +- packages/core/useDebouncedRefHistory/index.ts | 4 +- packages/core/useDropZone/index.ts | 4 +- packages/core/useElementByPoint/index.ts | 11 +++--- packages/core/useElementSize/index.ts | 5 ++- packages/core/useElementVisibility/index.ts | 22 ++++++----- packages/core/useEventListener/index.ts | 38 +++++++++++++++---- packages/core/useResizeObserver/index.ts | 4 +- packages/core/useScreenOrientation/index.ts | 1 - packages/core/useTitle/index.ts | 37 +++++++++++++----- packages/shared/resolveRef/index.ts | 1 + packages/shared/utils/filters.ts | 21 +++++----- 17 files changed, 133 insertions(+), 82 deletions(-) diff --git a/packages/core/onKeyStroke/index.ts b/packages/core/onKeyStroke/index.ts index 37acac2e2d4..d5f94149df8 100644 --- a/packages/core/onKeyStroke/index.ts +++ b/packages/core/onKeyStroke/index.ts @@ -1,4 +1,4 @@ -import type { MaybeRef } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' import { useEventListener } from '../useEventListener' import { defaultWindow } from '../_configurable' @@ -7,7 +7,7 @@ export type KeyFilter = null | undefined | string | string[] | KeyPredicate export type KeyStrokeEventName = 'keydown' | 'keypress' | 'keyup' export interface KeyStrokeOptions { eventName?: KeyStrokeEventName - target?: MaybeRef + target?: MaybeComputedRef passive?: boolean } diff --git a/packages/core/unrefElement/index.ts b/packages/core/unrefElement/index.ts index 712be030647..0abe15ea35a 100644 --- a/packages/core/unrefElement/index.ts +++ b/packages/core/unrefElement/index.ts @@ -1,9 +1,10 @@ import type { ComponentPublicInstance } from 'vue-demi' -import { unref } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' +import type { MaybeComputedRef, MaybeRef } from '@vueuse/shared' +import { resolveUnref } from '@vueuse/shared' export type VueInstance = ComponentPublicInstance export type MaybeElementRef = MaybeRef +export type MaybeComputedElementRef = MaybeComputedRef export type MaybeElement = HTMLElement | SVGElement | VueInstance | undefined | null export type UnRefElementReturn = T extends VueInstance ? Exclude : T | undefined @@ -13,7 +14,7 @@ export type UnRefElementReturn = T extend * * @param elRef */ -export function unrefElement(elRef: MaybeElementRef): UnRefElementReturn { - const plain = unref(elRef) +export function unrefElement(elRef: MaybeComputedElementRef): UnRefElementReturn { + const plain = resolveUnref(elRef) return (plain as VueInstance)?.$el ?? plain } diff --git a/packages/core/useBase64/index.ts b/packages/core/useBase64/index.ts index d8a5bde7f40..d8c2165de15 100644 --- a/packages/core/useBase64/index.ts +++ b/packages/core/useBase64/index.ts @@ -1,7 +1,7 @@ import type { Ref } from 'vue-demi' -import { isRef, ref, unref, watch } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' -import { isClient } from '@vueuse/shared' +import { isRef, ref, watch } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { isClient, isFunction, resolveUnref } from '@vueuse/shared' import { getDefaultSerialization } from './serialization' export interface ToDataURLOptions { @@ -25,15 +25,15 @@ export interface UseBase64Return { execute: () => Promise } -export function useBase64(target: MaybeRef): UseBase64Return -export function useBase64(target: MaybeRef): UseBase64Return -export function useBase64(target: MaybeRef): UseBase64Return -export function useBase64(target: MaybeRef, options?: ToDataURLOptions): UseBase64Return -export function useBase64(target: MaybeRef, options?: ToDataURLOptions): UseBase64Return -export function useBase64>(target: MaybeRef, options?: UseBase64ObjectOptions): UseBase64Return -export function useBase64>(target: MaybeRef, options?: UseBase64ObjectOptions): UseBase64Return -export function useBase64>(target: MaybeRef, options?: UseBase64ObjectOptions): UseBase64Return -export function useBase64(target: MaybeRef, options?: UseBase64ObjectOptions): UseBase64Return +export function useBase64(target: MaybeComputedRef): UseBase64Return +export function useBase64(target: MaybeComputedRef): UseBase64Return +export function useBase64(target: MaybeComputedRef): UseBase64Return +export function useBase64(target: MaybeComputedRef, options?: ToDataURLOptions): UseBase64Return +export function useBase64(target: MaybeComputedRef, options?: ToDataURLOptions): UseBase64Return +export function useBase64>(target: MaybeComputedRef, options?: UseBase64ObjectOptions): UseBase64Return +export function useBase64>(target: MaybeComputedRef, options?: UseBase64ObjectOptions): UseBase64Return +export function useBase64>(target: MaybeComputedRef, options?: UseBase64ObjectOptions): UseBase64Return +export function useBase64(target: MaybeComputedRef, options?: UseBase64ObjectOptions): UseBase64Return export function useBase64( target: any, options?: any, @@ -47,7 +47,7 @@ export function useBase64( promise.value = new Promise((resolve, reject) => { try { - const _target = unref(target) + const _target = resolveUnref(target) if (_target == null) { resolve('') } @@ -94,7 +94,7 @@ export function useBase64( return promise.value } - if (isRef(target)) + if (isRef(target) || isFunction(target)) watch(target, execute, { immediate: true }) else execute() diff --git a/packages/core/useClamp/index.ts b/packages/core/useClamp/index.ts index 7bf2c37ec9c..ab34751a747 100644 --- a/packages/core/useClamp/index.ts +++ b/packages/core/useClamp/index.ts @@ -1,7 +1,7 @@ import type { Ref } from 'vue-demi' -import { computed, ref, unref } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' -import { clamp } from '@vueuse/shared' +import { computed, ref } from 'vue-demi' +import type { MaybeComputedRef, MaybeRef } from '@vueuse/shared' +import { clamp, resolveUnref } from '@vueuse/shared' /** * Reactively clamp a value between two other values. @@ -11,14 +11,14 @@ import { clamp } from '@vueuse/shared' * @param min * @param max */ -export function useClamp(value: MaybeRef, min: MaybeRef, max: MaybeRef): Ref { +export function useClamp(value: MaybeRef, min: MaybeComputedRef, max: MaybeComputedRef): Ref { const _value = ref(value) return computed({ get() { - return _value.value = clamp(_value.value, unref(min), unref(max)) + return _value.value = clamp(_value.value, resolveUnref(min), resolveUnref(max)) }, set(value) { - _value.value = clamp(value, unref(min), unref(max)) + _value.value = clamp(value, resolveUnref(min), resolveUnref(max)) }, }) } diff --git a/packages/core/useCssVar/index.ts b/packages/core/useCssVar/index.ts index 424eb6cdfd2..bf546302c8d 100644 --- a/packages/core/useCssVar/index.ts +++ b/packages/core/useCssVar/index.ts @@ -1,5 +1,6 @@ -import { computed, ref, unref, watch } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' +import { computed, ref, watch } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveUnref } from '@vueuse/shared' import type { ConfigurableWindow } from '../_configurable' import { defaultWindow } from '../_configurable' import type { MaybeElementRef } from '../unrefElement' @@ -19,7 +20,7 @@ export interface UseCssVarOptions extends ConfigurableWindow { * @param options */ export function useCssVar( - prop: MaybeRef, + prop: MaybeComputedRef, target?: MaybeElementRef, { window = defaultWindow, initialValue = '' }: UseCssVarOptions = {}, ) { @@ -27,7 +28,7 @@ export function useCssVar( const elRef = computed(() => unrefElement(target) || window?.document?.documentElement) watch( - [elRef, () => unref(prop)], + [elRef, () => resolveUnref(prop)], ([el, prop]) => { if (el && window) { const value = window.getComputedStyle(el).getPropertyValue(prop)?.trim() @@ -41,7 +42,7 @@ export function useCssVar( variable, (val) => { if (elRef.value?.style) - elRef.value.style.setProperty(unref(prop), val) + elRef.value.style.setProperty(resolveUnref(prop), val) }, ) diff --git a/packages/core/useCycleList/index.ts b/packages/core/useCycleList/index.ts index 01cecbf19a4..718bfb2261d 100644 --- a/packages/core/useCycleList/index.ts +++ b/packages/core/useCycleList/index.ts @@ -1,13 +1,12 @@ import type { Ref } from 'vue-demi' import { computed, shallowRef } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' export interface UseCycleListOptions { /** * The initial value of the state. * A ref can be provided to reuse. */ - initialValue?: MaybeRef + initialValue?: T /** * The default index when diff --git a/packages/core/useDebouncedRefHistory/index.ts b/packages/core/useDebouncedRefHistory/index.ts index 92e3e3ed767..54db46209ea 100644 --- a/packages/core/useDebouncedRefHistory/index.ts +++ b/packages/core/useDebouncedRefHistory/index.ts @@ -1,4 +1,4 @@ -import type { MaybeRef } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' import { debounceFilter } from '@vueuse/shared' import type { Ref } from 'vue-demi' import type { UseRefHistoryOptions, UseRefHistoryReturn } from '../useRefHistory' @@ -13,7 +13,7 @@ import { useRefHistory } from '../useRefHistory' */ export function useDebouncedRefHistory( source: Ref, - options: Omit, 'eventFilter'> & { debounce?: MaybeRef } = {}, + options: Omit, 'eventFilter'> & { debounce?: MaybeComputedRef } = {}, ): UseRefHistoryReturn { const filter = options.debounce ? debounceFilter(options.debounce) : undefined const history = useRefHistory(source, { ...options, eventFilter: filter }) diff --git a/packages/core/useDropZone/index.ts b/packages/core/useDropZone/index.ts index 219a9f14d99..9c8b78c14b7 100644 --- a/packages/core/useDropZone/index.ts +++ b/packages/core/useDropZone/index.ts @@ -1,6 +1,6 @@ import { ref } from 'vue-demi' import type { Ref } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' import { isClient } from '@vueuse/shared' import { useEventListener } from '../useEventListener' @@ -8,7 +8,7 @@ export interface UseDropZoneReturn { isOverDropZone: Ref } -export function useDropZone(target: MaybeRef, onDrop: (files: File[] | null) => void): UseDropZoneReturn { +export function useDropZone(target: MaybeComputedRef, onDrop: (files: File[] | null) => void): UseDropZoneReturn { const isOverDropZone = ref(false) let counter = 0 diff --git a/packages/core/useElementByPoint/index.ts b/packages/core/useElementByPoint/index.ts index ed44a6151aa..8e29da2d15d 100644 --- a/packages/core/useElementByPoint/index.ts +++ b/packages/core/useElementByPoint/index.ts @@ -1,10 +1,11 @@ -import { ref, unref } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' +import { ref } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveUnref } from '@vueuse/shared' import { useRafFn } from '../useRafFn' export interface UseElementByPointOptions { - x: MaybeRef - y: MaybeRef + x: MaybeComputedRef + y: MaybeComputedRef } /** @@ -19,7 +20,7 @@ export function useElementByPoint(options: UseElementByPointOptions) { const { x, y } = options const controls = useRafFn(() => { - element.value = document.elementFromPoint(unref(x), unref(y)) as HTMLElement | null + element.value = document.elementFromPoint(resolveUnref(x), resolveUnref(y)) as HTMLElement | null }) return { diff --git a/packages/core/useElementSize/index.ts b/packages/core/useElementSize/index.ts index c9422f6a3c8..8d53a30c345 100644 --- a/packages/core/useElementSize/index.ts +++ b/packages/core/useElementSize/index.ts @@ -1,8 +1,9 @@ import { ref, watch } from 'vue-demi' -import type { MaybeElementRef } from '../unrefElement' +import type { MaybeComputedElementRef } from '../unrefElement' import type { ResizeObserverOptions } from '../useResizeObserver' import { useResizeObserver } from '../useResizeObserver' import { unrefElement } from '../unrefElement' + export interface ElementSize { width: number height: number @@ -17,7 +18,7 @@ export interface ElementSize { * @param options */ export function useElementSize( - target: MaybeElementRef, + target: MaybeComputedElementRef, initialSize: ElementSize = { width: 0, height: 0 }, options: ResizeObserverOptions = {}, ) { diff --git a/packages/core/useElementVisibility/index.ts b/packages/core/useElementVisibility/index.ts index 15bf85d67b3..4a9d876d7a5 100644 --- a/packages/core/useElementVisibility/index.ts +++ b/packages/core/useElementVisibility/index.ts @@ -1,12 +1,13 @@ -import type { MaybeRef } from '@vueuse/shared' -import { tryOnMounted } from '@vueuse/shared' -import { ref, unref } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveUnref, tryOnMounted } from '@vueuse/shared' +import { ref } from 'vue-demi' +import type { MaybeComputedElementRef } from '../unrefElement' import { useEventListener } from '../useEventListener' import type { ConfigurableWindow } from '../_configurable' import { defaultWindow } from '../_configurable' export interface VisibilityScrollTargetOptions extends ConfigurableWindow { - scrollTarget?: MaybeRef + scrollTarget?: MaybeComputedRef } /** @@ -17,7 +18,7 @@ export interface VisibilityScrollTargetOptions extends ConfigurableWindow { * @param options */ export function useElementVisibility( - element: MaybeRef, + element: MaybeComputedElementRef, { window = defaultWindow, scrollTarget }: VisibilityScrollTargetOptions = {}, ) { const elementIsVisible = ref(false) @@ -27,11 +28,12 @@ export function useElementVisibility( return const document = window.document - if (!unref(element)) { + const el = resolveUnref(element) + if (!el) { elementIsVisible.value = false } else { - const rect = (unref(element) as HTMLElement).getBoundingClientRect() + const rect = (el as HTMLElement).getBoundingClientRect() elementIsVisible.value = ( rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth) @@ -43,8 +45,10 @@ export function useElementVisibility( tryOnMounted(testBounding) - if (window) - tryOnMounted(() => useEventListener(unref(scrollTarget) || window, 'scroll', testBounding, { capture: false, passive: true })) + if (window) { + tryOnMounted(() => useEventListener( + () => resolveUnref(scrollTarget) || window, 'scroll', testBounding, { capture: false, passive: true })) + } return elementIsVisible } diff --git a/packages/core/useEventListener/index.ts b/packages/core/useEventListener/index.ts index 1ba3f847924..a321ae7334e 100644 --- a/packages/core/useEventListener/index.ts +++ b/packages/core/useEventListener/index.ts @@ -1,4 +1,4 @@ -import type { Fn, MaybeRef } from '@vueuse/shared' +import type { Fn, MaybeComputedRef } from '@vueuse/shared' import { isString, noop, tryOnScopeDispose } from '@vueuse/shared' import { watch } from 'vue-demi' import type { MaybeElementRef } from '../unrefElement' @@ -27,7 +27,11 @@ export interface GeneralEventListener { * @param listener * @param options */ -export function useEventListener(event: E, listener: (this: Window, ev: WindowEventMap[E]) => any, options?: boolean | AddEventListenerOptions): Fn +export function useEventListener( + event: E, + listener: (this: Window, ev: WindowEventMap[E]) => any, + options?: boolean | AddEventListenerOptions +): Fn /** * Register using addEventListener on mounted, and removeEventListener automatically on unmounted. @@ -40,7 +44,12 @@ export function useEventListener(event: E, liste * @param listener * @param options */ -export function useEventListener(target: Window, event: E, listener: (this: Window, ev: WindowEventMap[E]) => any, options?: boolean | AddEventListenerOptions): Fn +export function useEventListener( + target: Window, + event: E, + listener: (this: Window, ev: WindowEventMap[E]) => any, + options?: boolean | AddEventListenerOptions +): Fn /** * Register using addEventListener on mounted, and removeEventListener automatically on unmounted. @@ -53,7 +62,12 @@ export function useEventListener(target: Window, * @param listener * @param options */ -export function useEventListener(target: Document, event: E, listener: (this: Document, ev: DocumentEventMap[E]) => any, options?: boolean | AddEventListenerOptions): Fn +export function useEventListener( + target: Document, + event: E, + listener: (this: Document, ev: DocumentEventMap[E]) => any, + options?: boolean | AddEventListenerOptions +): Fn /** * Register using addEventListener on mounted, and removeEventListener automatically on unmounted. @@ -66,7 +80,12 @@ export function useEventListener(target: Docum * @param listener * @param options */ -export function useEventListener(target: InferEventTarget, event: Names, listener: GeneralEventListener, options?: boolean | AddEventListenerOptions): Fn +export function useEventListener( + target: InferEventTarget, + event: Names, + listener: GeneralEventListener, + options?: boolean | AddEventListenerOptions +): Fn /** * Register using addEventListener on mounted, and removeEventListener automatically on unmounted. @@ -79,10 +98,15 @@ export function useEventListener(target * @param listener * @param options */ -export function useEventListener(target: MaybeRef, event: string, listener: GeneralEventListener, options?: boolean | AddEventListenerOptions): Fn +export function useEventListener( + target: MaybeComputedRef, + event: string, + listener: GeneralEventListener, + options?: boolean | AddEventListenerOptions +): Fn export function useEventListener(...args: any[]) { - let target: MaybeRef | undefined + let target: MaybeComputedRef | undefined let event: string let listener: any let options: any diff --git a/packages/core/useResizeObserver/index.ts b/packages/core/useResizeObserver/index.ts index 6b15d3ff3c2..eb07afed98b 100644 --- a/packages/core/useResizeObserver/index.ts +++ b/packages/core/useResizeObserver/index.ts @@ -1,6 +1,6 @@ import { tryOnScopeDispose } from '@vueuse/shared' import { watch } from 'vue-demi' -import type { MaybeElementRef } from '../unrefElement' +import type { MaybeComputedElementRef } from '../unrefElement' import { unrefElement } from '../unrefElement' import type { ConfigurableWindow } from '../_configurable' import { defaultWindow } from '../_configurable' @@ -46,7 +46,7 @@ declare class ResizeObserver { * @param options */ export function useResizeObserver( - target: MaybeElementRef, + target: MaybeComputedElementRef, callback: ResizeObserverCallback, options: ResizeObserverOptions = {}, ) { diff --git a/packages/core/useScreenOrientation/index.ts b/packages/core/useScreenOrientation/index.ts index ecb4d583745..6ef91e043f8 100644 --- a/packages/core/useScreenOrientation/index.ts +++ b/packages/core/useScreenOrientation/index.ts @@ -4,7 +4,6 @@ import type { ConfigurableWindow } from '../_configurable' import { defaultWindow } from '../_configurable' /** - * * Reactive screen orientation * * @see https://vueuse.org/useScreenOrientation diff --git a/packages/core/useTitle/index.ts b/packages/core/useTitle/index.ts index a416590b4dc..bc9c7f16519 100644 --- a/packages/core/useTitle/index.ts +++ b/packages/core/useTitle/index.ts @@ -1,6 +1,7 @@ -import type { MaybeRef } from '@vueuse/shared' -import { isString } from '@vueuse/shared' -import { ref, watch } from 'vue-demi' +import type { MaybeComputedRef, MaybeRef } from '@vueuse/shared' +import { isFunction, isString, resolveRef } from '@vueuse/shared' +import type { ComputedRef, Ref } from 'vue-demi' +import { unref, watch } from 'vue-demi' import type { ConfigurableDocument } from '../_configurable' import { defaultDocument } from '../_configurable' import { useMutationObserver } from '../useMutationObserver' @@ -17,9 +18,19 @@ export interface UseTitleOptions extends ConfigurableDocument { * * @default '%s' */ - titleTemplate?: string + titleTemplate?: MaybeRef | ((title: string) => string) } +export function useTitle( + newTitle?: MaybeRef, + options?: UseTitleOptions, +): Ref + +export function useTitle( + newTitle?: MaybeComputedRef, + options?: UseTitleOptions, +): ComputedRef + /** * Reactive document title. * @@ -28,7 +39,7 @@ export interface UseTitleOptions extends ConfigurableDocument { * @param options */ export function useTitle( - newTitle: MaybeRef = null, + newTitle: MaybeComputedRef = null, options: UseTitleOptions = {}, ) { const { @@ -36,23 +47,31 @@ export function useTitle( observe = false, titleTemplate = '%s', } = options - const title = ref(newTitle ?? document?.title ?? null) + + const title = resolveRef(newTitle ?? document?.title ?? null) as Ref + const isReadonly = newTitle && isFunction(newTitle) + + function format(t: string) { + return isFunction(titleTemplate) + ? titleTemplate(t) + : unref(titleTemplate).replace('%s', t) + } watch( title, (t, o) => { if (isString(t) && t !== o && document) - document.title = titleTemplate.replace('%s', t) + document.title = format(t) }, { immediate: true }, ) - if (observe && document) { + if (observe && document && !isReadonly) { useMutationObserver( document.head?.querySelector('title'), () => { if (document && document.title !== title.value) - title.value = titleTemplate.replace('%s', document.title) + title.value = format(document.title) }, { childList: true }, ) diff --git a/packages/shared/resolveRef/index.ts b/packages/shared/resolveRef/index.ts index 6490150a433..91510c6bc91 100644 --- a/packages/shared/resolveRef/index.ts +++ b/packages/shared/resolveRef/index.ts @@ -7,6 +7,7 @@ import type { MaybeComputedRef, MaybeRef } from '../utils' */ export function resolveRef(r: MaybeComputedRef): ComputedRef export function resolveRef(r: MaybeRef): Ref +export function resolveRef(r: T): Ref export function resolveRef(r: MaybeComputedRef) { return typeof r === 'function' ? computed(r as any) diff --git a/packages/shared/utils/filters.ts b/packages/shared/utils/filters.ts index bc55d12d5f2..257bd813c8f 100644 --- a/packages/shared/utils/filters.ts +++ b/packages/shared/utils/filters.ts @@ -1,5 +1,6 @@ -import { ref, unref } from 'vue-demi' -import type { Fn, MaybeRef, Pausable } from './types' +import { ref } from 'vue-demi' +import { resolveUnref } from '../resolveUnref' +import type { Fn, MaybeComputedRef, Pausable } from './types' export type FunctionArgs = (...args: Args) => Return @@ -28,7 +29,7 @@ export interface DebounceFilterOptions { * The maximum time allowed to be delayed before it's invoked. * In milliseconds. */ - maxWait?: number + maxWait?: MaybeComputedRef } /** @@ -52,13 +53,13 @@ export const bypassFilter: EventFilter = (invoke) => { * @param ms * @param [maxWait=null] */ -export function debounceFilter(ms: MaybeRef, options: DebounceFilterOptions = {}) { +export function debounceFilter(ms: MaybeComputedRef, options: DebounceFilterOptions = {}) { let timer: ReturnType | undefined let maxTimer: ReturnType | undefined | null const filter: EventFilter = (invoke) => { - const duration = unref(ms) - const maxDuration = unref(options.maxWait) + const duration = resolveUnref(ms) + const maxDuration = resolveUnref(options.maxWait) if (timer) clearTimeout(timer) @@ -71,7 +72,7 @@ export function debounceFilter(ms: MaybeRef, options: DebounceFilterOpti return invoke() } - // Create the maxTimer. Clears the regular timer on invokation + // Create the maxTimer. Clears the regular timer on invoke if (maxDuration && !maxTimer) { maxTimer = setTimeout(() => { if (timer) @@ -81,7 +82,7 @@ export function debounceFilter(ms: MaybeRef, options: DebounceFilterOpti }, maxDuration) } - // Create the regular timer. Clears the max timer on invokation + // Create the regular timer. Clears the max timer on invoke timer = setTimeout(() => { if (maxTimer) clearTimeout(maxTimer) @@ -100,7 +101,7 @@ export function debounceFilter(ms: MaybeRef, options: DebounceFilterOpti * @param [trailing=true] * @param [leading=true] */ -export function throttleFilter(ms: MaybeRef, trailing = true, leading = true) { +export function throttleFilter(ms: MaybeComputedRef, trailing = true, leading = true) { let lastExec = 0 let timer: ReturnType | undefined let isLeading = true @@ -113,7 +114,7 @@ export function throttleFilter(ms: MaybeRef, trailing = true, leading = } const filter: EventFilter = (invoke) => { - const duration = unref(ms) + const duration = resolveUnref(ms) const elapsed = Date.now() - lastExec clear() From f27285930559ed1db6dbf404c49d915a601ab97e Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Thu, 7 Jul 2022 20:11:47 +0800 Subject: [PATCH 02/23] feat(useDraggable): use computed ref --- packages/core/useDraggable/index.ts | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/packages/core/useDraggable/index.ts b/packages/core/useDraggable/index.ts index 4df2b2d336f..6f13ce4ce90 100644 --- a/packages/core/useDraggable/index.ts +++ b/packages/core/useDraggable/index.ts @@ -1,7 +1,6 @@ -import type { Ref } from 'vue-demi' -import { computed, ref, unref } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' -import { isClient, toRefs } from '@vueuse/shared' +import { computed, ref } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { isClient, resolveUnref, toRefs } from '@vueuse/shared' import { useEventListener } from '../useEventListener' import type { PointerType, Position } from '../types' import { defaultWindow } from '../_configurable' @@ -12,28 +11,28 @@ export interface UseDraggableOptions { * * @default false */ - exact?: MaybeRef + exact?: MaybeComputedRef /** * Prevent events defaults * * @default false */ - preventDefault?: MaybeRef + preventDefault?: MaybeComputedRef /** * Prevent events propagation * * @default false */ - stopPropagation?: MaybeRef + stopPropagation?: MaybeComputedRef /** * Element to attach `pointermove` and `pointerup` events to. * * @default window */ - draggingElement?: MaybeRef + draggingElement?: MaybeComputedRef /** * Pointer types that listen to. @@ -47,7 +46,7 @@ export interface UseDraggableOptions { * * @default { x: 0, y: 0} */ - initialValue?: MaybeRef + initialValue?: MaybeComputedRef /** * Callback when the dragging starts. Return `false` to prevent dragging. @@ -72,9 +71,9 @@ export interface UseDraggableOptions { * @param target * @param options */ -export function useDraggable(target: MaybeRef, options: UseDraggableOptions = {}) { +export function useDraggable(target: MaybeComputedRef, options: UseDraggableOptions = {}) { const draggingElement = options.draggingElement ?? defaultWindow - const position: Ref = ref(options.initialValue ?? { x: 0, y: 0 }) + const position = ref(resolveUnref(options.initialValue) ?? { x: 0, y: 0 }) const pressedDelta = ref() const filterEvent = (e: PointerEvent) => { @@ -84,18 +83,18 @@ export function useDraggable(target: MaybeRef { - if (unref(options.preventDefault)) + if (resolveUnref(options.preventDefault)) e.preventDefault() - if (unref(options.stopPropagation)) + if (resolveUnref(options.stopPropagation)) e.stopPropagation() } const start = (e: PointerEvent) => { if (!filterEvent(e)) return - if (unref(options.exact) && e.target !== unref(target)) + if (resolveUnref(options.exact) && e.target !== resolveUnref(target)) return - const rect = unref(target)!.getBoundingClientRect() + const rect = resolveUnref(target)!.getBoundingClientRect() const pos = { x: e.pageX - rect.left, y: e.pageY - rect.top, From 661d6add80d838ccc12cfa3eff42aa0bea9e1b82 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Thu, 7 Jul 2022 20:15:38 +0800 Subject: [PATCH 03/23] feat: more functions --- packages/core/useDropZone/index.ts | 5 ++++- packages/core/useElementBounding/index.ts | 4 ++-- packages/core/useElementHover/index.ts | 4 ++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/packages/core/useDropZone/index.ts b/packages/core/useDropZone/index.ts index 9c8b78c14b7..7a51a86d76c 100644 --- a/packages/core/useDropZone/index.ts +++ b/packages/core/useDropZone/index.ts @@ -8,7 +8,10 @@ export interface UseDropZoneReturn { isOverDropZone: Ref } -export function useDropZone(target: MaybeComputedRef, onDrop: (files: File[] | null) => void): UseDropZoneReturn { +export function useDropZone( + target: MaybeComputedRef, + onDrop: (files: File[] | null) => void, +): UseDropZoneReturn { const isOverDropZone = ref(false) let counter = 0 diff --git a/packages/core/useElementBounding/index.ts b/packages/core/useElementBounding/index.ts index 9f6a9060c9d..28777941327 100644 --- a/packages/core/useElementBounding/index.ts +++ b/packages/core/useElementBounding/index.ts @@ -1,7 +1,7 @@ import { ref, watch } from 'vue-demi' import { tryOnMounted } from '@vueuse/shared' import { useEventListener } from '../useEventListener' -import type { MaybeElementRef } from '../unrefElement' +import type { MaybeComputedElementRef } from '../unrefElement' import { unrefElement } from '../unrefElement' import { useResizeObserver } from '../useResizeObserver' @@ -41,7 +41,7 @@ export interface UseElementBoundingOptions { * @param target */ export function useElementBounding( - target: MaybeElementRef, + target: MaybeComputedElementRef, options: UseElementBoundingOptions = {}, ) { const { diff --git a/packages/core/useElementHover/index.ts b/packages/core/useElementHover/index.ts index 49266c887e5..d15b9a832c9 100644 --- a/packages/core/useElementHover/index.ts +++ b/packages/core/useElementHover/index.ts @@ -1,9 +1,9 @@ import type { Ref } from 'vue-demi' import { ref } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' import { useEventListener } from '../useEventListener' -export function useElementHover(el: MaybeRef): Ref { +export function useElementHover(el: MaybeComputedRef): Ref { const isHovered = ref(false) useEventListener(el, 'mouseenter', () => isHovered.value = true) From 0284aace3df7f37cfc75bb76c70f19622de490fe Mon Sep 17 00:00:00 2001 From: Chris <1633711653@qq.com> Date: Thu, 7 Jul 2022 21:13:36 +0800 Subject: [PATCH 04/23] feat(useTimeago): use computed ref (#1775) --- packages/core/useTimeAgo/index.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/core/useTimeAgo/index.ts b/packages/core/useTimeAgo/index.ts index a6d95e51ae5..0fd292993dd 100644 --- a/packages/core/useTimeAgo/index.ts +++ b/packages/core/useTimeAgo/index.ts @@ -1,4 +1,5 @@ -import type { MaybeRef, Pausable } from '@vueuse/shared' +import type { MaybeComputedRef, Pausable } from '@vueuse/shared' +import { resolveUnref } from '@vueuse/shared' import type { ComputedRef } from 'vue-demi' import { computed, unref } from 'vue-demi' import { useNow } from '../useNow' @@ -104,9 +105,9 @@ const DEFAULT_FORMATTER = (date: Date) => date.toISOString().slice(0, 10) * @see https://vueuse.org/useTimeAgo * @param options */ -export function useTimeAgo(time: MaybeRef, options?: UseTimeAgoOptions): ComputedRef -export function useTimeAgo(time: MaybeRef, options: UseTimeAgoOptions): { timeAgo: ComputedRef } & Pausable -export function useTimeAgo(time: MaybeRef, options: UseTimeAgoOptions = {}) { +export function useTimeAgo(time: MaybeComputedRef, options?: UseTimeAgoOptions): ComputedRef +export function useTimeAgo(time: MaybeComputedRef, options: UseTimeAgoOptions): { timeAgo: ComputedRef } & Pausable +export function useTimeAgo(time: MaybeComputedRef, options: UseTimeAgoOptions = {}) { const { controls: exposeControls = false, max, @@ -156,7 +157,7 @@ export function useTimeAgo(time: MaybeRef, options: UseT return applyFormat(past ? 'past' : 'future', str, past) } - const timeAgo = computed(() => getTimeago(new Date(unref(time)), unref(now.value))) + const timeAgo = computed(() => getTimeago(new Date(resolveUnref(time)), unref(now.value))) if (exposeControls) { return { From 07aa5109ef4a72a7d80c7459667f8422f4982634 Mon Sep 17 00:00:00 2001 From: GZ Date: Thu, 7 Jul 2022 21:15:41 +0800 Subject: [PATCH 05/23] feat(useImage): use computed ref (#1776) --- packages/core/useImage/index.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/packages/core/useImage/index.ts b/packages/core/useImage/index.ts index 67814766265..39124223c0b 100644 --- a/packages/core/useImage/index.ts +++ b/packages/core/useImage/index.ts @@ -1,7 +1,6 @@ -import type { MaybeRef } from '@vueuse/shared' - -import { unref, watch } from 'vue-demi' - +import { watch } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveUnref } from '@vueuse/shared' import type { AsyncStateOptions } from '../useAsyncState' import { useAsyncState } from '../useAsyncState' @@ -38,11 +37,11 @@ async function loadImage(options: UseImageOptions): Promise { * @param asyncStateOptions */ export const useImage = ( - options: MaybeRef, + options: MaybeComputedRef, asyncStateOptions: AsyncStateOptions = {}, ) => { const state = useAsyncState( - () => loadImage(unref(options)), + () => loadImage(resolveUnref(options)), undefined, { resetOnExecute: true, @@ -51,7 +50,7 @@ export const useImage = ( ) watch( - () => unref(options), + () => resolveUnref(options), () => state.execute(asyncStateOptions.delay), { deep: true }, ) From 5dad6eca423952c25df1cc69808038dd0454ca3b Mon Sep 17 00:00:00 2001 From: BlackTooth <39750199+xiaojieajie@users.noreply.github.com> Date: Fri, 8 Jul 2022 00:50:04 +0800 Subject: [PATCH 06/23] feat(usePointerSwipe): use computed ref (#1773) --- packages/core/useClipboard/index.ts | 6 +++--- packages/core/useFavicon/index.ts | 9 +++------ packages/core/useFileSystemAccess/index.ts | 4 ++-- packages/core/usePointerSwipe/index.ts | 4 ++-- 4 files changed, 10 insertions(+), 13 deletions(-) diff --git a/packages/core/useClipboard/index.ts b/packages/core/useClipboard/index.ts index bcd83f7462f..dd9e04a3732 100644 --- a/packages/core/useClipboard/index.ts +++ b/packages/core/useClipboard/index.ts @@ -1,6 +1,6 @@ /* this implementation is original ported from https://github.com/logaretm/vue-use-web by Abdelrahman Awad */ -import type { MaybeRef } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' import { useTimeoutFn } from '@vueuse/shared' import type { ComputedRef } from 'vue-demi' import { ref, unref } from 'vue-demi' @@ -44,8 +44,8 @@ export interface ClipboardReturn { * @param options */ export function useClipboard(options?: ClipboardOptions): ClipboardReturn -export function useClipboard(options: ClipboardOptions>): ClipboardReturn -export function useClipboard(options: ClipboardOptions | undefined> = {}): ClipboardReturn { +export function useClipboard(options: ClipboardOptions>): ClipboardReturn +export function useClipboard(options: ClipboardOptions | undefined> = {}): ClipboardReturn { const { navigator = defaultNavigator, read = false, diff --git a/packages/core/useFavicon/index.ts b/packages/core/useFavicon/index.ts index 9d6bba38688..b085928b441 100644 --- a/packages/core/useFavicon/index.ts +++ b/packages/core/useFavicon/index.ts @@ -1,4 +1,4 @@ -import type { MaybeRef } from '@vueuse/shared' +import { MaybeComputedRef, resolveUnref } from '@vueuse/shared' import { isString } from '@vueuse/shared' import { isRef, ref, watch } from 'vue-demi' import type { ConfigurableDocument } from '../_configurable' @@ -17,7 +17,7 @@ export interface FaviconOptions extends ConfigurableDocument { * @param options */ export function useFavicon( - newIcon: MaybeRef = null, + newIcon: MaybeComputedRef = null, options: FaviconOptions = {}, ) { const { @@ -26,9 +26,6 @@ export function useFavicon( document = defaultDocument, } = options - const favicon = isRef(newIcon) - ? newIcon - : ref(newIcon) const applyIcon = (icon: string) => { document?.head @@ -37,7 +34,7 @@ export function useFavicon( } watch( - favicon, + () => resolveUnref(newIcon), (i, o) => { if (isString(i) && i !== o) applyIcon(i) diff --git a/packages/core/useFileSystemAccess/index.ts b/packages/core/useFileSystemAccess/index.ts index 0ccb3b72d8e..6921dec7348 100644 --- a/packages/core/useFileSystemAccess/index.ts +++ b/packages/core/useFileSystemAccess/index.ts @@ -1,6 +1,6 @@ import type { Ref } from 'vue-demi' import { computed, ref, unref, watch } from 'vue-demi' -import type { Awaitable, MaybeRef } from '@vueuse/shared' +import type { Awaitable, MaybeComputedRef } from '@vueuse/shared' import type { ConfigurableWindow } from '../_configurable' import { defaultWindow } from '../_configurable' @@ -84,7 +84,7 @@ export type UseFileSystemAccessOptions = ConfigurableWindow & UseFileSystemAcces /** * file data type */ - dataType?: MaybeRef<'Text' | 'ArrayBuffer' | 'Blob'> + dataType?: MaybeComputedRef<'Text' | 'ArrayBuffer' | 'Blob'> } /** diff --git a/packages/core/usePointerSwipe/index.ts b/packages/core/usePointerSwipe/index.ts index 913df280fd0..aac2d97306a 100644 --- a/packages/core/usePointerSwipe/index.ts +++ b/packages/core/usePointerSwipe/index.ts @@ -1,4 +1,4 @@ -import type { MaybeRef } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' import type { Ref } from 'vue-demi' import { computed, reactive, readonly, ref } from 'vue-demi' import { useEventListener } from '../useEventListener' @@ -52,7 +52,7 @@ export interface PointerSwipeReturn { * @param options */ export function usePointerSwipe( - target: MaybeRef, + target: MaybeComputedRef, options: PointerSwipeOptions = {}, ): PointerSwipeReturn { const targetRef = ref(target) From fb061a90b41795ec72163d0889965a6e53a1e7e8 Mon Sep 17 00:00:00 2001 From: hy <50621078+HYzihong@users.noreply.github.com> Date: Fri, 8 Jul 2022 00:54:39 +0800 Subject: [PATCH 07/23] feat(useDebounceFn): use computed ref (#1782) * feat(useDateFormat): use computed ref * feat(useDebounceFn): use computed ref --- packages/shared/useDateFormat/index.ts | 11 ++++++----- packages/shared/useDebounceFn/index.ts | 6 +++--- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/packages/shared/useDateFormat/index.ts b/packages/shared/useDateFormat/index.ts index 02f5d52ca81..0c837e7c448 100644 --- a/packages/shared/useDateFormat/index.ts +++ b/packages/shared/useDateFormat/index.ts @@ -1,5 +1,6 @@ -import type { MaybeRef } from '@vueuse/shared' -import { computed, unref } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveUnref } from '@vueuse/shared' +import { computed } from 'vue-demi' export type DateLike = Date | number | string | undefined @@ -49,7 +50,7 @@ export const normalizeDate = (date: DateLike) => { 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) + || 1, d[4] || 0, d[5] || 0, d[6] || 0, ms) } } @@ -64,8 +65,8 @@ export const normalizeDate = (date: DateLike) => { * @param formatStr */ -export function useDateFormat(date: MaybeRef, formatStr: MaybeRef = 'HH:mm:ss') { - return computed(() => formatDate(normalizeDate(unref(date)), unref(formatStr))) +export function useDateFormat(date: MaybeComputedRef, formatStr: MaybeComputedRef = 'HH:mm:ss') { + return computed(() => formatDate(normalizeDate(resolveUnref(date)), resolveUnref(formatStr))) } export type UseDateFormatReturn = ReturnType diff --git a/packages/shared/useDebounceFn/index.ts b/packages/shared/useDebounceFn/index.ts index 51257479131..d394168bd56 100644 --- a/packages/shared/useDebounceFn/index.ts +++ b/packages/shared/useDebounceFn/index.ts @@ -1,6 +1,6 @@ -import type { DebounceFilterOptions, FunctionArgs, MaybeRef } from '../utils' +import type { MaybeComputedRef } from '@vueuse/shared' +import type { DebounceFilterOptions, FunctionArgs } from '../utils' import { createFilterWrapper, debounceFilter } from '../utils' - /** * Debounce execution of a function. * @@ -10,7 +10,7 @@ import { createFilterWrapper, debounceFilter } from '../utils' * * @return A new, debounce, function. */ -export function useDebounceFn(fn: T, ms: MaybeRef = 200, options: DebounceFilterOptions = {}): T { +export function useDebounceFn(fn: T, ms: MaybeComputedRef = 200, options: DebounceFilterOptions = {}): T { return createFilterWrapper( debounceFilter(ms, options), fn, From 3f907eddea75ba2bb25212bcac65b91a2b08c1d7 Mon Sep 17 00:00:00 2001 From: Chris <1633711653@qq.com> Date: Fri, 8 Jul 2022 00:57:28 +0800 Subject: [PATCH 08/23] feat(useQrcode): use computed ref (#1774) * feat(useQrcide): use computed ref * chore: update * chore: update --- packages/integrations/useQRCode/index.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/integrations/useQRCode/index.ts b/packages/integrations/useQRCode/index.ts index 208c921951e..77e351058bc 100644 --- a/packages/integrations/useQRCode/index.ts +++ b/packages/integrations/useQRCode/index.ts @@ -1,5 +1,5 @@ -import type { MaybeRef } from '@vueuse/shared' -import { isClient } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' +import { isClient, resolveRef } from '@vueuse/shared' import { ref, watch } from 'vue-demi' import QRCode from 'qrcode' @@ -11,10 +11,10 @@ import QRCode from 'qrcode' * @param options */ export function useQRCode( - text: MaybeRef, + text: MaybeComputedRef, options?: QRCode.QRCodeToDataURLOptions, ) { - const src = ref(text) + const src = resolveRef(text) const result = ref('') watch( From 4e38abcbac261896050819d73ada571865b2b184 Mon Sep 17 00:00:00 2001 From: zz <2418184580@qq.com> Date: Fri, 8 Jul 2022 10:41:13 +0800 Subject: [PATCH 09/23] fix(useClipboard): fix type error (#1785) --- packages/core/useClipboard/index.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/core/useClipboard/index.ts b/packages/core/useClipboard/index.ts index dd9e04a3732..0f8ee88d728 100644 --- a/packages/core/useClipboard/index.ts +++ b/packages/core/useClipboard/index.ts @@ -1,9 +1,9 @@ /* this implementation is original ported from https://github.com/logaretm/vue-use-web by Abdelrahman Awad */ import type { MaybeComputedRef } from '@vueuse/shared' -import { useTimeoutFn } from '@vueuse/shared' +import { resolveUnref, useTimeoutFn } from '@vueuse/shared' import type { ComputedRef } from 'vue-demi' -import { ref, unref } from 'vue-demi' +import { ref } from 'vue-demi' import type { WindowEventName } from '../useEventListener' import { useEventListener } from '../useEventListener' import type { ConfigurableNavigator } from '../_configurable' @@ -71,7 +71,7 @@ export function useClipboard(options: ClipboardOptions useEventListener(event as WindowEventName, updateText) } - async function copy(value = unref(source)) { + async function copy(value = resolveUnref(source)) { if (isSupported && value != null) { await navigator!.clipboard.writeText(value) text.value = value From 22242ac325f04e0a4b1c53de21f9337612e87f88 Mon Sep 17 00:00:00 2001 From: zz <2418184580@qq.com> Date: Fri, 8 Jul 2022 10:55:47 +0800 Subject: [PATCH 10/23] chore: correct type example (#1784) --- packages/shared/utils/types.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/shared/utils/types.ts b/packages/shared/utils/types.ts index fd91e815329..5628e65f461 100644 --- a/packages/shared/utils/types.ts +++ b/packages/shared/utils/types.ts @@ -28,10 +28,10 @@ export type RemoveableRef = RemovableRef export type MaybeRef = T | Ref /** - * Maybe it's a ref, or a getter function + * Maybe it's a ref, or a plain value, or a getter function * * ```ts - * type MaybeRef = T | Ref + * type MaybeComputedRef = T | Ref | (() => T) * ``` */ export type MaybeComputedRef = T extends Function From 18784aeefebfd3fbb1144abc051b2f80e370aaaa Mon Sep 17 00:00:00 2001 From: hy <50621078+HYzihong@users.noreply.github.com> Date: Fri, 8 Jul 2022 10:56:59 +0800 Subject: [PATCH 11/23] feat(useDateFormat): use computed ref (#1781) From 90be9e833639e30dac521a2bc2901db0ae14b25c Mon Sep 17 00:00:00 2001 From: zz <2418184580@qq.com> Date: Fri, 8 Jul 2022 11:26:16 +0800 Subject: [PATCH 12/23] fix(usePointerSwipe): fix error (#1791) --- packages/core/usePointerSwipe/index.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/core/usePointerSwipe/index.ts b/packages/core/usePointerSwipe/index.ts index aac2d97306a..8bff97bdeb4 100644 --- a/packages/core/usePointerSwipe/index.ts +++ b/packages/core/usePointerSwipe/index.ts @@ -1,4 +1,5 @@ import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveRef } from '@vueuse/shared' import type { Ref } from 'vue-demi' import { computed, reactive, readonly, ref } from 'vue-demi' import { useEventListener } from '../useEventListener' @@ -55,7 +56,7 @@ export function usePointerSwipe( target: MaybeComputedRef, options: PointerSwipeOptions = {}, ): PointerSwipeReturn { - const targetRef = ref(target) + const targetRef = resolveRef(target) const { threshold = 50, onSwipe, From 57d24cb8a716b7d0ee6d57be5bedd4e28d3ea021 Mon Sep 17 00:00:00 2001 From: zz <2418184580@qq.com> Date: Fri, 8 Jul 2022 11:26:23 +0800 Subject: [PATCH 13/23] fix(useFavicon): fix error (#1790) --- packages/core/useFavicon/index.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/core/useFavicon/index.ts b/packages/core/useFavicon/index.ts index b085928b441..810841a5f0d 100644 --- a/packages/core/useFavicon/index.ts +++ b/packages/core/useFavicon/index.ts @@ -1,6 +1,6 @@ -import { MaybeComputedRef, resolveUnref } from '@vueuse/shared' -import { isString } from '@vueuse/shared' -import { isRef, ref, watch } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { isString, resolveRef } from '@vueuse/shared' +import { watch } from 'vue-demi' import type { ConfigurableDocument } from '../_configurable' import { defaultDocument } from '../_configurable' @@ -26,6 +26,7 @@ export function useFavicon( document = defaultDocument, } = options + const favicon = resolveRef(newIcon) const applyIcon = (icon: string) => { document?.head @@ -34,7 +35,7 @@ export function useFavicon( } watch( - () => resolveUnref(newIcon), + favicon, (i, o) => { if (isString(i) && i !== o) applyIcon(i) From c48234ce193641378342ace9f338b0e30a925778 Mon Sep 17 00:00:00 2001 From: zz <2418184580@qq.com> Date: Fri, 8 Jul 2022 11:32:22 +0800 Subject: [PATCH 14/23] fix(useDraggable): fix error (#1792) --- packages/core/useDraggable/component.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/core/useDraggable/component.ts b/packages/core/useDraggable/component.ts index 4ece8272096..d2d35669ead 100644 --- a/packages/core/useDraggable/component.ts +++ b/packages/core/useDraggable/component.ts @@ -1,6 +1,7 @@ -import { defineComponent, h, reactive, ref, unref } from 'vue-demi' +import { defineComponent, h, reactive, ref } from 'vue-demi' import type { UseDraggableOptions } from '@vueuse/core' import { isClient, useDraggable, useStorage } from '@vueuse/core' +import { resolveUnref } from '@vueuse/shared' import type { RenderableComponent } from '../types' export interface UseDraggableProps extends UseDraggableOptions, RenderableComponent { @@ -34,7 +35,7 @@ export const UseDraggable = defineComponent({ const initialValue = props.storageKey ? useStorage( props.storageKey, - unref(props.initialValue) || { x: 0, y: 0 }, + resolveUnref(props.initialValue) || { x: 0, y: 0 }, isClient ? props.storageType === 'session' ? sessionStorage From cadf0f6676fcdd0507ba34b86f64fa2f4c55ce40 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Fri, 8 Jul 2022 12:46:38 +0800 Subject: [PATCH 15/23] chore: update types --- packages/contributors.json | 11 +++++++---- packages/core/useTimeAgo/component.ts | 6 ++---- packages/math/package.json | 2 +- packages/shared/utils/types.ts | 2 +- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/packages/contributors.json b/packages/contributors.json index 8f52dc7c89f..b07d70ce2c2 100644 --- a/packages/contributors.json +++ b/packages/contributors.json @@ -27,6 +27,8 @@ "LittleSound", "ArcherGu", "daikiojm", + "dfreier", + "innocenzi", "Demivan", "jbaubree", "ansidev", @@ -61,11 +63,13 @@ "manaust", "lpj145", "maxma241", + "michaelhue", "xizher", "nhedger", "g-plane", "coolhome", "herrmannplatz", + "wobsoriano", "seifsay3d", "darkxanter", "shigma", @@ -115,13 +119,13 @@ "damienroche", "danmindru", "DesselBane", - "dfreier", + "DevilTea", + "w1ndy", "eggsy", "posva", "Maiquu", "Danmer", "emilsgulbis", - "innocenzi", "iendeavor", "web2033", "sp1ker", @@ -175,7 +179,6 @@ "mxmvshnvsk", "AldeonMoriak", "MelihAltintas", - "michaelhue", "mdbetancourt", "edimitchel", "michael-harvey", @@ -195,7 +198,6 @@ "ramonakira", "Redemption198", "neelance", - "wobsoriano", "rromanv", "Rolanddoda", "romansp", @@ -232,6 +234,7 @@ "koheing", "kongmoumou", "laozei6401", + "lavolpecheprogramma", "leovoon", "likeswinds", "lxhyl", diff --git a/packages/core/useTimeAgo/component.ts b/packages/core/useTimeAgo/component.ts index 494f1a15a3f..67deaca5fb4 100644 --- a/packages/core/useTimeAgo/component.ts +++ b/packages/core/useTimeAgo/component.ts @@ -1,5 +1,4 @@ -import type { Ref } from 'vue-demi' -import { defineComponent, reactive, toRef } from 'vue-demi' +import { defineComponent, reactive } from 'vue-demi' import type { MaybeRef } from '@vueuse/shared' import type { UseTimeAgoOptions } from '@vueuse/core' import { useTimeAgo } from '@vueuse/core' @@ -12,8 +11,7 @@ export const UseTimeAgo = defineComponent({ name: 'UseTimeAgo', props: ['time', 'updateInterval', 'max', 'fullDateFormatter', 'messages'] as unknown as undefined, setup(props, { slots }) { - const time = toRef(props, 'time') as Ref - const data = reactive(useTimeAgo(time, { ...props, controls: true })) + const data = reactive(useTimeAgo(() => props.time as number, { ...props, controls: true })) return () => { if (slots.default) diff --git a/packages/math/package.json b/packages/math/package.json index 5cbe53138c5..82fabab89e2 100644 --- a/packages/math/package.json +++ b/packages/math/package.json @@ -1,6 +1,6 @@ { "name": "@vueuse/math", - "version": "7.5.5", + "version": "8.8.1", "description": "Math functions for VueUse", "author": "Jacob Clevenger", "license": "MIT", diff --git a/packages/shared/utils/types.ts b/packages/shared/utils/types.ts index 5628e65f461..92dd3ecdade 100644 --- a/packages/shared/utils/types.ts +++ b/packages/shared/utils/types.ts @@ -34,7 +34,7 @@ export type MaybeRef = T | Ref * type MaybeComputedRef = T | Ref | (() => T) * ``` */ -export type MaybeComputedRef = T extends Function +export type MaybeComputedRef = T extends () => void ? never : (() => T) | MaybeRef From a6ff87b942f9d50e992c62783fdc35f90aae0067 Mon Sep 17 00:00:00 2001 From: Butter fly Date: Fri, 8 Jul 2022 12:47:59 +0800 Subject: [PATCH 16/23] feat: 3 hooks use computed ref (#1783) --- packages/core/useTimeoutPoll/index.ts | 4 ++-- packages/core/useVibrate/index.ts | 9 ++++----- packages/shared/useTimeoutFn/index.ts | 10 ++++++---- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/packages/core/useTimeoutPoll/index.ts b/packages/core/useTimeoutPoll/index.ts index be07c895fd1..3c342b0603e 100644 --- a/packages/core/useTimeoutPoll/index.ts +++ b/packages/core/useTimeoutPoll/index.ts @@ -1,8 +1,8 @@ import { ref } from 'vue-demi' -import type { Awaitable, MaybeRef, Pausable, TimeoutFnOptions } from '@vueuse/shared' +import type { Awaitable, MaybeComputedRef, Pausable, TimeoutFnOptions } from '@vueuse/shared' import { tryOnScopeDispose, useTimeoutFn } from '@vueuse/shared' -export function useTimeoutPoll(fn: () => Awaitable, interval: MaybeRef, timeoutPollOptions?: TimeoutFnOptions): Pausable { +export function useTimeoutPoll(fn: () => Awaitable, interval: MaybeComputedRef, timeoutPollOptions?: TimeoutFnOptions): Pausable { const { start } = useTimeoutFn(loop, interval) const isActive = ref(false) diff --git a/packages/core/useVibrate/index.ts b/packages/core/useVibrate/index.ts index 6b410f0e6b4..e26c74bbe1a 100644 --- a/packages/core/useVibrate/index.ts +++ b/packages/core/useVibrate/index.ts @@ -1,6 +1,5 @@ -import { ref } from 'vue-demi' -import type { MaybeRef, Pausable } from '@vueuse/shared' -import { useIntervalFn } from '@vueuse/shared' +import type { MaybeComputedRef, Pausable } from '@vueuse/shared' +import { resolveRef, useIntervalFn } from '@vueuse/shared' import type { ConfigurableNavigator } from '../_configurable' import { defaultNavigator } from '../_configurable' @@ -18,7 +17,7 @@ export interface UseVibrateOptions extends ConfigurableNavigator { * @default [] * */ - pattern?: MaybeRef + pattern?: MaybeComputedRef /** * Interval to run a persistent vibration, in ms * @@ -46,7 +45,7 @@ export function useVibrate(options?: UseVibrateOptions) { const isSupported = typeof navigator !== 'undefined' && 'vibrate' in navigator - const patternRef = ref(pattern) + const patternRef = resolveRef(pattern) let intervalControls: Pausable | undefined const vibrate = (pattern = patternRef.value) => { diff --git a/packages/shared/useTimeoutFn/index.ts b/packages/shared/useTimeoutFn/index.ts index c6ad0c8fd8f..fa91ce83588 100644 --- a/packages/shared/useTimeoutFn/index.ts +++ b/packages/shared/useTimeoutFn/index.ts @@ -1,6 +1,8 @@ -import { ref, unref } from 'vue-demi' +import { ref } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveUnref } from '@vueuse/shared' import { tryOnScopeDispose } from '../tryOnScopeDispose' -import type { MaybeRef, Stoppable } from '../utils' +import type { Stoppable } from '../utils' import { isClient } from '../utils' export interface TimeoutFnOptions { @@ -21,7 +23,7 @@ export interface TimeoutFnOptions { */ export function useTimeoutFn( cb: (...args: unknown[]) => any, - interval: MaybeRef, + interval: MaybeComputedRef, options: TimeoutFnOptions = {}, ): Stoppable { const { @@ -52,7 +54,7 @@ export function useTimeoutFn( timer = null cb(...args) - }, unref(interval)) as unknown as number + }, resolveUnref(interval)) as unknown as number } if (immediate) { From a715272d365eb3e4b41586c37e280e37b5ddeed6 Mon Sep 17 00:00:00 2001 From: Chris <1633711653@qq.com> Date: Fri, 8 Jul 2022 12:48:55 +0800 Subject: [PATCH 17/23] feat: five hooks use computed ref (#1779) --- packages/core/useScroll/index.ts | 8 ++++---- packages/core/useScrollLock/index.ts | 14 +++++++------- packages/core/useShare/index.ts | 12 ++++++------ packages/core/useSpeechRecognition/index.ts | 8 ++++---- packages/core/useSpeechSynthesis/index.ts | 12 ++++++------ 5 files changed, 27 insertions(+), 27 deletions(-) diff --git a/packages/core/useScroll/index.ts b/packages/core/useScroll/index.ts index 1fe7771446c..ee7720c7622 100644 --- a/packages/core/useScroll/index.ts +++ b/packages/core/useScroll/index.ts @@ -1,6 +1,6 @@ import { reactive, ref } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' -import { noop, useDebounceFn, useThrottleFn } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' +import { noop, resolveUnref, useDebounceFn, useThrottleFn } from '@vueuse/shared' import { useEventListener } from '../useEventListener' export interface UseScrollOptions { @@ -59,7 +59,7 @@ export interface UseScrollOptions { */ export function useScroll( - element: MaybeRef, + element: MaybeComputedRef, options: UseScrollOptions = {}, ) { const { @@ -95,7 +95,7 @@ export function useScroll( bottom: false, }) - if (element) { + if (resolveUnref(element)) { const onScrollEnd = useDebounceFn((e: Event) => { isScrolling.value = false directions.left = false diff --git a/packages/core/useScrollLock/index.ts b/packages/core/useScrollLock/index.ts index ce52cc2ddb1..2636233d5e5 100644 --- a/packages/core/useScrollLock/index.ts +++ b/packages/core/useScrollLock/index.ts @@ -1,6 +1,6 @@ -import { computed, ref, unref, watch } from 'vue-demi' -import type { Fn, MaybeRef } from '@vueuse/shared' -import { isIOS, tryOnScopeDispose } from '@vueuse/shared' +import { computed, ref, watch } from 'vue-demi' +import type { Fn, MaybeComputedRef } from '@vueuse/shared' +import { isIOS, resolveRef, resolveUnref, tryOnScopeDispose } from '@vueuse/shared' import { useEventListener } from '../useEventListener' @@ -23,14 +23,14 @@ function preventDefault(rawEvent: TouchEvent): boolean { * @param element */ export function useScrollLock( - element: MaybeRef, + element: MaybeComputedRef, initialState = false, ) { const isLocked = ref(initialState) let stopTouchMoveListener: Fn | null = null let initialOverflow: CSSStyleDeclaration['overflow'] - watch(() => unref(element), (el) => { + watch(resolveRef(element), (el) => { if (el) { const ele = el as HTMLElement initialOverflow = ele.style.overflow @@ -42,7 +42,7 @@ export function useScrollLock( }) const lock = () => { - const ele = (unref(element) as HTMLElement) + const ele = (resolveUnref(element) as HTMLElement) if (!ele || isLocked.value) return if (isIOS) { @@ -58,7 +58,7 @@ export function useScrollLock( } const unlock = () => { - const ele = (unref(element) as HTMLElement) + const ele = (resolveUnref(element) as HTMLElement) if (!ele || !isLocked.value) return isIOS && stopTouchMoveListener?.() diff --git a/packages/core/useShare/index.ts b/packages/core/useShare/index.ts index 265400bd4c7..38b6af17b82 100644 --- a/packages/core/useShare/index.ts +++ b/packages/core/useShare/index.ts @@ -1,5 +1,5 @@ -import type { MaybeRef } from '@vueuse/shared' -import { unref } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveUnref } from '@vueuse/shared' import type { ConfigurableNavigator } from '../_configurable' import { defaultNavigator } from '../_configurable' @@ -22,17 +22,17 @@ interface NavigatorWithShare { * @param shareOptions * @param options */ -export function useShare(shareOptions: MaybeRef = {}, options: ConfigurableNavigator = {}) { +export function useShare(shareOptions: MaybeComputedRef = {}, options: ConfigurableNavigator = {}) { const { navigator = defaultNavigator } = options const _navigator = (navigator as NavigatorWithShare) const isSupported = _navigator && 'canShare' in _navigator - const share = async (overrideOptions: MaybeRef = {}) => { + const share = async (overrideOptions: MaybeComputedRef = {}) => { if (isSupported) { const data = { - ...unref(shareOptions), - ...unref(overrideOptions), + ...resolveUnref(shareOptions), + ...resolveUnref(overrideOptions), } let granted = true diff --git a/packages/core/useSpeechRecognition/index.ts b/packages/core/useSpeechRecognition/index.ts index 4f54078746b..a7c7a55cd0b 100644 --- a/packages/core/useSpeechRecognition/index.ts +++ b/packages/core/useSpeechRecognition/index.ts @@ -1,8 +1,8 @@ // ported from https://www.reddit.com/r/vuejs/comments/jksizl/speech_recognition_as_a_vue_3_hook // by https://github.com/wobsoriano -import type { MaybeRef } from '@vueuse/shared' -import { tryOnScopeDispose } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveRef, tryOnScopeDispose } from '@vueuse/shared' import type { Ref } from 'vue-demi' import { ref, shallowRef, unref, watch } from 'vue-demi' import type { ConfigurableWindow } from '../_configurable' @@ -27,7 +27,7 @@ export interface SpeechRecognitionOptions extends ConfigurableWindow { * * @default 'en-US' */ - lang?: MaybeRef + lang?: MaybeComputedRef } /** @@ -44,7 +44,7 @@ export function useSpeechRecognition(options: SpeechRecognitionOptions = {}) { window = defaultWindow, } = options - const lang = ref(options.lang || 'en-US') + const lang = resolveRef(options.lang || 'en-US') const isListening = ref(false) const isFinal = ref(false) const result = ref('') diff --git a/packages/core/useSpeechSynthesis/index.ts b/packages/core/useSpeechSynthesis/index.ts index 884f5283382..7090f19db6d 100644 --- a/packages/core/useSpeechSynthesis/index.ts +++ b/packages/core/useSpeechSynthesis/index.ts @@ -1,5 +1,5 @@ -import type { MaybeRef } from '@vueuse/shared' -import { tryOnScopeDispose } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveRef, tryOnScopeDispose } from '@vueuse/shared' import type { Ref } from 'vue-demi' import { computed, ref, shallowRef, unref, watch } from 'vue-demi' import type { ConfigurableWindow } from '../_configurable' @@ -15,7 +15,7 @@ export interface SpeechSynthesisOptions extends ConfigurableWindow { * * @default 'en-US' */ - lang?: MaybeRef + lang?: MaybeComputedRef /** * Gets and sets the pitch at which the utterance will be spoken at. * @@ -47,7 +47,7 @@ export interface SpeechSynthesisOptions extends ConfigurableWindow { * @see https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis SpeechSynthesis * @param options */ -export function useSpeechSynthesis(text: MaybeRef, options: SpeechSynthesisOptions = {}) { +export function useSpeechSynthesis(text: MaybeComputedRef, options: SpeechSynthesisOptions = {}) { const { pitch = 1, rate = 1, @@ -66,8 +66,8 @@ export function useSpeechSynthesis(text: MaybeRef, options: SpeechSynthe name: options.voice?.name || '', } - const spokenText = ref(text || '') - const lang = ref(options.lang || 'en-US') + const spokenText = resolveRef(text || '') + const lang = resolveRef(options.lang || 'en-US') const error = shallowRef(undefined) as Ref const toggle = (value = !isPlaying.value) => { From 0fe3237a88c19a7889742510467e3c685725f3c2 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Fri, 8 Jul 2022 12:55:31 +0800 Subject: [PATCH 18/23] feat(useFetch): update --- packages/core/useFetch/index.ts | 61 ++++++++++++++++++--------------- 1 file changed, 33 insertions(+), 28 deletions(-) diff --git a/packages/core/useFetch/index.ts b/packages/core/useFetch/index.ts index 8b95fb8609b..01c6bab5218 100644 --- a/packages/core/useFetch/index.ts +++ b/packages/core/useFetch/index.ts @@ -1,7 +1,7 @@ import type { ComputedRef, Ref } from 'vue-demi' -import type { EventHookOn, Fn, MaybeRef, Stoppable } from '@vueuse/shared' -import { containsProp, createEventHook, until, useTimeoutFn } from '@vueuse/shared' -import { computed, isRef, ref, shallowRef, unref, watch } from 'vue-demi' +import type { EventHookOn, Fn, MaybeComputedRef, MaybeRef, Stoppable } from '@vueuse/shared' +import { containsProp, createEventHook, resolveRef, resolveUnref, until, useTimeoutFn } from '@vueuse/shared' +import { computed, isRef, ref, shallowRef, watch } from 'vue-demi' import { defaultWindow } from '../_configurable' export interface UseFetchReturn { @@ -73,12 +73,12 @@ export interface UseFetchReturn { // methods get(): UseFetchReturn & PromiseLike> - post(payload?: MaybeRef, type?: string): UseFetchReturn & PromiseLike> - put(payload?: MaybeRef, type?: string): UseFetchReturn & PromiseLike> - delete(payload?: MaybeRef, type?: string): UseFetchReturn & PromiseLike> - patch(payload?: MaybeRef, type?: string): UseFetchReturn & PromiseLike> - head(payload?: MaybeRef, type?: string): UseFetchReturn & PromiseLike> - options(payload?: MaybeRef, type?: string): UseFetchReturn & PromiseLike> + post(payload?: MaybeComputedRef, type?: string): UseFetchReturn & PromiseLike> + put(payload?: MaybeComputedRef, type?: string): UseFetchReturn & PromiseLike> + delete(payload?: MaybeComputedRef, type?: string): UseFetchReturn & PromiseLike> + patch(payload?: MaybeComputedRef, type?: string): UseFetchReturn & PromiseLike> + head(payload?: MaybeComputedRef, type?: string): UseFetchReturn & PromiseLike> + options(payload?: MaybeComputedRef, type?: string): UseFetchReturn & PromiseLike> // type json(): UseFetchReturn & PromiseLike> @@ -146,7 +146,7 @@ export interface UseFetchOptions { * * @default false */ - refetch?: MaybeRef + refetch?: MaybeComputedRef /** * Initial data before the request finished @@ -228,10 +228,10 @@ export function createFetch(config: CreateFetchOptions = {}) { const _options = config.options || {} const _fetchOptions = config.fetchOptions || {} - function useFactoryFetch(url: MaybeRef, ...args: any[]) { + function useFactoryFetch(url: MaybeComputedRef, ...args: any[]) { const computedUrl = computed(() => config.baseUrl - ? joinPaths(unref(config.baseUrl), unref(url)) - : unref(url), + ? joinPaths(resolveUnref(config.baseUrl), resolveUnref(url)) + : resolveUnref(url), ) let options = _options @@ -269,11 +269,11 @@ export function createFetch(config: CreateFetchOptions = {}) { return useFactoryFetch as typeof useFetch } -export function useFetch(url: MaybeRef): UseFetchReturn & PromiseLike> -export function useFetch(url: MaybeRef, useFetchOptions: UseFetchOptions): UseFetchReturn & PromiseLike> -export function useFetch(url: MaybeRef, options: RequestInit, useFetchOptions?: UseFetchOptions): UseFetchReturn & PromiseLike> +export function useFetch(url: MaybeComputedRef): UseFetchReturn & PromiseLike> +export function useFetch(url: MaybeComputedRef, useFetchOptions: UseFetchOptions): UseFetchReturn & PromiseLike> +export function useFetch(url: MaybeComputedRef, options: RequestInit, useFetchOptions?: UseFetchOptions): UseFetchReturn & PromiseLike> -export function useFetch(url: MaybeRef, ...args: any[]): UseFetchReturn & PromiseLike> { +export function useFetch(url: MaybeComputedRef, ...args: any[]): UseFetchReturn & PromiseLike> { const supportsAbort = typeof AbortController === 'function' let fetchOptions: RequestInit = {} @@ -360,11 +360,14 @@ export function useFetch(url: MaybeRef, ...args: any[]): UseFetchRetu if (config.payloadType) headers['Content-Type'] = payloadMapping[config.payloadType] ?? config.payloadType - defaultFetchOptions.body = config.payloadType === 'json' ? JSON.stringify(unref(config.payload)) : unref(config.payload) as BodyInit + const payload = resolveUnref(config.payload) + defaultFetchOptions.body = config.payloadType === 'json' + ? JSON.stringify(payload) + : payload as BodyInit } let isCanceled = false - const context: BeforeFetchContext = { url: unref(url), options: { ...defaultFetchOptions, ...fetchOptions }, cancel: () => { isCanceled = true } } + const context: BeforeFetchContext = { url: resolveUnref(url), options: { ...defaultFetchOptions, ...fetchOptions }, cancel: () => { isCanceled = true } } if (options.beforeFetch) Object.assign(context, await options.beforeFetch(context)) @@ -432,12 +435,13 @@ export function useFetch(url: MaybeRef, ...args: any[]): UseFetchRetu }) } + const refetch = resolveRef(options.refetch) watch( - () => [ - unref(url), - unref(options.refetch), + [ + refetch, + resolveRef(url), ], - () => unref(options.refetch) && execute(), + ([refetch]) => refetch && execute(), { deep: true }, ) @@ -482,18 +486,19 @@ export function useFetch(url: MaybeRef, ...args: any[]): UseFetchRetu // watch for payload changes if (isRef(config.payload)) { watch( - () => [ - unref(config.payload), - unref(options.refetch), + [ + refetch, + resolveRef(config.payload), ], - () => unref(options.refetch) && execute(), + ([refetch]) => refetch && execute(), { deep: true }, ) } + const rawPayload = resolveUnref(config.payload) // Set the payload to json type only if it's not provided and a literal object is provided // The only case we can deduce the content type and `fetch` can't - if (!payloadType && unref(payload) && Object.getPrototypeOf(unref(payload)) === Object.prototype) + if (!payloadType && rawPayload && Object.getPrototypeOf(rawPayload) === Object.prototype) config.payloadType = 'json' return { From 04320817209d7c0421c29f28684ff1f6491f5a67 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Fri, 8 Jul 2022 12:59:38 +0800 Subject: [PATCH 19/23] chore: update --- packages/core/useInfiniteScroll/index.ts | 9 +-- packages/core/useScroll/index.ts | 84 ++++++++++++------------ packages/integrations/useDrauu/index.ts | 4 +- 3 files changed, 48 insertions(+), 49 deletions(-) diff --git a/packages/core/useInfiniteScroll/index.ts b/packages/core/useInfiniteScroll/index.ts index 71fb7653214..b6b3d399a45 100644 --- a/packages/core/useInfiniteScroll/index.ts +++ b/packages/core/useInfiniteScroll/index.ts @@ -1,6 +1,7 @@ import type { UnwrapNestedRefs } from 'vue-demi' -import { nextTick, reactive, unref, watch } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' +import { nextTick, reactive, watch } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveUnref } from '@vueuse/shared' import type { UseScrollOptions } from '../useScroll' import { useScroll } from '../useScroll' @@ -33,7 +34,7 @@ export interface UseInfiniteScrollOptions extends UseScrollOptions { * @see https://vueuse.org/useInfiniteScroll */ export function useInfiniteScroll( - element: MaybeRef, + element: MaybeComputedRef, onLoadMore: (state: UnwrapNestedRefs>) => void | Promise, options: UseInfiniteScrollOptions = {}, ) { @@ -53,7 +54,7 @@ export function useInfiniteScroll( () => state.arrivedState[direction], async (v) => { if (v) { - const elem = unref(element) as Element + const elem = resolveUnref(element) as Element const previous = { height: elem?.scrollHeight ?? 0, width: elem?.scrollWidth ?? 0, diff --git a/packages/core/useScroll/index.ts b/packages/core/useScroll/index.ts index ee7720c7622..c80d8328549 100644 --- a/packages/core/useScroll/index.ts +++ b/packages/core/useScroll/index.ts @@ -1,6 +1,6 @@ import { reactive, ref } from 'vue-demi' import type { MaybeComputedRef } from '@vueuse/shared' -import { noop, resolveUnref, useDebounceFn, useThrottleFn } from '@vueuse/shared' +import { noop, useDebounceFn, useThrottleFn } from '@vueuse/shared' import { useEventListener } from '../useEventListener' export interface UseScrollOptions { @@ -95,55 +95,53 @@ export function useScroll( bottom: false, }) - if (resolveUnref(element)) { - const onScrollEnd = useDebounceFn((e: Event) => { - isScrolling.value = false - directions.left = false - directions.right = false - directions.top = false - directions.bottom = false - onStop(e) - }, throttle + idle) - - const onScrollHandler = (e: Event) => { - const eventTarget = ( - e.target === document ? (e.target as Document).documentElement : e.target - ) as HTMLElement - - const scrollLeft = eventTarget.scrollLeft - directions.left = scrollLeft < x.value - directions.right = scrollLeft > x.value - arrivedState.left = scrollLeft <= 0 + (offset.left || 0) - arrivedState.right + const onScrollEnd = useDebounceFn((e: Event) => { + isScrolling.value = false + directions.left = false + directions.right = false + directions.top = false + directions.bottom = false + onStop(e) + }, throttle + idle) + + const onScrollHandler = (e: Event) => { + const eventTarget = ( + e.target === document ? (e.target as Document).documentElement : e.target + ) as HTMLElement + + const scrollLeft = eventTarget.scrollLeft + directions.left = scrollLeft < x.value + directions.right = scrollLeft > x.value + arrivedState.left = scrollLeft <= 0 + (offset.left || 0) + arrivedState.right = scrollLeft + eventTarget.clientWidth >= eventTarget.scrollWidth - (offset.right || 0) - x.value = scrollLeft + x.value = scrollLeft - let scrollTop = eventTarget.scrollTop + let scrollTop = eventTarget.scrollTop - // patch for mobile compatible - if (e.target === document && !scrollTop) - scrollTop = document.body.scrollTop + // patch for mobile compatible + if (e.target === document && !scrollTop) + scrollTop = document.body.scrollTop - directions.top = scrollTop < y.value - directions.bottom = scrollTop > y.value - arrivedState.top = scrollTop <= 0 + (offset.top || 0) - arrivedState.bottom + directions.top = scrollTop < y.value + directions.bottom = scrollTop > y.value + arrivedState.top = scrollTop <= 0 + (offset.top || 0) + arrivedState.bottom = scrollTop + eventTarget.clientHeight >= eventTarget.scrollHeight - (offset.bottom || 0) - y.value = scrollTop - - isScrolling.value = true - onScrollEnd(e) - onScroll(e) - } - - useEventListener( - element, - 'scroll', - throttle ? useThrottleFn(onScrollHandler, throttle) : onScrollHandler, - eventListenerOptions, - ) + y.value = scrollTop + + isScrolling.value = true + onScrollEnd(e) + onScroll(e) } + useEventListener( + element, + 'scroll', + throttle ? useThrottleFn(onScrollHandler, throttle) : onScrollHandler, + eventListenerOptions, + ) + return { x, y, diff --git a/packages/integrations/useDrauu/index.ts b/packages/integrations/useDrauu/index.ts index e6924c82182..8b09c426372 100644 --- a/packages/integrations/useDrauu/index.ts +++ b/packages/integrations/useDrauu/index.ts @@ -2,7 +2,7 @@ import type { Ref } from 'vue-demi' import { ref, watch } from 'vue-demi' import type { Brush, Drauu, DrawingMode, Options } from 'drauu' import { createDrauu } from 'drauu' -import type { EventHookOn, MaybeElementRef } from '@vueuse/core' +import type { EventHookOn, MaybeComputedElementRef } from '@vueuse/core' import { createEventHook, unrefElement } from '@vueuse/core' import type { Fn } from '@vueuse/shared' import { tryOnScopeDispose } from '@vueuse/shared' @@ -36,7 +36,7 @@ export interface UseDrauuReturn { * @param options Drauu Options */ export function useDrauu( - target: MaybeElementRef, + target: MaybeComputedElementRef, options?: UseDrauuOptions, ): UseDrauuReturn { const drauuInstance = ref() From f5218defef6fefa3f17bbd31fe4ecfb366d4b89d Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Fri, 8 Jul 2022 13:10:40 +0800 Subject: [PATCH 20/23] feat: update --- packages/core/useLocalStorage/index.ts | 14 ++++++------- packages/core/useScriptTag/index.ts | 10 +++++----- packages/core/useSessionStorage/index.ts | 14 ++++++------- packages/core/useStorage/index.ts | 20 +++++++++---------- packages/core/useStorageAsync/index.ts | 20 +++++++++---------- packages/core/useSwipe/index.ts | 4 ++-- .../integrations/useAsyncValidator/index.ts | 16 +++++++++------ packages/integrations/useAxios/index.ts | 5 ++--- packages/integrations/useChangeCase/index.md | 2 +- packages/integrations/useChangeCase/index.ts | 19 +++++++++++++++--- packages/math/useProjection/index.ts | 7 +++++-- 11 files changed, 75 insertions(+), 56 deletions(-) diff --git a/packages/core/useLocalStorage/index.ts b/packages/core/useLocalStorage/index.ts index 01b11b98358..e630c763e9b 100644 --- a/packages/core/useLocalStorage/index.ts +++ b/packages/core/useLocalStorage/index.ts @@ -1,13 +1,13 @@ -import type { MaybeRef, RemovableRef } from '@vueuse/shared' +import type { MaybeComputedRef, RemovableRef } from '@vueuse/shared' import type { StorageOptions } from '../useStorage' import { useStorage } from '../useStorage' import { defaultWindow } from '../_configurable' -export function useLocalStorage(key: string, initialValue: MaybeRef, options?: StorageOptions): RemovableRef -export function useLocalStorage(key: string, initialValue: MaybeRef, options?: StorageOptions): RemovableRef -export function useLocalStorage(key: string, initialValue: MaybeRef, options?: StorageOptions): RemovableRef -export function useLocalStorage(key: string, initialValue: MaybeRef, options?: StorageOptions): RemovableRef -export function useLocalStorage(key: string, initialValue: MaybeRef, options?: StorageOptions): RemovableRef +export function useLocalStorage(key: string, initialValue: MaybeComputedRef, options?: StorageOptions): RemovableRef +export function useLocalStorage(key: string, initialValue: MaybeComputedRef, options?: StorageOptions): RemovableRef +export function useLocalStorage(key: string, initialValue: MaybeComputedRef, options?: StorageOptions): RemovableRef +export function useLocalStorage(key: string, initialValue: MaybeComputedRef, options?: StorageOptions): RemovableRef +export function useLocalStorage(key: string, initialValue: MaybeComputedRef, options?: StorageOptions): RemovableRef /** * Reactive LocalStorage. @@ -19,7 +19,7 @@ export function useLocalStorage(key: string, initialValue: MaybeRef */ export function useLocalStorage( key: string, - initialValue: MaybeRef, + initialValue: MaybeComputedRef, options: StorageOptions = {}, ): RemovableRef { const { window = defaultWindow } = options diff --git a/packages/core/useScriptTag/index.ts b/packages/core/useScriptTag/index.ts index 08d9d4e6b51..f4d501f5af1 100644 --- a/packages/core/useScriptTag/index.ts +++ b/packages/core/useScriptTag/index.ts @@ -1,6 +1,6 @@ -import type { MaybeRef } from '@vueuse/shared' -import { noop, tryOnMounted, tryOnUnmounted } from '@vueuse/shared' -import { ref, unref } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { noop, resolveUnref, tryOnMounted, tryOnUnmounted } from '@vueuse/shared' +import { ref } from 'vue-demi' import type { ConfigurableDocument } from '../_configurable' import { defaultDocument } from '../_configurable' @@ -55,7 +55,7 @@ export interface UseScriptTagOptions extends ConfigurableDocument { * @param options */ export function useScriptTag( - src: MaybeRef, + src: MaybeComputedRef, onLoaded: (el: HTMLScriptElement) => void = noop, options: UseScriptTagOptions = {}, ) { @@ -105,7 +105,7 @@ export function useScriptTag( el = document.createElement('script') el.type = type el.async = async - el.src = unref(src) + el.src = resolveUnref(src) // Optional attributes if (defer) diff --git a/packages/core/useSessionStorage/index.ts b/packages/core/useSessionStorage/index.ts index ee212cf8937..a1c03bb64f7 100644 --- a/packages/core/useSessionStorage/index.ts +++ b/packages/core/useSessionStorage/index.ts @@ -1,13 +1,13 @@ -import type { MaybeRef, RemovableRef } from '@vueuse/shared' +import type { MaybeComputedRef, RemovableRef } from '@vueuse/shared' import type { StorageOptions } from '../useStorage' import { useStorage } from '../useStorage' import { defaultWindow } from '../_configurable' -export function useSessionStorage(key: string, initialValue: MaybeRef, options?: StorageOptions): RemovableRef -export function useSessionStorage(key: string, initialValue: MaybeRef, options?: StorageOptions): RemovableRef -export function useSessionStorage(key: string, initialValue: MaybeRef, options?: StorageOptions): RemovableRef -export function useSessionStorage(key: string, initialValue: MaybeRef, options?: StorageOptions): RemovableRef -export function useSessionStorage(key: string, initialValue: MaybeRef, options?: StorageOptions): RemovableRef +export function useSessionStorage(key: string, initialValue: MaybeComputedRef, options?: StorageOptions): RemovableRef +export function useSessionStorage(key: string, initialValue: MaybeComputedRef, options?: StorageOptions): RemovableRef +export function useSessionStorage(key: string, initialValue: MaybeComputedRef, options?: StorageOptions): RemovableRef +export function useSessionStorage(key: string, initialValue: MaybeComputedRef, options?: StorageOptions): RemovableRef +export function useSessionStorage(key: string, initialValue: MaybeComputedRef, options?: StorageOptions): RemovableRef /** * Reactive SessionStorage. @@ -19,7 +19,7 @@ export function useSessionStorage(key: string, initialValue: MaybeR */ export function useSessionStorage( key: string, - initialValue: MaybeRef, + initialValue: MaybeComputedRef, options: StorageOptions = {}, ): RemovableRef { const { window = defaultWindow } = options diff --git a/packages/core/useStorage/index.ts b/packages/core/useStorage/index.ts index 59b8740572e..4f470a79e79 100644 --- a/packages/core/useStorage/index.ts +++ b/packages/core/useStorage/index.ts @@ -1,6 +1,6 @@ -import type { Awaitable, ConfigurableEventFilter, ConfigurableFlush, MaybeRef, RemovableRef } from '@vueuse/shared' -import { pausableWatch } from '@vueuse/shared' -import { ref, shallowRef, unref } from 'vue-demi' +import type { Awaitable, ConfigurableEventFilter, ConfigurableFlush, MaybeComputedRef, RemovableRef } from '@vueuse/shared' +import { pausableWatch, resolveUnref } from '@vueuse/shared' +import { ref, shallowRef } from 'vue-demi' import type { StorageLike } from '../ssr-handlers' import { getSSRHandler } from '../ssr-handlers' import { useEventListener } from '../useEventListener' @@ -95,11 +95,11 @@ export interface StorageOptions extends ConfigurableEventFilter, Configurable shallow?: boolean } -export function useStorage(key: string, initialValue: MaybeRef, storage?: StorageLike, options?: StorageOptions): RemovableRef -export function useStorage(key: string, initialValue: MaybeRef, storage?: StorageLike, options?: StorageOptions): RemovableRef -export function useStorage(key: string, initialValue: MaybeRef, storage?: StorageLike, options?: StorageOptions): RemovableRef -export function useStorage(key: string, initialValue: MaybeRef, storage?: StorageLike, options?: StorageOptions): RemovableRef -export function useStorage(key: string, initialValue: MaybeRef, storage?: StorageLike, options?: StorageOptions): RemovableRef +export function useStorage(key: string, initialValue: MaybeComputedRef, storage?: StorageLike, options?: StorageOptions): RemovableRef +export function useStorage(key: string, initialValue: MaybeComputedRef, storage?: StorageLike, options?: StorageOptions): RemovableRef +export function useStorage(key: string, initialValue: MaybeComputedRef, storage?: StorageLike, options?: StorageOptions): RemovableRef +export function useStorage(key: string, initialValue: MaybeComputedRef, storage?: StorageLike, options?: StorageOptions): RemovableRef +export function useStorage(key: string, initialValue: MaybeComputedRef, storage?: StorageLike, options?: StorageOptions): RemovableRef /** * Reactive LocalStorage/SessionStorage. @@ -112,7 +112,7 @@ export function useStorage(key: string, initialValue: MaybeRef( key: string, - initialValue: MaybeRef, + initialValue: MaybeComputedRef, storage: StorageLike | undefined, options: StorageOptions = {}, ): RemovableRef { @@ -142,7 +142,7 @@ export function useStorage if (!storage) return data - const rawInit: T = unref(initialValue) + const rawInit: T = resolveUnref(initialValue) const type = guessSerializerType(rawInit) const serializer = options.serializer ?? StorageSerializers[type] diff --git a/packages/core/useStorageAsync/index.ts b/packages/core/useStorageAsync/index.ts index 4081d0fd7a9..9fac08350c6 100644 --- a/packages/core/useStorageAsync/index.ts +++ b/packages/core/useStorageAsync/index.ts @@ -1,7 +1,7 @@ -import type { MaybeRef, RemovableRef } from '@vueuse/shared' -import { watchWithFilter } from '@vueuse/shared' +import type { MaybeComputedRef, RemovableRef } from '@vueuse/shared' +import { resolveUnref, watchWithFilter } from '@vueuse/shared' import type { Ref } from 'vue-demi' -import { ref, shallowRef, unref } from 'vue-demi' +import { ref, shallowRef } from 'vue-demi' import type { StorageLikeAsync } from '../ssr-handlers' import { getSSRHandler } from '../ssr-handlers' import type { SerializerAsync, StorageOptions } from '../useStorage' @@ -17,11 +17,11 @@ export interface StorageAsyncOptions extends Omit, 'seriali serializer?: SerializerAsync } -export function useStorageAsync(key: string, initialValue: MaybeRef, storage?: StorageLikeAsync, options?: StorageAsyncOptions): RemovableRef -export function useStorageAsync(key: string, initialValue: MaybeRef, storage?: StorageLikeAsync, options?: StorageAsyncOptions): RemovableRef -export function useStorageAsync(key: string, initialValue: MaybeRef, storage?: StorageLikeAsync, options?: StorageAsyncOptions): RemovableRef -export function useStorageAsync(key: string, initialValue: MaybeRef, storage?: StorageLikeAsync, options?: StorageAsyncOptions): RemovableRef -export function useStorageAsync(key: string, initialValue: MaybeRef, storage?: StorageLikeAsync, options?: StorageAsyncOptions): RemovableRef +export function useStorageAsync(key: string, initialValue: MaybeComputedRef, storage?: StorageLikeAsync, options?: StorageAsyncOptions): RemovableRef +export function useStorageAsync(key: string, initialValue: MaybeComputedRef, storage?: StorageLikeAsync, options?: StorageAsyncOptions): RemovableRef +export function useStorageAsync(key: string, initialValue: MaybeComputedRef, storage?: StorageLikeAsync, options?: StorageAsyncOptions): RemovableRef +export function useStorageAsync(key: string, initialValue: MaybeComputedRef, storage?: StorageLikeAsync, options?: StorageAsyncOptions): RemovableRef +export function useStorageAsync(key: string, initialValue: MaybeComputedRef, storage?: StorageLikeAsync, options?: StorageAsyncOptions): RemovableRef /** * Reactive Storage in with async support. @@ -34,7 +34,7 @@ export function useStorageAsync(key: string, initialValue: MaybeRef */ export function useStorageAsync( key: string, - initialValue: MaybeRef, + initialValue: MaybeComputedRef, storage: StorageLikeAsync | undefined, options: StorageAsyncOptions = {}, ): RemovableRef { @@ -51,7 +51,7 @@ export function useStorageAsync(rawInit) const data = (shallow ? shallowRef : ref)(initialValue) as Ref diff --git a/packages/core/useSwipe/index.ts b/packages/core/useSwipe/index.ts index a0d527657b1..a99b47ca102 100644 --- a/packages/core/useSwipe/index.ts +++ b/packages/core/useSwipe/index.ts @@ -1,4 +1,4 @@ -import type { MaybeRef } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' import { noop } from '@vueuse/shared' import type { ComputedRef, Ref } from 'vue-demi' import { computed, reactive, ref } from 'vue-demi' @@ -63,7 +63,7 @@ export interface SwipeReturn { * @param options */ export function useSwipe( - target: MaybeRef, + target: MaybeComputedRef, options: SwipeOptions = {}, ): SwipeReturn { const { diff --git a/packages/integrations/useAsyncValidator/index.ts b/packages/integrations/useAsyncValidator/index.ts index 26fcd097008..cec9e61b780 100644 --- a/packages/integrations/useAsyncValidator/index.ts +++ b/packages/integrations/useAsyncValidator/index.ts @@ -1,9 +1,9 @@ -import type { MaybeRef } from '@vueuse/shared' -import { until } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveUnref, until } from '@vueuse/shared' import Schema from 'async-validator' import type { Rules, ValidateError, ValidateOption } from 'async-validator' import type { Ref } from 'vue-demi' -import { computed, ref, unref, watchEffect } from 'vue-demi' +import { computed, ref, watchEffect } from 'vue-demi' export type AsyncValidatorError = Error & { errors: ValidateError[] @@ -31,7 +31,11 @@ export interface UseAsyncValidatorOptions { * @see https://vueuse.org/useAsyncValidator * @see https://github.com/yiminghe/async-validator */ -export function useAsyncValidator(value: MaybeRef>, rules: MaybeRef, options: UseAsyncValidatorOptions = {}): UseAsyncValidatorReturn & PromiseLike { +export function useAsyncValidator( + value: MaybeComputedRef>, + rules: MaybeComputedRef, + options: UseAsyncValidatorOptions = {}, +): UseAsyncValidatorReturn & PromiseLike { const errorInfo = ref() const isFinished = ref(false) const pass = ref(false) @@ -43,9 +47,9 @@ export function useAsyncValidator(value: MaybeRef>, rules: M watchEffect(async () => { isFinished.value = false pass.value = false - const validator = new Schema(unref(rules)) + const validator = new Schema(resolveUnref(rules)) try { - await validator.validate(unref(value), validateOption) + await validator.validate(resolveUnref(value), validateOption) pass.value = true errorInfo.value = null } diff --git a/packages/integrations/useAxios/index.ts b/packages/integrations/useAxios/index.ts index 8cdbf17e57c..f63a8e37ad0 100644 --- a/packages/integrations/useAxios/index.ts +++ b/packages/integrations/useAxios/index.ts @@ -5,7 +5,6 @@ import type { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, Canc import axios from 'axios' export interface UseAxiosReturn { - /** * Axios Response */ @@ -95,18 +94,18 @@ export interface UseAxiosOptions { immediate?: boolean } type OverallUseAxiosReturn = StrictUseAxiosReturn | EasyUseAxiosReturn + export function useAxios(url: string, config?: AxiosRequestConfig, options?: UseAxiosOptions): StrictUseAxiosReturn & PromiseLike> export function useAxios(url: string, instance?: AxiosInstance, options?: UseAxiosOptions): StrictUseAxiosReturn & PromiseLike> export function useAxios(url: string, config: AxiosRequestConfig, instance: AxiosInstance, options?: UseAxiosOptions): StrictUseAxiosReturn & PromiseLike> export function useAxios(config?: AxiosRequestConfig): EasyUseAxiosReturn & PromiseLike> export function useAxios(instance?: AxiosInstance): EasyUseAxiosReturn & PromiseLike> export function useAxios(config?: AxiosRequestConfig, instance?: AxiosInstance): EasyUseAxiosReturn & PromiseLike> + /** * Wrapper for axios. * * @see https://vueuse.org/useAxios - * @param url - * @param config */ export function useAxios(...args: any[]): OverallUseAxiosReturn & PromiseLike> { const url: string | undefined = typeof args[0] === 'string' ? args[0] : undefined diff --git a/packages/integrations/useChangeCase/index.md b/packages/integrations/useChangeCase/index.md index ccaf106a356..fa82185b13a 100644 --- a/packages/integrations/useChangeCase/index.md +++ b/packages/integrations/useChangeCase/index.md @@ -4,7 +4,7 @@ category: '@Integrations' # useChangeCase -wrapper for [`change-case`](https://github.com/blakeembrey/change-case) +Reactive wrapper for [`change-case`](https://github.com/blakeembrey/change-case) ## Install diff --git a/packages/integrations/useChangeCase/index.ts b/packages/integrations/useChangeCase/index.ts index 5aeadcd014d..aa32aed816a 100644 --- a/packages/integrations/useChangeCase/index.ts +++ b/packages/integrations/useChangeCase/index.ts @@ -1,11 +1,24 @@ import type { Options } from 'change-case' -import type { MaybeRef } from '@vueuse/shared' -import type { WritableComputedRef } from 'vue-demi' +import type { MaybeComputedRef, MaybeRef } from '@vueuse/shared' +import { isFunction, resolveUnref } from '@vueuse/shared' +import type { ComputedRef, WritableComputedRef } from 'vue-demi' import { computed, ref } from 'vue-demi' import * as changeCase from './changeCase' export type ChangeCaseType = keyof typeof changeCase -export function useChangeCase(input: MaybeRef, type: ChangeCaseType, options?: Options | undefined): WritableComputedRef { + +export function useChangeCase(input: MaybeRef, type: ChangeCaseType, options?: Options | undefined): WritableComputedRef +export function useChangeCase(input: MaybeComputedRef, type: ChangeCaseType, options?: Options | undefined): ComputedRef + +/** + * Reactive wrapper for `change-case` + * + * @see https://vueuse.org/useChangeCase + */ +export function useChangeCase(input: MaybeComputedRef, type: ChangeCaseType, options?: Options | undefined) { + if (isFunction(input)) + return computed(() => changeCase[type](resolveUnref(input), options)) + const text = ref(input) return computed({ get() { diff --git a/packages/math/useProjection/index.ts b/packages/math/useProjection/index.ts index c04b793a2c8..a2c2f5be32f 100644 --- a/packages/math/useProjection/index.ts +++ b/packages/math/useProjection/index.ts @@ -20,6 +20,7 @@ function useGenericProjection( valueEnd: MaybeRef, options: CoProjectionOptions ): readonly [Projector, CoProjector] + function useGenericProjection( domainStart: MaybeRef, domainEnd: MaybeRef, @@ -27,6 +28,7 @@ function useGenericProjection( valueEnd: MaybeRef, options: ProjectionOptions ): readonly [Projector] + function useGenericProjection( domainStart: MaybeRef, domainEnd: MaybeRef, @@ -34,6 +36,7 @@ function useGenericProjection( valueEnd: MaybeRef, options: ProjectionOptions | CoProjectionOptions ): readonly [Projector] | readonly [Projector, CoProjector] + function useGenericProjection( domainStart: MaybeRef, domainEnd: MaybeRef, @@ -53,13 +56,13 @@ function useGenericProjection( if (!valueToDomain) return [projector] as const - const coprojector = (value: MaybeRef) => computed(() => { + const coProjector = (value: MaybeRef) => computed(() => { return unref(valueToDomain)(unref(domainStart), unref(domainEnd), unref(valueStart), unref(valueEnd), unref(value)) }) return [ projector, - coprojector, + coProjector, ] as const } From a90c54fe774a3ada86d6ba66b8e97ee2ea5351b5 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Fri, 8 Jul 2022 13:23:45 +0800 Subject: [PATCH 21/23] chore: update --- packages/core/useFetch/index.ts | 4 +- packages/core/useMediaControls/index.ts | 48 ++++++++++----------- packages/integrations/useJwt/index.ts | 14 +++--- packages/integrations/useNProgress/index.ts | 12 ++---- packages/shared/until/index.ts | 25 +++++------ packages/shared/watchDebounced/index.ts | 4 +- packages/shared/watchThrottled/index.ts | 4 +- 7 files changed, 53 insertions(+), 58 deletions(-) diff --git a/packages/core/useFetch/index.ts b/packages/core/useFetch/index.ts index 01c6bab5218..02ef0d433c3 100644 --- a/packages/core/useFetch/index.ts +++ b/packages/core/useFetch/index.ts @@ -1,5 +1,5 @@ import type { ComputedRef, Ref } from 'vue-demi' -import type { EventHookOn, Fn, MaybeComputedRef, MaybeRef, Stoppable } from '@vueuse/shared' +import type { EventHookOn, Fn, MaybeComputedRef, Stoppable } from '@vueuse/shared' import { containsProp, createEventHook, resolveRef, resolveUnref, until, useTimeoutFn } from '@vueuse/shared' import { computed, isRef, ref, shallowRef, watch } from 'vue-demi' import { defaultWindow } from '../_configurable' @@ -185,7 +185,7 @@ export interface CreateFetchOptions { /** * The base URL that will be prefixed to all urls */ - baseUrl?: MaybeRef + baseUrl?: MaybeComputedRef /** * Default Options for the useFetch function diff --git a/packages/core/useMediaControls/index.ts b/packages/core/useMediaControls/index.ts index f479b58f07a..622bed79847 100644 --- a/packages/core/useMediaControls/index.ts +++ b/packages/core/useMediaControls/index.ts @@ -1,6 +1,6 @@ -import { ref, unref, watch, watchEffect } from 'vue-demi' -import type { Fn, MaybeRef } from '@vueuse/shared' -import { createEventHook, isNumber, isObject, isString, tryOnScopeDispose, watchIgnorable } from '@vueuse/shared' +import { ref, watch, watchEffect } from 'vue-demi' +import type { Fn, MaybeComputedRef, MaybeRef } from '@vueuse/shared' +import { createEventHook, isNumber, isObject, isString, resolveUnref, tryOnScopeDispose, watchIgnorable } from '@vueuse/shared' import { useEventListener } from '../useEventListener' import type { ConfigurableDocument } from '../_configurable' import { defaultDocument } from '../_configurable' @@ -58,12 +58,12 @@ interface UseMediaControlsOptions extends ConfigurableDocument { * The source for the media, may either be a string, a `UseMediaSource` object, or a list * of `UseMediaSource` objects. */ - src?: MaybeRef + src?: MaybeComputedRef /** * A list of text tracks for the media */ - tracks?: MaybeRef + tracks?: MaybeComputedRef } export interface UseMediaTextTrack { @@ -113,9 +113,9 @@ export interface UseMediaTextTrack { /** * Automatically check if the ref exists and if it does run the cb fn */ -function usingElRef(source: MaybeRef, cb: (el: T) => void) { - if (unref(source)) - cb(unref(source)) +function usingElRef(source: MaybeComputedRef, cb: (el: T) => void) { + if (resolveUnref(source)) + cb(resolveUnref(source)) } /** @@ -243,11 +243,11 @@ export function useMediaControls(target: MaybeRef { - const el = unref(target) + const el = resolveUnref(target) if (!el) return @@ -296,7 +296,7 @@ export function useMediaControls(target: MaybeRef { - const el = unref(target) + const el = resolveUnref(target) if (!el) return @@ -304,7 +304,7 @@ export function useMediaControls(target: MaybeRef { - const el = unref(target) + const el = resolveUnref(target) if (!el) return @@ -312,7 +312,7 @@ export function useMediaControls(target: MaybeRef { - const el = unref(target) + const el = resolveUnref(target) if (!el) return @@ -326,8 +326,8 @@ export function useMediaControls(target: MaybeRef { - const el = unref(target) + const el = resolveUnref(target) if (!el) return @@ -376,21 +376,21 @@ export function useMediaControls(target: MaybeRef { - const el = unref(target) + const el = resolveUnref(target) if (!el) return isPlaying ? el.play() : el.pause() }) - useEventListener(target, 'timeupdate', () => ignoreCurrentTimeUpdates(() => currentTime.value = (unref(target))!.currentTime)) - useEventListener(target, 'durationchange', () => duration.value = (unref(target))!.duration) - useEventListener(target, 'progress', () => buffered.value = timeRangeToArray((unref(target))!.buffered)) + useEventListener(target, 'timeupdate', () => ignoreCurrentTimeUpdates(() => currentTime.value = (resolveUnref(target))!.currentTime)) + useEventListener(target, 'durationchange', () => duration.value = (resolveUnref(target))!.duration) + useEventListener(target, 'progress', () => buffered.value = timeRangeToArray((resolveUnref(target))!.buffered)) useEventListener(target, 'seeking', () => seeking.value = true) useEventListener(target, 'seeked', () => seeking.value = false) useEventListener(target, 'waiting', () => waiting.value = true) useEventListener(target, 'playing', () => waiting.value = false) - useEventListener(target, 'ratechange', () => rate.value = (unref(target))!.playbackRate) + useEventListener(target, 'ratechange', () => rate.value = (resolveUnref(target))!.playbackRate) useEventListener(target, 'stalled', () => stalled.value = true) useEventListener(target, 'ended', () => ended.value = true) useEventListener(target, 'pause', () => ignorePlayingUpdates(() => playing.value = false)) @@ -398,7 +398,7 @@ export function useMediaControls(target: MaybeRef isPictureInPicture.value = true) useEventListener(target, 'leavepictureinpicture', () => isPictureInPicture.value = false) useEventListener(target, 'volumechange', () => { - const el = unref(target) + const el = resolveUnref(target) if (!el) return @@ -414,7 +414,7 @@ export function useMediaControls(target: MaybeRef { - const el = unref(target) + const el = resolveUnref(target) if (!el) return diff --git a/packages/integrations/useJwt/index.ts b/packages/integrations/useJwt/index.ts index bd6296f1ba9..ab6dad51645 100644 --- a/packages/integrations/useJwt/index.ts +++ b/packages/integrations/useJwt/index.ts @@ -1,6 +1,7 @@ import type { ComputedRef } from 'vue-demi' -import { computed, ref } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' +import { computed } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveUnref } from '@vueuse/shared' import jwt_decode from 'jwt-decode' import type { JwtDecodeOptions, JwtHeader, JwtPayload } from 'jwt-decode' @@ -34,11 +35,9 @@ export function useJwt< Header extends object = JwtHeader, Fallback = null, >( - encodedJwt: MaybeRef, + encodedJwt: MaybeComputedRef, options: JwtOptions = {}, ): JwtResult { - const encodedJwtRef = ref(encodedJwt) - const { onError, fallbackValue = null, @@ -54,9 +53,8 @@ export function useJwt< } } - const header = computed(() => decodeWithFallback
(encodedJwtRef.value, { header: true })) - - const payload = computed(() => decodeWithFallback(encodedJwtRef.value)) + const header = computed(() => decodeWithFallback
(resolveUnref(encodedJwt), { header: true })) + const payload = computed(() => decodeWithFallback(resolveUnref(encodedJwt))) return { header, diff --git a/packages/integrations/useNProgress/index.ts b/packages/integrations/useNProgress/index.ts index bd8d473a4f8..99a8914de5b 100644 --- a/packages/integrations/useNProgress/index.ts +++ b/packages/integrations/useNProgress/index.ts @@ -1,23 +1,19 @@ import type { NProgressOptions } from 'nprogress' import nprogress from 'nprogress' -import type { MaybeRef } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' import { isNumber, tryOnScopeDispose } from '@vueuse/shared' -import { computed, isRef, ref, watchEffect } from 'vue-demi' +import { computed, ref, watchEffect } from 'vue-demi' /** * Reactive progress bar. * * @see https://vueuse.org/useNProgress - * @param currentProgress - * @param options */ export function useNProgress( - currentProgress: MaybeRef = null, + currentProgress: MaybeComputedRef = null, options?: Partial, ) { - const progress = isRef(currentProgress) - ? currentProgress - : ref(currentProgress) + const progress = ref(currentProgress) const isLoading = computed({ set: load => load ? nprogress.start() : nprogress.done(), get: () => isNumber(progress.value) && progress.value < 1, diff --git a/packages/shared/until/index.ts b/packages/shared/until/index.ts index 499d8f1b610..66012c89978 100644 --- a/packages/shared/until/index.ts +++ b/packages/shared/until/index.ts @@ -1,6 +1,7 @@ import type { WatchOptions, WatchSource } from 'vue-demi' -import { isRef, unref, watch } from 'vue-demi' -import type { ElementOf, MaybeRef, ShallowUnwrapRef } from '../utils' +import { isRef, watch } from 'vue-demi' +import { resolveUnref } from '../resolveUnref' +import type { ElementOf, MaybeComputedRef, ShallowUnwrapRef } from '../utils' import { promiseTimeout } from '../utils' export interface UntilToMatchOptions { @@ -52,7 +53,7 @@ type Falsy = false | void | null | undefined | 0 | 0n | '' export interface UntilValueInstance extends UntilBaseInstance { readonly not: UntilValueInstance - toBe

(value: MaybeRef

, options?: UntilToMatchOptions): Not extends true ? Promise : Promise

+ toBe

(value: MaybeComputedRef

, options?: UntilToMatchOptions): Not extends true ? Promise : Promise

toBeTruthy(options?: UntilToMatchOptions): Not extends true ? Promise : Promise> toBeNull(options?: UntilToMatchOptions): Not extends true ? Promise> : Promise toBeUndefined(options?: UntilToMatchOptions): Not extends true ? Promise> : Promise @@ -62,7 +63,7 @@ export interface UntilValueInstance extends Unti export interface UntilArrayInstance extends UntilBaseInstance { readonly not: UntilArrayInstance - toContains(value: MaybeRef>>, options?: UntilToMatchOptions): Promise + toContains(value: MaybeComputedRef>>, options?: UntilToMatchOptions): Promise } /** @@ -78,8 +79,8 @@ export interface UntilArrayInstance extends UntilBaseInstance { * alert('Counter is now larger than 7!') * ``` */ -export function until(r: WatchSource | MaybeRef): UntilArrayInstance -export function until(r: WatchSource | MaybeRef): UntilValueInstance +export function until(r: WatchSource | MaybeComputedRef): UntilArrayInstance +export function until(r: WatchSource | MaybeComputedRef): UntilValueInstance export function until(r: any): any { let isNot = false @@ -109,7 +110,7 @@ export function until(r: any): any { if (timeout != null) { promises.push( promiseTimeout(timeout, throwOnTimeout) - .then(() => unref(r)) + .then(() => resolveUnref(r)) .finally(() => stop?.()), ) } @@ -117,7 +118,7 @@ export function until(r: any): any { return Promise.race(promises) } - function toBe

(value: MaybeRef

, options?: UntilToMatchOptions) { + function toBe

(value: MaybeComputedRef

, options?: UntilToMatchOptions) { if (!isRef(value)) return toMatch(v => v === value, options) @@ -144,10 +145,10 @@ export function until(r: any): any { if (timeout != null) { promises.push( promiseTimeout(timeout, throwOnTimeout) - .then(() => unref(r)) + .then(() => resolveUnref(r)) .finally(() => { stop?.() - return unref(r) + return resolveUnref(r) }), ) } @@ -177,7 +178,7 @@ export function until(r: any): any { ) { return toMatch((v) => { const array = Array.from(v as any) - return array.includes(value) || array.includes(unref(value)) + return array.includes(value) || array.includes(resolveUnref(value)) }, options) } @@ -193,7 +194,7 @@ export function until(r: any): any { }, options) } - if (Array.isArray(unref(r))) { + if (Array.isArray(resolveUnref(r))) { const instance: UntilArrayInstance = { toMatch, toContains, diff --git a/packages/shared/watchDebounced/index.ts b/packages/shared/watchDebounced/index.ts index 42b74cc27c5..d1ce08dc6f9 100644 --- a/packages/shared/watchDebounced/index.ts +++ b/packages/shared/watchDebounced/index.ts @@ -1,10 +1,10 @@ import type { WatchCallback, WatchOptions, WatchSource, WatchStopHandle } from 'vue-demi' -import type { DebounceFilterOptions, MapOldSources, MapSources, MaybeRef } from '../utils' +import type { DebounceFilterOptions, MapOldSources, MapSources, MaybeComputedRef } from '../utils' import { debounceFilter } from '../utils' import { watchWithFilter } from '../watchWithFilter' export interface WatchDebouncedOptions extends WatchOptions, DebounceFilterOptions { - debounce?: MaybeRef + debounce?: MaybeComputedRef } // overlads diff --git a/packages/shared/watchThrottled/index.ts b/packages/shared/watchThrottled/index.ts index 53a0eb23570..ad259a4e2f7 100644 --- a/packages/shared/watchThrottled/index.ts +++ b/packages/shared/watchThrottled/index.ts @@ -1,10 +1,10 @@ import type { WatchCallback, WatchOptions, WatchSource, WatchStopHandle } from 'vue-demi' -import type { MapOldSources, MapSources, MaybeRef } from '../utils' +import type { MapOldSources, MapSources, MaybeComputedRef } from '../utils' import { throttleFilter } from '../utils' import { watchWithFilter } from '../watchWithFilter' export interface WatchThrottledOptions extends WatchOptions { - throttle?: MaybeRef + throttle?: MaybeComputedRef trailing?: boolean leading?: boolean } From c1113259536250490fbb0ebb0b74773b699d9698 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Fri, 8 Jul 2022 13:26:04 +0800 Subject: [PATCH 22/23] chore: update --- packages/core/useMagicKeys/index.ts | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/packages/core/useMagicKeys/index.ts b/packages/core/useMagicKeys/index.ts index b699f30a241..f90bd79448d 100644 --- a/packages/core/useMagicKeys/index.ts +++ b/packages/core/useMagicKeys/index.ts @@ -1,6 +1,6 @@ import type { ComputedRef } from 'vue-demi' import { computed, reactive, ref, unref } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' import { noop } from '@vueuse/shared' import { useEventListener } from '../useEventListener' import { defaultWindow } from '../_configurable' @@ -19,7 +19,7 @@ export interface UseMagicKeysOptions { * * @default window */ - target?: MaybeRef + target?: MaybeComputedRef /** * Alias map for keys, all the keys should be lowercase @@ -126,16 +126,14 @@ export function useMagicKeys(options: UseMagicKeysOptions = {}): any { } } - if (target) { - useEventListener(target, 'keydown', (e: KeyboardEvent) => { - updateRefs(e, true) - return onEventFired(e) - }, { passive }) - useEventListener(target, 'keyup', (e: KeyboardEvent) => { - updateRefs(e, false) - return onEventFired(e) - }, { passive }) - } + useEventListener(target, 'keydown', (e: KeyboardEvent) => { + updateRefs(e, true) + return onEventFired(e) + }, { passive }) + useEventListener(target, 'keyup', (e: KeyboardEvent) => { + updateRefs(e, false) + return onEventFired(e) + }, { passive }) const proxy = new Proxy( refs, From e57f03054e589532ce0a15b8f5f0f8cfc4ecdfc0 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Fri, 8 Jul 2022 13:38:48 +0800 Subject: [PATCH 23/23] chore: update --- packages/integrations/useFuse/index.ts | 35 +++++++++++++------------- packages/shared/logicAnd/index.ts | 9 ++++--- packages/shared/logicNot/index.ts | 9 ++++--- packages/shared/logicOr/index.ts | 9 ++++--- packages/shared/refAutoReset/index.ts | 9 ++++--- packages/shared/useInterval/index.ts | 8 +++--- packages/shared/useIntervalFn/index.ts | 7 +++--- packages/shared/useThrottleFn/index.ts | 4 +-- packages/shared/useToggle/index.ts | 29 +++++++++++++-------- packages/shared/watchAtMost/index.ts | 9 ++++--- 10 files changed, 71 insertions(+), 57 deletions(-) diff --git a/packages/integrations/useFuse/index.ts b/packages/integrations/useFuse/index.ts index d987afd5ad6..8c14bfb5e69 100644 --- a/packages/integrations/useFuse/index.ts +++ b/packages/integrations/useFuse/index.ts @@ -1,7 +1,8 @@ import Fuse from 'fuse.js' import type { ComputedRef } from 'vue-demi' import { computed, ref, unref, watch } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveUnref } from '@vueuse/shared' export type FuseOptions = Fuse.IFuseOptions export interface UseFuseOptions { @@ -11,44 +12,44 @@ export interface UseFuseOptions { } export function useFuse( - search: MaybeRef, - data: MaybeRef, - options?: MaybeRef>, + search: MaybeComputedRef, + data: MaybeComputedRef, + options?: MaybeComputedRef>, ) { - const createFuse = (data: MaybeRef, options?: FuseOptions) => { - const _options = options - + const createFuse = () => { return new Fuse( - unref(data) ?? [], - _options, + resolveUnref(data) ?? [], + resolveUnref(options)?.fuseOptions, ) } - const fuse = ref(createFuse(data, unref(options)?.fuseOptions)) + const fuse = ref(createFuse()) watch( - () => unref(options)?.fuseOptions, - (newOptions) => { fuse.value = createFuse(data, newOptions) }, + () => resolveUnref(options)?.fuseOptions, + () => { fuse.value = createFuse() }, { deep: true }, ) watch( - () => unref(data), + () => resolveUnref(data), (newData) => { fuse.value.setCollection(newData) }, { deep: true }, ) const results: ComputedRef[]> = computed(() => { + const resolved = resolveUnref(options) // This will also be recomputed when `data` changes, as it causes a change // to the Fuse instance, which is tracked here. - if (unref(options)?.matchAllWhenSearchEmpty && !unref(search)) - return unref(data).map((item, index) => ({ item, refIndex: index })) + if (resolved?.matchAllWhenSearchEmpty && !unref(search)) + return resolveUnref(data).map((item, index) => ({ item, refIndex: index })) - const limit = unref(options)?.resultLimit - return fuse.value.search(unref(search), (limit ? { limit } : undefined)) + const limit = resolved?.resultLimit + return fuse.value.search(resolveUnref(search), (limit ? { limit } : undefined)) }) return { + fuse, results, } } diff --git a/packages/shared/logicAnd/index.ts b/packages/shared/logicAnd/index.ts index 1906732c9b6..900893696e2 100644 --- a/packages/shared/logicAnd/index.ts +++ b/packages/shared/logicAnd/index.ts @@ -1,14 +1,15 @@ import type { ComputedRef } from 'vue-demi' -import { computed, unref } from 'vue-demi' -import type { MaybeRef } from '../utils' +import { computed } from 'vue-demi' +import { resolveUnref } from '../resolveUnref' +import type { MaybeComputedRef } from '../utils' /** * `AND` conditions for refs. * * @see https://vueuse.org/logicAnd */ -export function logicAnd(...args: MaybeRef[]): ComputedRef { - return computed(() => args.every(i => unref(i))) +export function logicAnd(...args: MaybeComputedRef[]): ComputedRef { + return computed(() => args.every(i => resolveUnref(i))) } // alias diff --git a/packages/shared/logicNot/index.ts b/packages/shared/logicNot/index.ts index a6d931a4357..93295023f48 100644 --- a/packages/shared/logicNot/index.ts +++ b/packages/shared/logicNot/index.ts @@ -1,14 +1,15 @@ import type { ComputedRef } from 'vue-demi' -import { computed, unref } from 'vue-demi' -import type { MaybeRef } from '../utils' +import { computed } from 'vue-demi' +import { resolveUnref } from '../resolveUnref' +import type { MaybeComputedRef } from '../utils' /** * `NOT` conditions for refs. * * @see https://vueuse.org/logicNot */ -export function logicNot(v: MaybeRef): ComputedRef { - return computed(() => !unref(v)) +export function logicNot(v: MaybeComputedRef): ComputedRef { + return computed(() => !resolveUnref(v)) } // alias diff --git a/packages/shared/logicOr/index.ts b/packages/shared/logicOr/index.ts index e90c945d033..997eb95ffcd 100644 --- a/packages/shared/logicOr/index.ts +++ b/packages/shared/logicOr/index.ts @@ -1,14 +1,15 @@ import type { ComputedRef } from 'vue-demi' -import { computed, unref } from 'vue-demi' -import type { MaybeRef } from '../utils' +import { computed } from 'vue-demi' +import { resolveUnref } from '../resolveUnref' +import type { MaybeComputedRef } from '../utils' /** * `OR` conditions for refs. * * @see https://vueuse.org/logicOr */ -export function logicOr(...args: MaybeRef[]): ComputedRef { - return computed(() => args.some(i => unref(i))) +export function logicOr(...args: MaybeComputedRef[]): ComputedRef { + return computed(() => args.some(i => resolveUnref(i))) } // alias diff --git a/packages/shared/refAutoReset/index.ts b/packages/shared/refAutoReset/index.ts index 8e7016fd49a..4ac8f94be49 100644 --- a/packages/shared/refAutoReset/index.ts +++ b/packages/shared/refAutoReset/index.ts @@ -1,6 +1,7 @@ import type { Ref } from 'vue-demi' -import { customRef, unref } from 'vue-demi' -import type { MaybeRef } from '@vueuse/shared' +import { customRef } from 'vue-demi' +import { resolveUnref } from '@vueuse/shared' +import type { MaybeComputedRef } from '@vueuse/shared' import { tryOnScopeDispose } from '../tryOnScopeDispose' /** @@ -10,7 +11,7 @@ import { tryOnScopeDispose } from '../tryOnScopeDispose' * @param defaultValue The value which will be set. * @param afterMs A zero-or-greater delay in milliseconds. */ -export function refAutoReset(defaultValue: T, afterMs: MaybeRef = 10000): Ref { +export function refAutoReset(defaultValue: T, afterMs: MaybeComputedRef = 10000): Ref { return customRef((track, trigger) => { let value: T = defaultValue let timer: any @@ -19,7 +20,7 @@ export function refAutoReset(defaultValue: T, afterMs: MaybeRef = 100 setTimeout(() => { value = defaultValue trigger() - }, unref(afterMs)) + }, resolveUnref(afterMs)) tryOnScopeDispose(() => { clearTimeout(timer) diff --git a/packages/shared/useInterval/index.ts b/packages/shared/useInterval/index.ts index a508101b1c4..0f7cd835f11 100644 --- a/packages/shared/useInterval/index.ts +++ b/packages/shared/useInterval/index.ts @@ -1,6 +1,6 @@ import type { Ref } from 'vue-demi' import { ref } from 'vue-demi' -import type { MaybeRef, Pausable } from '../utils' +import type { MaybeComputedRef, Pausable } from '../utils' import { useIntervalFn } from '../useIntervalFn' export interface IntervalOptions { @@ -19,9 +19,9 @@ export interface IntervalOptions { immediate?: boolean } -export function useInterval(interval?: MaybeRef, options?: IntervalOptions): Ref -export function useInterval(interval: MaybeRef, options: IntervalOptions): { counter: Ref } & Pausable -export function useInterval(interval: MaybeRef = 1000, options: IntervalOptions = {}) { +export function useInterval(interval?: MaybeComputedRef, options?: IntervalOptions): Ref +export function useInterval(interval: MaybeComputedRef, options: IntervalOptions): { counter: Ref } & Pausable +export function useInterval(interval: MaybeComputedRef = 1000, options: IntervalOptions = {}) { const { controls: exposeControls = false, immediate = true, diff --git a/packages/shared/useIntervalFn/index.ts b/packages/shared/useIntervalFn/index.ts index 68b5d00c165..d7cb7290fba 100644 --- a/packages/shared/useIntervalFn/index.ts +++ b/packages/shared/useIntervalFn/index.ts @@ -1,6 +1,7 @@ import { isRef, ref, unref, watch } from 'vue-demi' +import { resolveUnref } from '../resolveUnref' import { tryOnScopeDispose } from '../tryOnScopeDispose' -import type { Fn, MaybeRef, Pausable } from '../utils' +import type { Fn, MaybeComputedRef, Pausable } from '../utils' import { isClient } from '../utils' export interface IntervalFnOptions { @@ -26,7 +27,7 @@ export interface IntervalFnOptions { * @param interval * @param options */ -export function useIntervalFn(cb: Fn, interval: MaybeRef = 1000, options: IntervalFnOptions = {}): Pausable { +export function useIntervalFn(cb: Fn, interval: MaybeComputedRef = 1000, options: IntervalFnOptions = {}): Pausable { const { immediate = true, immediateCallback = false, @@ -54,7 +55,7 @@ export function useIntervalFn(cb: Fn, interval: MaybeRef = 1000, options if (immediateCallback) cb() clean() - timer = setInterval(cb, unref(interval)) + timer = setInterval(cb, resolveUnref(interval)) } if (immediate && isClient) diff --git a/packages/shared/useThrottleFn/index.ts b/packages/shared/useThrottleFn/index.ts index a5d9c12c0ee..56103d92afb 100644 --- a/packages/shared/useThrottleFn/index.ts +++ b/packages/shared/useThrottleFn/index.ts @@ -1,4 +1,4 @@ -import type { FunctionArgs, MaybeRef } from '../utils' +import type { FunctionArgs, MaybeComputedRef } from '../utils' import { createFilterWrapper, throttleFilter } from '../utils' /** @@ -15,7 +15,7 @@ import { createFilterWrapper, throttleFilter } from '../utils' * * @return A new, throttled, function. */ -export function useThrottleFn(fn: T, ms: MaybeRef = 200, trailing = false, leading = true): T { +export function useThrottleFn(fn: T, ms: MaybeComputedRef = 200, trailing = false, leading = true): T { return createFilterWrapper( throttleFilter(ms, trailing, leading), fn, diff --git a/packages/shared/useToggle/index.ts b/packages/shared/useToggle/index.ts index 21c4ba69cd9..b891a710f65 100644 --- a/packages/shared/useToggle/index.ts +++ b/packages/shared/useToggle/index.ts @@ -1,10 +1,11 @@ import type { Ref } from 'vue-demi' -import { isRef, ref, unref } from 'vue-demi' -import type { MaybeRef } from '../utils' +import { isRef, ref } from 'vue-demi' +import { resolveUnref } from '../resolveUnref' +import type { MaybeComputedRef, MaybeRef } from '../utils' export interface UseToggleOptions { - truthyValue?: MaybeRef - falsyValue?: MaybeRef + truthyValue?: MaybeComputedRef + falsyValue?: MaybeComputedRef } export function useToggle(initialValue: Ref, options?: UseToggleOptions): (value?: T) => T @@ -16,29 +17,35 @@ export function useToggle(init * @see https://vueuse.org/useToggle * @param [initialValue=false] */ -export function useToggle(initialValue: MaybeRef = false, options: UseToggleOptions = {}) { +export function useToggle( + initialValue: MaybeRef = false, + options: UseToggleOptions = {}, +) { const { truthyValue = true, falsyValue = false, } = options const valueIsRef = isRef(initialValue) - const innerValue = ref(initialValue) as Ref + const _value = ref(initialValue) as Ref function toggle(value?: boolean) { // has arguments if (arguments.length) { - innerValue.value = value! - return innerValue.value + _value.value = value! + return _value.value } else { - innerValue.value = innerValue.value === unref(truthyValue) ? unref(falsyValue) : unref(truthyValue) - return innerValue.value + const truthy = resolveUnref(truthyValue) + _value.value = _value.value === truthy + ? resolveUnref(falsyValue) + : truthy + return _value.value } } if (valueIsRef) return toggle else - return [innerValue, toggle] as const + return [_value, toggle] as const } diff --git a/packages/shared/watchAtMost/index.ts b/packages/shared/watchAtMost/index.ts index ddbc1c87fbc..c5f82175f48 100644 --- a/packages/shared/watchAtMost/index.ts +++ b/packages/shared/watchAtMost/index.ts @@ -1,11 +1,12 @@ import type { Ref, WatchCallback, WatchSource, WatchStopHandle } from 'vue-demi' -import { nextTick, ref, unref } from 'vue-demi' -import type { MapOldSources, MapSources, MaybeRef } from '../utils' +import { nextTick, ref } from 'vue-demi' +import { resolveUnref } from '../resolveUnref' +import type { MapOldSources, MapSources, MaybeComputedRef } from '../utils' import type { WatchWithFilterOptions } from '../watchWithFilter' import { watchWithFilter } from '../watchWithFilter' export interface WatchAtMostOptions extends WatchWithFilterOptions { - count: MaybeRef + count: MaybeComputedRef } export interface WatchAtMostReturn { @@ -35,7 +36,7 @@ export function watchAtMost = false>( source, (...args) => { current.value += 1 - if (current.value >= unref(count)) + if (current.value >= resolveUnref(count)) nextTick(() => stop()) cb(...args)