UNPKG

react-snappy-modal

Version:

Flexible and easy-to-use modal library for React, supporting customizable dialogs with promise-based interactions.

105 lines (104 loc) 2.89 kB
// src/SnappyModal.tsx import React from "react"; import "../SnappyModal-JGLWFQD3.css"; import { jsx } from "react/jsx-runtime"; var currentComponents = []; var SnappyModal = class { static isShow() { return currentComponents.length > 0; } static getCurrentComponent(layer) { return currentComponents.find((c) => c.options.layer === layer); } static removeModalProcess(layer) { const index = currentComponents.findIndex((c) => c.options.layer === layer); if (index === -1) return; currentComponents.splice(index, 1); SnappyModalExternalStore.emitChange(); } static getModalProcess() { return currentComponents; } static close(value, layer = 0) { const currentComponent = this.getCurrentComponent(layer); currentComponent?.resolve(value); this.removeModalProcess(layer); } static throw(thrower, layer = 0) { const currentComponent = this.getCurrentComponent(layer); currentComponent?.throw(thrower); this.removeModalProcess(layer); currentComponent?.throw(thrower); } static show(component, options) { const dialogOptions = { ...defaultDialogOptions, ...options }; return new Promise((resolve, reject) => { currentComponents.push({ component: () => /* @__PURE__ */ jsx(React.Fragment, { children: component }), options: dialogOptions, resolve: (value) => { resolve(value); SnappyModalExternalStore.emitChange(); }, throw: (thrower) => { reject(thrower); SnappyModalExternalStore.emitChange(); } }); currentComponents.sort((a, b) => a.options.layer - b.options.layer); SnappyModalExternalStore.emitChange(); }); } }; var defaultDialogOptions = { allowOutsideClick: true, allowScroll: false, backdrop: true, position: "center", layer: 0 }; // src/context/useSnappyModalState.tsx import { useSyncExternalStore } from "react"; var snappyModalListeners = []; var snappyModalState = { isShow: false, modalProgress: [] }; function emitChange() { for (const listener of snappyModalListeners) { listener(); } } var SnappyModalExternalStore = { emitChange: () => { snappyModalState = { isShow: SnappyModal.isShow(), modalProgress: [...SnappyModal.getModalProcess()] }; emitChange(); }, subscribe(listener) { snappyModalListeners = [...snappyModalListeners, listener]; return () => { snappyModalListeners = snappyModalListeners.filter((l) => l !== listener); }; }, getSnappyModalState() { return snappyModalState; } }; var useSnappyModalState = () => { return useSyncExternalStore( SnappyModalExternalStore.subscribe, SnappyModalExternalStore.getSnappyModalState ); }; export { SnappyModalExternalStore, useSnappyModalState }; //# sourceMappingURL=useSnappyModalState.mjs.map