|
| 1 | +import autoAnimate, { type AutoAnimateOptions, type AutoAnimationPlugin } from '@formkit/auto-animate' |
| 2 | +import type { Ref } from 'vue' |
| 3 | + |
| 4 | +/** |
| 5 | + * Composable to apply autoAnimate to an element |
| 6 | + * @param options - AutoAnimate options |
| 7 | + * @returns A function that can be used as a template ref |
| 8 | + */ |
| 9 | +export function useAutoAnimate<T extends HTMLElement>( |
| 10 | + options?: Partial<AutoAnimateOptions> | AutoAnimationPlugin, |
| 11 | +): [(el: T | null) => void, (enabled: boolean) => void] { |
| 12 | + let autoAnimateController: ReturnType<typeof autoAnimate> | undefined |
| 13 | + |
| 14 | + const setEnabled = (enabled: boolean) => { |
| 15 | + if (autoAnimateController) { |
| 16 | + autoAnimateController.isEnabled = enabled |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + const ref = (el: T | null) => { |
| 21 | + if (el) { |
| 22 | + autoAnimateController = autoAnimate(el, options || {}) |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + return [ref, setEnabled] |
| 27 | +} |
| 28 | + |
| 29 | +/** |
| 30 | + * Apply autoAnimate directly to a ref element |
| 31 | + * @param target - The ref to apply autoAnimate to |
| 32 | + * @param options - AutoAnimate options |
| 33 | + */ |
| 34 | +export function applyAutoAnimate<T extends HTMLElement>( |
| 35 | + target: Ref<T | null | undefined>, |
| 36 | + options?: Partial<AutoAnimateOptions> | AutoAnimationPlugin, |
| 37 | +): void { |
| 38 | + watch( |
| 39 | + target, |
| 40 | + (el) => { |
| 41 | + if (el) { |
| 42 | + autoAnimate(el, options || {}) |
| 43 | + } |
| 44 | + }, |
| 45 | + { immediate: true }, |
| 46 | + ) |
| 47 | +} |
| 48 | + |
0 commit comments