mirror of
https://github.com/ArthurDanjou/ui.git
synced 2026-01-14 20:19:34 +01:00
feat(Button): loading-auto (#2198)
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
async function onClick() {
|
||||
return new Promise<void>(res => setTimeout(res, 1000))
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UButton loading-auto @click="onClick">
|
||||
Button
|
||||
</UButton>
|
||||
</template>
|
||||
@@ -0,0 +1,23 @@
|
||||
<script setup lang="ts">
|
||||
const state = reactive({ fullName: '' })
|
||||
|
||||
async function onSubmit() {
|
||||
return new Promise<void>(res => setTimeout(res, 1000))
|
||||
}
|
||||
|
||||
async function validate(data: Partial<typeof state>) {
|
||||
if (!data.fullName?.length) return [{ name: 'fullName', message: 'Required' }]
|
||||
return []
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UForm :state="state" :validate="validate" @submit="onSubmit">
|
||||
<UFormField name="fullName" label="Full name">
|
||||
<UInput v-model="state.fullName" />
|
||||
</UFormField>
|
||||
<UButton type="submit" class="mt-2" loading-auto>
|
||||
Submit
|
||||
</UButton>
|
||||
</UForm>
|
||||
</template>
|
||||
@@ -103,11 +103,11 @@ async function onSubmit(event: FormSubmitEvent<any>) {
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mt-8">
|
||||
<UButton color="gray" type="submit" :disabled="form?.disabled">
|
||||
<UButton color="gray" type="submit">
|
||||
Submit
|
||||
</UButton>
|
||||
|
||||
<UButton color="gray" variant="outline" :disabled="form?.disabled" @click="form?.clear()">
|
||||
<UButton color="gray" variant="outline" @click="form?.clear()">
|
||||
Clear
|
||||
</UButton>
|
||||
</div>
|
||||
|
||||
@@ -29,7 +29,7 @@ async function onSubmit(event: FormSubmitEvent<any>) {
|
||||
:state="state"
|
||||
:schema="schema"
|
||||
class="gap-4 flex flex-col w-60"
|
||||
@submit="(event) => onSubmit(event)"
|
||||
@submit="onSubmit"
|
||||
>
|
||||
<UFormField label="Name" name="name">
|
||||
<UInput v-model="state.name" placeholder="John Lennon" />
|
||||
|
||||
@@ -20,9 +20,11 @@ async function onSubmit(event: FormSubmitEvent<any>) {
|
||||
}
|
||||
|
||||
async function onError(event: FormErrorEvent) {
|
||||
const element = document.getElementById(event.errors[0].id)
|
||||
element?.focus()
|
||||
element?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
if (event?.errors?.[0]?.id) {
|
||||
const element = document.getElementById(event.errors[0].id)
|
||||
element?.focus()
|
||||
element?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ const schema = z.object({
|
||||
|
||||
type Schema = z.output<typeof schema>
|
||||
|
||||
const state = reactive({
|
||||
const state = reactive<Partial<Schema>>({
|
||||
email: undefined,
|
||||
password: undefined
|
||||
})
|
||||
|
||||
@@ -140,7 +140,6 @@ props:
|
||||
slots:
|
||||
default: Button
|
||||
---
|
||||
|
||||
Button
|
||||
::
|
||||
|
||||
@@ -148,6 +147,14 @@ Button
|
||||
You can customize this icon globally in your `app.config.ts` under `ui.icons.loading` key.
|
||||
::
|
||||
|
||||
Use the `loading-auto` prop to show the loading icon automatically while the `@click` promise is pending.
|
||||
|
||||
:component-example{name="button-loading-auto-example"}
|
||||
|
||||
This also works with the [Form](/components/form) component.
|
||||
|
||||
:component-example{name="button-loading-auto-form-example"}
|
||||
|
||||
### Disabled
|
||||
|
||||
Use the `disabled` prop to disable the Button.
|
||||
|
||||
@@ -35,8 +35,8 @@ function onError(event: any) {
|
||||
:state="state"
|
||||
:schema="schema"
|
||||
class="gap-4 flex flex-col w-60"
|
||||
@submit="(event) => onSubmit(event)"
|
||||
@error="(event) => onError(event)"
|
||||
@submit="onSubmit"
|
||||
@error="onError"
|
||||
>
|
||||
<UFormField label="Email" name="email">
|
||||
<UInput v-model="state.email" placeholder="john@lennon.com" />
|
||||
|
||||
@@ -4,6 +4,10 @@ import theme from '#build/ui/button'
|
||||
|
||||
const sizes = Object.keys(theme.variants.size) as Array<keyof typeof theme.variants.size>
|
||||
const variants = Object.keys(theme.variants.variant) as Array<keyof typeof theme.variants.variant>
|
||||
|
||||
function onClick() {
|
||||
return new Promise<void>(res => setTimeout(res, 5000))
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -23,7 +27,7 @@ const variants = Object.keys(theme.variants.variant) as Array<keyof typeof theme
|
||||
</UButton>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<UButton loading>
|
||||
<UButton loading-auto @click="onClick">
|
||||
Loading
|
||||
</UButton>
|
||||
</div>
|
||||
|
||||
@@ -25,7 +25,7 @@ function onSubmit(event: FormSubmitEvent<Schema>) {
|
||||
:state="state"
|
||||
:schema="schema"
|
||||
class="gap-4 flex flex-col w-60"
|
||||
@submit="(event) => onSubmit(event)"
|
||||
@submit="onSubmit"
|
||||
>
|
||||
<UFormField label="Email" name="email">
|
||||
<UInput v-model="state.email" placeholder="john@lennon.com" />
|
||||
@@ -51,7 +51,7 @@ function onSubmit(event: FormSubmitEvent<Schema>) {
|
||||
:schema="schema"
|
||||
class="gap-4 flex flex-col w-60"
|
||||
:validate-on-input-delay="2000"
|
||||
@submit="(event) => onSubmit(event)"
|
||||
@submit="onSubmit"
|
||||
>
|
||||
<UFormField label="Email" name="email">
|
||||
<UInput v-model="state2.email" placeholder="john@lennon.com" />
|
||||
|
||||
@@ -6,6 +6,7 @@ import theme from '#build/ui/button'
|
||||
import type { LinkProps } from './Link.vue'
|
||||
import type { UseComponentIconsProps } from '../composables/useComponentIcons'
|
||||
import type { PartialString } from '../types/utils'
|
||||
import { formLoadingInjectionKey } from '../composables/useFormField'
|
||||
|
||||
const appConfig = _appConfig as AppConfig & { ui: { button: Partial<typeof theme> } }
|
||||
|
||||
@@ -22,6 +23,9 @@ export interface ButtonProps extends UseComponentIconsProps, Omit<LinkProps, 'ra
|
||||
square?: boolean
|
||||
/** Render the button full width. */
|
||||
block?: boolean
|
||||
/** Set loading state automatically based on the `@click` promise state */
|
||||
loadingAuto?: boolean
|
||||
onClick?: (event: Event) => void | Promise<void>
|
||||
class?: any
|
||||
ui?: PartialString<typeof button.slots>
|
||||
}
|
||||
@@ -34,7 +38,7 @@ export interface ButtonSlots {
|
||||
</script>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { type Ref, computed, ref, inject } from 'vue'
|
||||
import { useForwardProps } from 'radix-vue'
|
||||
import { useComponentIcons } from '../composables/useComponentIcons'
|
||||
import { useButtonGroup } from '../composables/useButtonGroup'
|
||||
@@ -48,13 +52,32 @@ const slots = defineSlots<ButtonSlots>()
|
||||
const linkProps = useForwardProps(pickLinkProps(props))
|
||||
|
||||
const { orientation, size: buttonSize } = useButtonGroup<ButtonProps>(props)
|
||||
const { isLeading, isTrailing, leadingIconName, trailingIconName } = useComponentIcons(props)
|
||||
|
||||
const loadingAutoState = ref(false)
|
||||
const formLoading = inject<Ref<boolean> | undefined>(formLoadingInjectionKey, undefined)
|
||||
|
||||
async function onClickWrapper(event: Event) {
|
||||
loadingAutoState.value = true
|
||||
try {
|
||||
await props.onClick?.(event)
|
||||
} finally {
|
||||
loadingAutoState.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const isLoading = computed(() => {
|
||||
return props.loading || (props.loadingAuto && (loadingAutoState.value || (formLoading?.value && props.type === 'submit')))
|
||||
})
|
||||
|
||||
const { isLeading, isTrailing, leadingIconName, trailingIconName } = useComponentIcons(
|
||||
computed(() => ({ ...props, loading: isLoading.value }))
|
||||
)
|
||||
|
||||
const ui = computed(() => button({
|
||||
color: props.color,
|
||||
variant: props.variant,
|
||||
size: buttonSize.value,
|
||||
loading: props.loading,
|
||||
loading: isLoading.value,
|
||||
block: props.block,
|
||||
square: props.square || (!slots.default && !props.label),
|
||||
leading: isLeading.value,
|
||||
@@ -64,7 +87,14 @@ const ui = computed(() => button({
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ULink :type="type" :disabled="disabled || loading" :class="ui.base({ class: props.class })" v-bind="linkProps" raw>
|
||||
<ULink
|
||||
:type="type"
|
||||
:disabled="disabled || isLoading"
|
||||
:class="ui.base({ class: props.class })"
|
||||
v-bind="linkProps"
|
||||
raw
|
||||
@click="onClickWrapper"
|
||||
>
|
||||
<slot name="leading">
|
||||
<UIcon v-if="isLeading && leadingIconName" :name="leadingIconName" :class="ui.leadingIcon({ class: props.ui?.leadingIcon })" />
|
||||
</slot>
|
||||
|
||||
@@ -13,11 +13,12 @@ export interface FormProps<T extends object> {
|
||||
id?: string | number
|
||||
schema?: FormSchema<T>
|
||||
state: Partial<T>
|
||||
validate?: (state: Partial<T>) => Promise<FormError[]>
|
||||
validate?: (state: Partial<T>) => Promise<FormError[]> | FormError[]
|
||||
validateOn?: FormInputEvents[]
|
||||
disabled?: boolean
|
||||
validateOnInputDelay?: number
|
||||
class?: any
|
||||
onSubmit?: ((event: FormSubmitEvent<T>) => void | Promise<void>) | (() => void | Promise<void>)
|
||||
}
|
||||
|
||||
export interface FormEmits<T extends object> {
|
||||
@@ -31,9 +32,9 @@ export interface FormSlots {
|
||||
</script>
|
||||
|
||||
<script lang="ts" setup generic="T extends object">
|
||||
import { provide, inject, nextTick, ref, onUnmounted, onMounted, computed, useId } from 'vue'
|
||||
import { provide, inject, nextTick, ref, onUnmounted, onMounted, computed, useId, readonly } from 'vue'
|
||||
import { useEventBus } from '@vueuse/core'
|
||||
import { formOptionsInjectionKey, formInputsInjectionKey, formBusInjectionKey } from '../composables/useFormField'
|
||||
import { formOptionsInjectionKey, formInputsInjectionKey, formBusInjectionKey, formLoadingInjectionKey } from '../composables/useFormField'
|
||||
import { getYupErrors, isYupSchema, getValibotError, isValibotSchema, getZodErrors, isZodSchema, getJoiErrors, isJoiSchema } from '../utils/form'
|
||||
import { FormValidationException } from '../types/form'
|
||||
|
||||
@@ -53,6 +54,7 @@ const parentBus = inject(
|
||||
formBusInjectionKey,
|
||||
undefined
|
||||
)
|
||||
|
||||
provide(formBusInjectionKey, bus)
|
||||
|
||||
const nestedForms = ref<Map<string | number, { validate: () => any }>>(new Map())
|
||||
@@ -86,11 +88,6 @@ onUnmounted(() => {
|
||||
}
|
||||
})
|
||||
|
||||
provide(formOptionsInjectionKey, computed(() => ({
|
||||
disabled: props.disabled,
|
||||
validateOnInputDelay: props.validateOnInputDelay
|
||||
})))
|
||||
|
||||
const errors = ref<FormErrorWithId[]>([])
|
||||
provide('form-errors', errors)
|
||||
|
||||
@@ -157,13 +154,18 @@ async function _validate(opts: { name?: string | string[], silent?: boolean, nes
|
||||
return props.state as T
|
||||
}
|
||||
|
||||
async function onSubmit(payload: Event) {
|
||||
const loading = ref(false)
|
||||
provide(formLoadingInjectionKey, readonly(loading))
|
||||
|
||||
async function onSubmitWrapper(payload: Event) {
|
||||
loading.value = true
|
||||
|
||||
const event = payload as FormSubmitEvent<any>
|
||||
|
||||
try {
|
||||
await _validate({ nested: true })
|
||||
event.data = props.state
|
||||
emits('submit', event)
|
||||
await props.onSubmit?.(event)
|
||||
} catch (error) {
|
||||
if (!(error instanceof FormValidationException)) {
|
||||
throw error
|
||||
@@ -176,8 +178,17 @@ async function onSubmit(payload: Event) {
|
||||
}
|
||||
emits('error', errorEvent)
|
||||
}
|
||||
|
||||
loading.value = false
|
||||
}
|
||||
|
||||
const disabled = computed(() => props.disabled || loading.value)
|
||||
|
||||
provide(formOptionsInjectionKey, computed(() => ({
|
||||
disabled: disabled.value,
|
||||
validateOnInputDelay: props.validateOnInputDelay
|
||||
})))
|
||||
|
||||
defineExpose<Form<T>>({
|
||||
validate: _validate,
|
||||
errors,
|
||||
@@ -193,7 +204,7 @@ defineExpose<Form<T>>({
|
||||
},
|
||||
|
||||
async submit() {
|
||||
await onSubmit(new Event('submit'))
|
||||
await onSubmitWrapper(new Event('submit'))
|
||||
},
|
||||
|
||||
getErrors(name?: string) {
|
||||
@@ -211,7 +222,7 @@ defineExpose<Form<T>>({
|
||||
}
|
||||
},
|
||||
|
||||
disabled: computed(() => props.disabled)
|
||||
disabled
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -220,7 +231,7 @@ defineExpose<Form<T>>({
|
||||
:is="parentBus ? 'div' : 'form'"
|
||||
:id="formId"
|
||||
:class="form({ class: props.class })"
|
||||
@submit.prevent="onSubmit"
|
||||
@submit.prevent="onSubmitWrapper"
|
||||
>
|
||||
<slot />
|
||||
</component>
|
||||
|
||||
@@ -20,6 +20,7 @@ export const formBusInjectionKey: InjectionKey<UseEventBusReturn<FormEvent, stri
|
||||
export const formFieldInjectionKey: InjectionKey<ComputedRef<FormFieldInjectedOptions<FormFieldProps>>> = Symbol('nuxt-ui.form-field')
|
||||
export const inputIdInjectionKey: InjectionKey<Ref<string | undefined>> = Symbol('nuxt-ui.input-id')
|
||||
export const formInputsInjectionKey: InjectionKey<Ref<Record<string, string>>> = Symbol('nuxt-ui.form-inputs')
|
||||
export const formLoadingInjectionKey: InjectionKey<Readonly<Ref<boolean>>> = Symbol('nuxt-ui.form-loading')
|
||||
|
||||
export function useFormField<T>(props?: Props<T>, opts?: { bind?: boolean }) {
|
||||
const formOptions = inject(formOptionsInjectionKey, undefined)
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { ref } from 'vue'
|
||||
import { describe, it, expect, test } from 'vitest'
|
||||
import Button, { type ButtonProps, type ButtonSlots } from '../../src/runtime/components/Button.vue'
|
||||
import ComponentRender from '../component-render'
|
||||
import theme from '#build/ui/button'
|
||||
import { mountSuspended } from '@nuxt/test-utils/runtime'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
|
||||
import {
|
||||
UForm
|
||||
} from '#components'
|
||||
|
||||
describe('Button', () => {
|
||||
const sizes = Object.keys(theme.variants.size) as any
|
||||
@@ -34,4 +41,63 @@ describe('Button', () => {
|
||||
const html = await ComponentRender(nameOrHtml, options, Button)
|
||||
expect(html).toMatchSnapshot()
|
||||
})
|
||||
|
||||
test('with loading-auto works', async () => {
|
||||
let resolve: any | null = null
|
||||
const wrapper = await mountSuspended({
|
||||
components: { Button },
|
||||
async setup() {
|
||||
function onClick() {
|
||||
return new Promise(res => resolve = res)
|
||||
}
|
||||
|
||||
return { onClick }
|
||||
},
|
||||
template: `
|
||||
<Button loading-auto @click="onClick"> Click </Button>
|
||||
`
|
||||
})
|
||||
|
||||
const button = wrapper.find('button')
|
||||
button.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const icon = wrapper.findComponent({ name: 'Icon' })
|
||||
|
||||
expect(icon.classes()).toContain('animate-spin')
|
||||
expect(icon?.vm?.name).toBe('i-heroicons-arrow-path-20-solid')
|
||||
|
||||
resolve?.(null)
|
||||
})
|
||||
|
||||
test('with loading-auto works with forms', async () => {
|
||||
let resolve: any | null = null
|
||||
const wrapper = await mountSuspended({
|
||||
components: { Button, UForm },
|
||||
async setup() {
|
||||
function onSubmit() {
|
||||
return new Promise(res => resolve = res)
|
||||
}
|
||||
|
||||
const form = ref()
|
||||
return { form, onSubmit }
|
||||
},
|
||||
template: `
|
||||
<UForm :state="{}" ref="form" @submit="onSubmit">
|
||||
<Button type="submit" loading-auto> Click </Button>
|
||||
</UForm>
|
||||
`
|
||||
})
|
||||
|
||||
const form = wrapper.setupState.form
|
||||
form.value.submit()
|
||||
await flushPromises()
|
||||
|
||||
const icon = wrapper.findComponent({ name: 'Icon' })
|
||||
|
||||
expect(icon.classes()).toContain('animate-spin')
|
||||
expect(icon?.vm?.name).toBe('i-heroicons-arrow-path-20-solid')
|
||||
|
||||
resolve?.(null)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -81,8 +81,10 @@ describe('Form', () => {
|
||||
}
|
||||
]
|
||||
])('%s validation works', async (_nameOrHtml: string, options: Partial<FormProps<any>>) => {
|
||||
const onSubmit = vi.fn()
|
||||
|
||||
const wrapper = await renderForm({
|
||||
props: options,
|
||||
props: { ...options, onSubmit },
|
||||
slotTemplate: `
|
||||
<UFormField name="email">
|
||||
<UInput id="email" v-model="state.email" />
|
||||
@@ -117,10 +119,9 @@ describe('Form', () => {
|
||||
await form.trigger('submit.prevent')
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.emitted()).toHaveProperty('submit')
|
||||
expect(wrapper.emitted('submit')![0][0]).toMatchObject({
|
||||
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: { email: 'bob@dylan.com', password: 'validpassword' }
|
||||
})
|
||||
}))
|
||||
|
||||
expect(wrapper.html()).toMatchSnapshot('without error')
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user