Skip to content

Commit

Permalink
fix: prevent preset variants from being mutated (#182)
Browse files Browse the repository at this point in the history
  • Loading branch information
BobbieGoede authored Apr 20, 2024
1 parent cd99fda commit e8b0b47
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
9 changes: 6 additions & 3 deletions src/directive/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,19 @@ import { resolveVariants } from '../utils/directive'
import { variantToStyle } from '../utils/transform'
import { registerVisibilityHooks } from '../features/visibilityHooks'

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

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

// We deep copy presets to prevent global mutation
const variantsObject = isPreset ? structuredClone(variants || {}) : variants || {}

// Initialize variants with argument
const variantsRef = ref(variants || {}) as Ref<MotionVariants<T>>
const variantsRef = ref(variantsObject) as Ref<MotionVariants<T>>

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

// Merge it with directive initial variants
const initial = defu(variants?.initial || {}, bindingInitial || {})
const initial = defu({}, variants?.initial || {}, bindingInitial || {})

// No initial
if (!initial || Object.keys(initial).length === 0) return
Expand Down
4 changes: 2 additions & 2 deletions src/plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const MotionPlugin: Plugin = {
const preset = presets[key]

// Register the preset `v-motion-${key}` directive
app.directive(`motion-${slugify(key)}`, directive(preset))
app.directive(`motion-${slugify(key)}`, directive(preset, true))
}
}

Expand All @@ -38,7 +38,7 @@ export const MotionPlugin: Plugin = {
}

// Register the custom `v-motion-${key}` directive
app.directive(`motion-${key}`, directive(variants))
app.directive(`motion-${key}`, directive(variants, true))
}
}
},
Expand Down

0 comments on commit e8b0b47

Please sign in to comment.