import { createApp } from 'vue'; import ModalStack from './ModalStack.vue'; import { ModalOptions } from './Types'; const globalStackInstancesKey = Symbol.for('GlobalStack'); export default class Modals { static globalStackInstances = window[globalStackInstancesKey] || (window[globalStackInstancesKey] = new Map()); /** * Creates a stack instance with the given name */ static createStackInstance(name: string): typeof ModalStack { console.warn( `[VueModals] No ModalStack was found for name "${name}". Using Modals without a stack instance causes one to be created as default at the end of the document body.` ); const existingStack = this.globalStackInstances.get(name); if (existingStack) { console.warn(`[VueModals] A ModalStack instance with the name "${name}" already exists. Returning stack.`); const existingStack = this.globalStackInstances.get(name); return existingStack; } const rootElement = document.createElement('aside'); document.body.insertAdjacentElement('beforeend', rootElement); const app = createApp(ModalStack, { name }) as unknown as typeof ModalStack; app.mount(rootElement); this.globalStackInstances.set(name, app); return app; } /** * Returns the stack modal instance by name. * If default instance is requested and is not registered, * it creates one and returns. */ static stack(name: string = 'default'): typeof ModalStack { // Create instance if no default one exists if (name === 'default' && !this.globalStackInstances.has('default')) { return this.createStackInstance('default'); } if (this.globalStackInstances.has(name)) { return this.globalStackInstances.get(name); } throw new Error( `[VueModals] No stack instance found for name "${ name ?? 'default' }". Create a ModalStack instance with this name to use it.` ); } static open(options: ModalOptions) { return (this.stack(options.stack) as any).push(options); } static registerStack(name: string, stack: typeof ModalStack) { console.warn('register', name, stack); if (this.globalStackInstances.has(name)) { console.warn( `[VueModals] Multiple instances of ModalStack must have unique names. Duplicate name found for ModalStack "${name}".` ); } else { this.globalStackInstances.set(name, stack); } } static unregisterStack(name: string, stack: typeof ModalStack) { console.warn('unregister', name, stack); if (this.globalStackInstances.get(name) === stack) { this.globalStackInstances.delete(name); } else { console.warn(`[VueModals] Could not unregister ModalStack because a duplicate name was found "${name}".`); } } }