Skip to content

Commit e8b0b47

Browse files
authored
fix: prevent preset variants from being mutated (#182)
1 parent cd99fda commit e8b0b47

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

src/directive/index.ts

+6-3
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,19 @@ import { resolveVariants } from '../utils/directive'
88
import { variantToStyle } from '../utils/transform'
99
import { registerVisibilityHooks } from '../features/visibilityHooks'
1010

11-
export function directive<T extends string>(variants?: MotionVariants<T>): Directive<HTMLElement | SVGElement> {
11+
export function directive<T extends string>(variants?: MotionVariants<T>, isPreset = false): Directive<HTMLElement | SVGElement> {
1212
const register = (el: HTMLElement | SVGElement, binding: DirectiveBinding, node: VNode<any, HTMLElement | SVGElement, Record<string, any>>) => {
1313
// Get instance key if possible (binding value or element key in case of v-for's)
1414
const key = (binding.value && typeof binding.value === 'string' ? binding.value : node.key) as string
1515

1616
// Cleanup previous motion instance if it exists
1717
if (key && motionState[key]) motionState[key].stop()
1818

19+
// We deep copy presets to prevent global mutation
20+
const variantsObject = isPreset ? structuredClone(variants || {}) : variants || {}
21+
1922
// Initialize variants with argument
20-
const variantsRef = ref(variants || {}) as Ref<MotionVariants<T>>
23+
const variantsRef = ref(variantsObject) as Ref<MotionVariants<T>>
2124

2225
// Set variants from v-motion binding
2326
if (typeof binding.value === 'object') variantsRef.value = binding.value
@@ -58,7 +61,7 @@ export function directive<T extends string>(variants?: MotionVariants<T>): Direc
5861
bindingInitial = unref(bindingInitial)
5962

6063
// Merge it with directive initial variants
61-
const initial = defu(variants?.initial || {}, bindingInitial || {})
64+
const initial = defu({}, variants?.initial || {}, bindingInitial || {})
6265

6366
// No initial
6467
if (!initial || Object.keys(initial).length === 0) return

src/plugin/index.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ export const MotionPlugin: Plugin = {
2121
const preset = presets[key]
2222

2323
// Register the preset `v-motion-${key}` directive
24-
app.directive(`motion-${slugify(key)}`, directive(preset))
24+
app.directive(`motion-${slugify(key)}`, directive(preset, true))
2525
}
2626
}
2727

@@ -38,7 +38,7 @@ export const MotionPlugin: Plugin = {
3838
}
3939

4040
// Register the custom `v-motion-${key}` directive
41-
app.directive(`motion-${key}`, directive(variants))
41+
app.directive(`motion-${key}`, directive(variants, true))
4242
}
4343
}
4444
},

0 commit comments

Comments
 (0)