Skip to content

Commit

Permalink
feat(Button): loading-auto (#2198)
Browse files Browse the repository at this point in the history
  • Loading branch information
romhml authored Sep 16, 2024
1 parent 6f20f24 commit ed18e74
Show file tree
Hide file tree
Showing 15 changed files with 191 additions and 35 deletions.
Original file line number Diff line number Diff line change
@@ -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>
Original file line number Diff line number Diff line change
@@ -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>
Original file line number Diff line number Diff line change
Expand Up @@ -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>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
Expand Down
9 changes: 8 additions & 1 deletion docs/content/3.components/button.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,14 +140,21 @@ props:
slots:
default: Button
---

Button
::

::tip
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.
Expand Down
4 changes: 2 additions & 2 deletions playground/app/components/FormNestedExample.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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="[email protected]" />
Expand Down
6 changes: 5 additions & 1 deletion playground/app/pages/components/button.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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>
Expand All @@ -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>
Expand Down
4 changes: 2 additions & 2 deletions playground/app/pages/components/form.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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="[email protected]" />
Expand All @@ -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="[email protected]" />
Expand Down
38 changes: 34 additions & 4 deletions src/runtime/components/Button.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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> } }
Expand All @@ -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>
}
Expand All @@ -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'
Expand All @@ -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,
Expand All @@ -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>
Expand Down
37 changes: 24 additions & 13 deletions src/runtime/components/Form.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
Expand All @@ -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'
Expand All @@ -53,6 +54,7 @@ const parentBus = inject(
formBusInjectionKey,
undefined
)
provide(formBusInjectionKey, bus)
const nestedForms = ref<Map<string | number, { validate: () => any }>>(new Map())
Expand Down Expand Up @@ -86,11 +88,6 @@ onUnmounted(() => {
}
})
provide(formOptionsInjectionKey, computed(() => ({
disabled: props.disabled,
validateOnInputDelay: props.validateOnInputDelay
})))
const errors = ref<FormErrorWithId[]>([])
provide('form-errors', errors)
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -193,7 +204,7 @@ defineExpose<Form<T>>({
},
async submit() {
await onSubmit(new Event('submit'))
await onSubmitWrapper(new Event('submit'))
},
getErrors(name?: string) {
Expand All @@ -211,7 +222,7 @@ defineExpose<Form<T>>({
}
},
disabled: computed(() => props.disabled)
disabled
})
</script>

Expand All @@ -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>
Expand Down
1 change: 1 addition & 0 deletions src/runtime/composables/useFormField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading

0 comments on commit ed18e74

Please sign in to comment.