Open History to see the last commit
1import * as Vue from 'vue'
2β
3export const useLayoutEffect =
4 typeof window !== 'undefined' ? Vue.effect : Vue.effect
5β
6export const usePrevious = (fn: () => boolean) => {
7 return Vue.computed(
8 (
9 prev: { current: boolean | null; previous: boolean | null } = {
10 current: null,
11 previous: null,
12 },
13 ) => {
14 const current = fn()
15β
16 if (prev.current !== current) {
17 prev.previous = prev.current
18 prev.current = current
19 }
20β
21 return prev
22 },
23 )
24}
25β
26/**
27 * React hook to wrap `IntersectionObserver`.
28 *
29 * This hook will create an `IntersectionObserver` and observe the ref passed to it.
30 *
31 * When the intersection changes, the callback will be called with the `IntersectionObserverEntry`.
32 *
33 * @param ref - The ref to observe
34 * @param callback - The callback to call when the intersection changes
35 * @param disabled - Whether observation is disabled
36 * @param cleanupWhenDisabled - Whether cleanup is needed without an observer (defaults to true)
37 * @example
38 * ```tsx
39 * const MyComponent = () => {
40 * const ref = React.useRef<HTMLDivElement>(null)
41 * useIntersectionObserver(
42 * ref,
43 * (entry) => { doSomething(entry) },
44 * () => false
45 * )
46 * return <div ref={ref} />
47 * ```
48 */
49export function useIntersectionObserver<T extends Element>(
50 ref: Vue.Ref<T | null>,
51 callback: (entry?: IntersectionObserverEntry) => void,
52 disabled: () => boolean,
53 cleanupWhenDisabled?: () => boolean,
54): void {
55 const isIntersectionObserverAvailable =
56 typeof IntersectionObserver === 'function'
57β
58 // Use watchEffect with cleanup to properly manage the observer lifecycle
59 Vue.watchEffect((onCleanup) => {
60 const r = ref.value
61 if (disabled() || !r || !isIntersectionObserverAvailable) {
62 if (cleanupWhenDisabled?.() ?? true) {
63 onCleanup(() => callback())
64 }
65 return
66 }
67β
68 let active = true
69 const observer = new IntersectionObserver(
70 (entries) => {
71 // Queued notifications can arrive after this effect has cleaned up.
72 if (active) {
73 callback(entries.pop())
74 }
75 },
76 { rootMargin: '100px' },
77 )
78β
79 observer.observe(r)
80β
81 onCleanup(() => {
82 active = false
83 observer.disconnect()
84 callback()
85 })
86 })
87}
88β
89export function splitProps<T extends Record<string, any>>(
90 props: T,
91 keys: Array<keyof T>,
92) {
93 // Get the specified props
94 const selectedProps = Vue.computed(() => {
95 return Object.fromEntries(keys.map((key) => [key, props[key]]))
96 })
97β
98 // Get remaining props as attrs
99 const remainingAttrs = Vue.computed(() => {
100 const attrs = Vue.useAttrs()
101 return Object.fromEntries(
102 Object.entries(attrs).filter(([key]) => !keys.includes(key as keyof T)),
103 )
104 })
105β
106 return [selectedProps, remainingAttrs]
107}
108β
109export type ParentProps<T = {}> = T & {
110 children?: Vue.VNode | Array<Vue.VNode> | string
111}