use-button.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { Text, computed, inject, ref, useSlots } from 'vue'
  2. import {
  3. useFormDisabled,
  4. useFormItem,
  5. useFormSize,
  6. } from '@kankan-components/components/basic/form'
  7. import { useGlobalConfig } from '@kankan-components/components/basic/config-provider'
  8. // import { useDeprecated } from '@kankan-components/hooks'
  9. import { buttonGroupContextKey } from './constants'
  10. import type { SetupContext } from 'vue'
  11. import type { ButtonEmits, ButtonProps } from './button'
  12. export const useButton = (
  13. props: ButtonProps,
  14. emit: SetupContext<ButtonEmits>['emit']
  15. ) => {
  16. // useDeprecated(
  17. // {
  18. // from: 'type.text',
  19. // replacement: 'link',
  20. // version: '3.0.0',
  21. // scope: 'props',
  22. // ref: 'https://element-plus.org/en-US/component/button.html#button-attributes',
  23. // },
  24. // computed(() => props.type === 'text')
  25. // )
  26. const buttonGroupContext = inject(buttonGroupContextKey, undefined)
  27. const globalConfig = useGlobalConfig('button')
  28. const { form } = useFormItem()
  29. const _size = useFormSize(computed(() => buttonGroupContext?.size))
  30. const _disabled = useFormDisabled()
  31. const _ref = ref<HTMLButtonElement>()
  32. const slots = useSlots()
  33. const _type = computed(() => props.type || buttonGroupContext?.type || '')
  34. const autoInsertSpace = computed(
  35. () => props.autoInsertSpace ?? globalConfig.value?.autoInsertSpace ?? false
  36. )
  37. const _props = computed(() => {
  38. if (props.tag === 'button') {
  39. return {
  40. ariaDisabled: _disabled.value || props.loading,
  41. disabled: _disabled.value || props.loading,
  42. autofocus: props.autofocus,
  43. type: props.nativeType,
  44. }
  45. }
  46. return {}
  47. })
  48. // add space between two characters in Chinese
  49. const shouldAddSpace = computed(() => {
  50. const defaultSlot = slots.default?.()
  51. if (autoInsertSpace.value && defaultSlot?.length === 1) {
  52. const slot = defaultSlot[0]
  53. if (slot?.type === Text) {
  54. const text = slot.children as string
  55. return /^\p{Unified_Ideograph}{2}$/u.test(text.trim())
  56. }
  57. }
  58. return false
  59. })
  60. const handleClick = (evt: MouseEvent) => {
  61. if (props.nativeType === 'reset') {
  62. form?.resetFields()
  63. }
  64. emit('click', evt)
  65. }
  66. return {
  67. _disabled,
  68. _size,
  69. _type,
  70. _ref,
  71. _props,
  72. shouldAddSpace,
  73. handleClick,
  74. }
  75. }