mirror of
https://github.com/ArthurDanjou/ui.git
synced 2026-01-14 20:19:34 +01:00
62 lines
1.3 KiB
TypeScript
62 lines
1.3 KiB
TypeScript
import { ref, inject } from 'vue'
|
|
import type { ShallowRef, Component, InjectionKey } from 'vue'
|
|
import { createSharedComposable } from '@vueuse/core'
|
|
import type { ComponentProps } from '../types/component'
|
|
import type { Modal, ModalState } from '../types/modal'
|
|
|
|
export const modalInjectionKey: InjectionKey<ShallowRef<ModalState>> = Symbol('nuxt-ui.modal')
|
|
|
|
function _useModal () {
|
|
const modalState = inject(modalInjectionKey)
|
|
|
|
const isOpen = ref(false)
|
|
|
|
function open<T extends Component> (component: T, props?: Modal & ComponentProps<T>) {
|
|
if (!modalState) {
|
|
throw new Error('useModal() is called without provider')
|
|
}
|
|
|
|
modalState.value = {
|
|
component,
|
|
props: props ?? {}
|
|
}
|
|
|
|
isOpen.value = true
|
|
}
|
|
|
|
function close () {
|
|
if (!modalState) return
|
|
|
|
isOpen.value = false
|
|
|
|
modalState.value = {
|
|
component: 'div',
|
|
props: {}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Allows updating the modal props
|
|
*/
|
|
function patch <T extends Component = {}> (props: Partial<Modal & ComponentProps<T>>) {
|
|
if (!modalState) return
|
|
|
|
modalState.value = {
|
|
...modalState.value,
|
|
props: {
|
|
...modalState.value.props,
|
|
...props
|
|
}
|
|
}
|
|
}
|
|
|
|
return {
|
|
open,
|
|
close,
|
|
patch,
|
|
isOpen
|
|
}
|
|
}
|
|
|
|
export const useModal = createSharedComposable(_useModal)
|