Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DRAFT] feat: configurable <MotionGroup> child element variants using :config-fn prop #193

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions docs/components/content/examples/MotionComponent.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<script lang="ts" setup></script>

<template>
<div class="example-wrapper">
<div class="example-hint">Scroll down to trigger motion!</div>
<Motion is="p" preset="slideVisibleLeft">
<div class="example-target">Text in Motion!</div>
</Motion>
</div>
</template>

<style scoped>
.example-wrapper {
height: 200px;
width: 100%;
overflow-y: scroll;
overflow-x: hidden;
text-align: center;
border: 1px solid #222;
border-radius: 0.5em;
}

.example-hint,
p {
display: flex;
flex: 1 0;

align-items: center;
justify-content: center;

height: 100%;
padding: 2em;
}

.example-target {
padding: 1em;
background-color: #111;
border-radius: 0.5em;
}
</style>
58 changes: 58 additions & 0 deletions docs/components/content/examples/MotionGroupComponent.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<script lang="ts" setup></script>

<template>
<div class="example-wrapper">
<div class="example-hint">Scroll down to trigger motion!</div>
<MotionGroup preset="slideVisibleLeft" :config-fn="(index) => ({ delay: index * 200 })">
<section>
<h3>Product 1</h3>
<p>Description text</p>
</section>
<section>
<h3>Product 2</h3>
<p>Description text</p>
</section>
<section>
<h3>Product 3</h3>
<p>Description text</p>
</section>
</MotionGroup>
</div>
</template>

<style scoped>
.example-wrapper {
height: 200px;
width: 100%;
overflow-y: scroll;
overflow-x: hidden;
text-align: center;
border: 1px solid #222;
border-radius: 0.5em;
}

.example-hint,
p,
section {
display: flex;
flex-direction: column;

flex: 1 0;
align-items: center;
justify-content: center;

height: 100%;
padding: 2em;
}

section {
background-color: #111;
height: calc(100% / 3);
}

section h3,
section p {
margin: 0.5em !important;
padding: 0 !important;
}
</style>
98 changes: 98 additions & 0 deletions docs/content/2.features/7.components.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Components

vueuse/motion allows you to implement your animations directly within the template of your components without the need to wrap target elements in any additional components.

These components work similar to the directive `v-motion` usage but work better in projects using server-side rendering.

## `<Motion>`

Example of a `<Motion>` component using a motion preset on a `<p>` element:

```vue
<template>
<Motion is="p" preset="slideVisibleLeft">Text in Motion!</Motion>
</template>
```

<MotionComponent></MotionComponent>

## `<MotionGroup>`

The `<MotionGroup>` can be used to apply motion configuration to all of its child elements, this component is renderless by default and can be used as a wrapper by passing a value to the `:is` prop.

```vue
<template>
<MotionGroup preset="slideVisibleLeft" :config-fn="(index) => ({ delay: index * 200 })">
<section>
<h3>Product 1</h3>
<p>Description text</p>
</section>
<section>
<h3>Product 2</h3>
<p>Description text</p>
</section>
<section>
<h3>Product 3</h3>
<p>Description text</p>
</section>
</MotionGroup>
</template>
```

<MotionGroupComponent></MotionGroupComponent>


## Props

The `<Motion>` and `<MotionGroup>` components allow you to define animation properties (variants) as props.

- **`is`**: What element should rendered (`div` by default for `<Motion>`).
- **`preset`**: Motion preset to use (expects camel-case string), see [Presets](/features/presets).

### Variant props

- **`initial`**: Properties the element will have before it is mounted.
- **`enter`**: Properties the element will have after it is mounted.
- **`visible`**: Properties the element will have whenever it is within view. Once out of view, the `initial` properties are reapplied.
- **`visible-once`**: Properties the element will have once it enters the view.
- **`hovered`**: Properties the element will have when hovered.
- **`focused`**: Properties the element will have when it receives focus.
- **`tapped`**: Properties the element will have upon being clicked or tapped.

Variants can be passed as an object using the `:variants` prop.

The `:variants` prop combines with other variant properties, allowing for the definition of custom variants from this object.

Additional variant properties can be explored on the [Variants](/features/variants) page.

### Shorthand Props

We support shorthand props for quickly setting transition properties:

- **`delay`**
- **`duration`**

These properties apply to `visible`, `visible-once`, or `enter` variants if specified; otherwise, they default to the `initial` variant.

```vue
<template>
<Motion
:initial="{ opacity: 0, y: 100 }"
:enter="{ opacity: 1, y: 0, scale: 1 }"
:variants="{ custom: { scale: 2 } }"
:hovered="{ scale: 1.2 }"
:delay="200"
:duration="1200"
>
Content to animate!
</Motion>
</template>
```

### Group props

These props are specific to the `<MotionGroup>` component:

- **`config-fn`**
- Type: `(index: number) => MotionComponentConfig`
A function that takes an `<MotionGroup>` child element index and returns a `MotionComponentConfig`, the returned value will be applied and merged to each element individually.
3 changes: 3 additions & 0 deletions docs/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ export default defineNuxtConfig({
'@vueuse/motion/nuxt': resolve(__dirname, '../src/nuxt/module.ts'),
},
modules: ['@vueuse/motion/nuxt'],
features: {
devLogs: false,
},
typescript: {
includeWorkspace: true,
},
Expand Down
1 change: 1 addition & 0 deletions src/components/Motion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { variantToStyle } from '../utils/transform'
import { MotionComponentProps, setupMotionComponent } from '../utils/component'

export default defineComponent({
name: 'Motion',
props: {
...MotionComponentProps,
is: {
Expand Down
4 changes: 3 additions & 1 deletion src/components/MotionGroup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@ import type { Component } from '@nuxt/schema'

import { defineComponent, h, useSlots } from 'vue'
import { variantToStyle } from '../utils/transform'
import { MotionComponentProps, setupMotionComponent } from '../utils/component'
import { MotionComponentProps, MotionGroupComponentProps, setupMotionComponent } from '../utils/component'

export default defineComponent({
name: 'MotionGroup',
props: {
...MotionComponentProps,
is: {
type: [String, Object] as PropType<string | Component>,
required: false,
},
...MotionGroupComponentProps,
},
setup(props) {
const slots = useSlots()
Expand Down
14 changes: 13 additions & 1 deletion src/nuxt/module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { defu } from 'defu'
import { addImportsDir, addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit'
import { addComponent, addImportsDir, addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit'
import type { NuxtModule } from '@nuxt/schema'
import type { ModuleOptions as MotionModuleOpts } from '../types'

Expand All @@ -20,6 +20,18 @@ export default defineNuxtModule<ModuleOptions>({
// Add templates (options and directives)
addPlugin(resolve('./runtime/templates/motion'))

addComponent({
name: 'Motion',
export: 'MotionComponent',
filePath: resolve('./runtime/components'),
})

addComponent({
name: 'MotionGroup',
export: 'MotionGroupComponent',
filePath: resolve('./runtime/components'),
})

// Add auto imports
addImportsDir(resolve('./runtime/composables'))

Expand Down
2 changes: 2 additions & 0 deletions src/nuxt/runtime/components/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { default as MotionComponent } from '../../../components/Motion'
export { default as MotionGroupComponent } from '../../../components/MotionGroup'
45 changes: 36 additions & 9 deletions src/utils/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,28 @@ export const MotionComponentProps = {
},
}

/**
* Partial `<MotionGroup>` config props
*/
export type MotionComponentConfig = Partial<LooseRequired<ExtractPropTypes<typeof MotionComponentProps>>>

/**
* Component props specific to <MotionGroup>
*/
export const MotionGroupComponentProps = {
configFn: {
type: Function as PropType<(index: number) => MotionComponentConfig>,
required: false,
},
}

/**
* Shared logic for <Motion> and <MotionGroup>
*/
export function setupMotionComponent(props: LooseRequired<ExtractPropTypes<typeof MotionComponentProps>>) {
export function setupMotionComponent(
// prettier-ignore
props: LooseRequired<ExtractPropTypes<typeof MotionComponentProps & typeof MotionGroupComponentProps>>,
) {
// Motion instance map
const instances = reactive<{ [key: number]: MotionInstance<string, MotionVariants<string>> }>({})

Expand All @@ -100,16 +118,12 @@ export function setupMotionComponent(props: LooseRequired<ExtractPropTypes<typeo
focused: props.focused,
}))

// Merged motion configuration using `props.preset`, inline prop variants (`:initial` ...), and `props.variants`
const motionConfig = computed(() => {
const config = defu({}, propsConfig.value, preset.value, props.variants || {})

function applyTransitionHelpers(config: typeof propsConfig.value, values: Partial<Pick<typeof props, 'delay' | 'duration'>>) {
for (const transitionKey of ['delay', 'duration'] as const) {
if (!props[transitionKey]) continue
if (!values[transitionKey]) continue

const transitionValueParsed = Number.parseInt(props[transitionKey] as string)
const transitionValueParsed = Number.parseInt(values[transitionKey] as string)

// TODO: extract to utility function
// Apply transition property to existing variants where applicable
for (const variantKey of ['enter', 'visible', 'visibleOnce'] as const) {
const variantConfig = config[variantKey]
Expand All @@ -123,6 +137,13 @@ export function setupMotionComponent(props: LooseRequired<ExtractPropTypes<typeo
}

return config
}

// Merged motion configuration using `props.preset`, inline prop variants (`:initial` ...), and `props.variants`
const motionConfig = computed(() => {
const config = defu({}, { ...propsConfig.value }, preset.value, props.variants || {})

return applyTransitionHelpers({ ...config }, props)
})

// Replay animations on component update Vue
Expand Down Expand Up @@ -156,7 +177,13 @@ export function setupMotionComponent(props: LooseRequired<ExtractPropTypes<typeo

// Track motion instance locally using `instances`
node.props.onVnodeMounted = ({ el }) => {
instances[index] = useMotion<string, MotionVariants<string>>(el as any, motionConfig.value)
if (props.configFn) {
const derivedConfig = defu({}, structuredClone({ ...motionConfig.value }), props.configFn?.(index) ?? {})
applyTransitionHelpers(derivedConfig, props.configFn(index))
instances[index] = useMotion<string, MotionVariants<string>>(el as any, derivedConfig)
} else {
instances[index] = useMotion<string, MotionVariants<string>>(el as any, motionConfig.value)
}
}

return node
Expand Down
Loading