feat(Button): loading-auto (#2198)

This commit is contained in:
Romain Hamel
2024-09-16 11:37:38 +02:00
committed by GitHub
parent 6f20f243fb
commit ed18e74549
15 changed files with 191 additions and 35 deletions

View File

@@ -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>

View File

@@ -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>

View File

@@ -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)