react-modal-navigation 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Modal Navigator contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.
package/README.md CHANGED
@@ -1,3 +1,265 @@
1
- # Temporary Holding Version
1
+ # react-modal-navigation
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ React 19 多页面弹窗导航组件库。支持 **Modal / Drawer / Sheet**、页面堆栈、KeepAlive、Promise 返回结果、异步关闭守卫、Footer、Loading、暗黑主题与自动注入样式。
4
+
5
+ > 包名 `react-modal-navigation`,源码版本 `1.0.0`。此源码包尚未代替你在 npm 上发布;请先运行构建及浏览器回归测试。**默认不需要导入 CSS 文件**。
6
+
7
+ ## 目录
8
+
9
+ 1. [安装和快速开始](#安装和快速开始)
10
+ 2. [弹窗位置与尺寸](#弹窗位置与尺寸)
11
+ 3. [配置优先级与响应式](#配置优先级与响应式)
12
+ 4. [页面导航与传参](#页面导航与传参)
13
+ 5. [Promise 结果与关闭守卫](#promise-结果与关闭守卫)
14
+ 6. [异步提交与 Loading](#异步提交与-loading)
15
+ 7. [主题与样式覆盖](#主题与样式覆盖)
16
+ 8. [事件、可访问性和注意事项](#事件可访问性和注意事项)
17
+ 9. [TypeScript 和发布](#typescript-和发布)
18
+
19
+ ## 安装和快速开始
20
+
21
+ ```bash
22
+ npm install react-modal-navigation
23
+ ```
24
+
25
+ ```jsx
26
+ import { ModalProvider, useModal } from 'react-modal-navigation';
27
+
28
+ function Home() {
29
+ const { modal } = useModal();
30
+ return <>
31
+ <button onClick={() => modal.open('editUser')}>居中编辑</button>
32
+ <button onClick={() => modal.open('deviceDrawer')}>右侧设备抽屉</button>
33
+ </>;
34
+ }
35
+
36
+ function UserForm() {
37
+ const { navigation } = useModal();
38
+ return <button onClick={() => navigation.close({ id: 1, name: 'Ada' })}>完成</button>;
39
+ }
40
+
41
+ function DeviceHome() {
42
+ const { navigation } = useModal();
43
+ return <button onClick={() => navigation.navigate('DeviceDetail', { id: 123 })}>查看详情</button>;
44
+ }
45
+
46
+ function DeviceDetail() {
47
+ const { navigation } = useModal();
48
+ return <button onClick={() => navigation.goBack()}>返回</button>;
49
+ }
50
+
51
+ const registry = {
52
+ editUser: {
53
+ initialRoute: 'UserForm',
54
+ modalOptions: { placement: 'center', width: 600, maxHeight: '85dvh' },
55
+ screens: { UserForm: { title: '编辑用户', component: UserForm } },
56
+ },
57
+ deviceDrawer: {
58
+ initialRoute: 'DeviceHome',
59
+ modalOptions: { placement: 'right', width: 520 },
60
+ screens: {
61
+ DeviceHome: { title: '设备', component: DeviceHome },
62
+ DeviceDetail: { title: '设备详情', component: DeviceDetail },
63
+ },
64
+ },
65
+ };
66
+
67
+ export default function App() {
68
+ return <ModalProvider registry={registry}><Home /></ModalProvider>;
69
+ }
70
+ ```
71
+
72
+ **不需要** `import 'react-modal-navigation/style.css'`,Provider 会自动注入组件样式;业务页面可以使用任意 CSS 方案。
73
+
74
+ ## 弹窗位置与尺寸
75
+
76
+ ### placement 可选值
77
+
78
+ | placement | 说明 | 默认高度 | 推荐场景 |
79
+ | --- | --- | --- | --- |
80
+ | `center` | 居中弹窗 | 内容高度,受 maxHeight 限制 | 表单、确认框、详情 |
81
+ | `left` | 左侧抽屉 | 视口高度减去上下缝隙 | 导航、筛选 |
82
+ | `right` | 右侧抽屉(默认) | 视口高度减去上下缝隙 | 设备设置、编辑页 |
83
+ | `top` | 顶部弹出层 | 内容高度 | 顶部操作面板 |
84
+ | `bottom` | 底部弹出层 | 内容高度 | 移动端操作、筛选 |
85
+
86
+ ### 右侧抽屉:上下左右与视口保持 5px
87
+
88
+ ```jsx
89
+ modal.open('deviceDrawer', { deviceId: 123 }, {
90
+ placement: 'right',
91
+ width: 520,
92
+ viewportGap: 5,
93
+ });
94
+ ```
95
+
96
+ **左右抽屉的高度固定为 `calc(100dvh - 10px)`**(`viewportGap: 5` 时),即距视口顶部、底部各 5px;同时距左右视口边缘至少 5px。无需传 `height: '100dvh'`,即使传入 `height`,左右抽屉仍遵循视口高度规则。
97
+
98
+ ```jsx
99
+ // 左侧抽屉
100
+ modal.open('deviceDrawer', {}, { placement: 'left', width: '35vw' });
101
+
102
+ // 居中弹窗
103
+ modal.open('editUser', {}, {
104
+ placement: 'center', width: 680, height: '70dvh', maxHeight: '85dvh',
105
+ });
106
+
107
+ // 底部 Sheet
108
+ modal.open('editUser', {}, {
109
+ placement: 'bottom', width: '100%', height: '55dvh',
110
+ });
111
+
112
+ // 顶部 Sheet
113
+ modal.open('editUser', {}, {
114
+ placement: 'top', width: 800, height: 320,
115
+ });
116
+ ```
117
+
118
+ ### 尺寸预设
119
+
120
+ `size` 仅控制**宽度**,可选 `sm`(400px)、`md`(560px)、`lg`(720px)、`xl`(960px)、`full`(100%)。显式 `width` 优先于 `size`。不传时默认宽度 460px。
121
+
122
+ ```jsx
123
+ modal.open('editUser', {}, { placement: 'center', size: 'lg' });
124
+ modal.open('editUser', {}, { placement: 'center', size: 'lg', width: 640 }); // width 优先
125
+ ```
126
+
127
+ | 属性 | 类型 | 默认 | 作用 |
128
+ | --- | --- | --- | --- |
129
+ | `placement` | `center \| left \| right \| top \| bottom` | `right` | 弹窗位置 |
130
+ | `size` | `sm \| md \| lg \| xl \| full` | 未设置 | 预设宽度 |
131
+ | `width` | `number \| string` | `460` | 弹窗宽度,数字单位 px |
132
+ | `height` | `number \| string` | 自动 | 居中/顶部/底部高度;左右抽屉强制视口高度 |
133
+ | `maxWidth` | `number \| string` | 同 width | 最大宽度 |
134
+ | `maxHeight` | `number \| string` | 视口减去缝隙 | 最大高度;左右抽屉强制视口高度 |
135
+ | `viewportGap` | `number` | `5` | 视口四周留白,单位 px |
136
+ | `borderRadius` | `number \| string` | `12` | 圆角 |
137
+ | `mobileFullscreen` | `boolean` | `false` | 宽度 ≤640px 时铺满屏幕,覆盖缝隙规则 |
138
+
139
+ 视口边界使用 `100dvh`(动态视口高度),适应移动端浏览器地址栏;内容区域单独滚动,Header / Footer 不跟随内容滚动。`viewportGap` 应使用有限的非负数字。
140
+
141
+ ## 配置优先级与响应式
142
+
143
+ 从低到高:`ModalProvider.defaultOptions` → `registry[name].modalOptions` → `modal.open(name, params, overrides)`。
144
+
145
+ ```jsx
146
+ <ModalProvider registry={registry} defaultOptions={{ placement: 'center', size: 'md', viewportGap: 5 }}>
147
+ <App />
148
+ </ModalProvider>
149
+ ```
150
+
151
+ ```jsx
152
+ const registry = {
153
+ users: {
154
+ initialRoute: 'List',
155
+ modalOptions: { placement: 'right', width: 520 },
156
+ screens: { List: { title: '用户列表', component: UserList } },
157
+ },
158
+ };
159
+
160
+ modal.open('users'); // 默认右侧 520px
161
+ modal.open('users', {}, { placement: 'center', width: 700 }); // 本次临时居中
162
+ modal.open('users', {}, { mobileFullscreen: true }); // 手机端全屏
163
+ ```
164
+
165
+ 注意:`mobileFullscreen: true` 在宽度 ≤640px 时会覆盖 placement 与 viewportGap,故**不再保留 5px 缝隙**;需要缝隙时不要启用此项。
166
+
167
+ ## 页面导航与传参
168
+
169
+ ```jsx
170
+ function UserList() {
171
+ const { navigation } = useModal();
172
+ return <button onClick={() => navigation.navigate('UserDetail', { id: 8 })}>详情</button>;
173
+ }
174
+
175
+ function UserDetail() {
176
+ const { navigation } = useModal();
177
+ const id = navigation.currentRoute?.params?.id;
178
+ return <>
179
+ <p>用户 ID:{id}</p>
180
+ <button onClick={() => navigation.setParams({ tab: 'settings' })}>切换标签</button>
181
+ <button onClick={() => navigation.goBack({ updated: true })}>返回</button>
182
+ </>;
183
+ }
184
+ ```
185
+
186
+ `navigate` 进入路由,`goBack(result?)` 返回上一页,`replace` 替换当前页,`reset` 重置栈,`setParams` 合并当前页参数。隐藏页面 KeepAlive 保留状态;建议用 `useFocusEffect` 管理轮询和订阅。
187
+
188
+ ## Promise 结果与关闭守卫
189
+
190
+ ```jsx
191
+ const { modal } = useModal();
192
+ const result = await modal.openAsync('editUser');
193
+ if (result.status === 'confirmed') console.log(result.value);
194
+ else console.log(result.status, result.reason);
195
+ ```
196
+
197
+ 弹窗内部:`await navigation.close({ id: 1 })` 返回确认结果。`modal.open()` 返回 `Promise<number | null>`(弹窗实例 ID 或阻止打开时 null),不是 `openAsync` 的业务结果。
198
+
199
+ ```jsx
200
+ modalOptions: {
201
+ onBeforeClose: async ({ reason }) => {
202
+ if (hasUnsavedChanges()) return window.confirm('未保存,确定关闭吗?');
203
+ return true;
204
+ },
205
+ onOpen: ctx => console.log('opened', ctx),
206
+ onClose: ctx => console.log('closed', ctx.reason),
207
+ onNavigate: ctx => console.log('navigated', ctx),
208
+ onFocus: ctx => console.log('focused', ctx),
209
+ onBlur: ctx => console.log('blurred', ctx),
210
+ }
211
+ ```
212
+
213
+ 关闭被拒绝时弹窗继续存在。替换、取消和 Provider 卸载等情况,`openAsync()` 返回不同状态与 reason。不要将 `onClose` 当作弹窗仍处于活动状态的回调。
214
+
215
+ ## 异步提交与 Loading
216
+
217
+ ```jsx
218
+ import { useModal, useModalTask, useModalLoading } from 'react-modal-navigation';
219
+
220
+ function SaveScreen() {
221
+ const { navigation } = useModal();
222
+ const { run, pending, error } = useModalTask();
223
+ const save = async () => {
224
+ const result = await run(() => Promise.resolve({ id: 10 }), { loadingText: '保存中...' });
225
+ if (result.status === 'success') await navigation.close(result.value);
226
+ };
227
+ return <>
228
+ {error && <p role="alert">保存失败,请重试</p>}
229
+ <button disabled={pending} onClick={save}>保存</button>
230
+ </>;
231
+ }
232
+ ```
233
+
234
+ `useModalLoading().showLoading()` 返回任务 token,使用 `hideLoading(token)` 结束对应任务;多个任务并发不会相互误关。`useModalTask` 阻止同一 Hook 的重复提交,但**不会自动取消网络请求**。
235
+
236
+ ## 主题与样式覆盖
237
+
238
+ ```jsx
239
+ <ModalProvider registry={registry} theme="auto"
240
+ backgroundColor={{ light: '#fff', dark: '#334155' }}>
241
+ <App />
242
+ </ModalProvider>
243
+ ```
244
+
245
+ 不需要导入库的 CSS。已有 `className`、`bodyClassName`、`headerClassName`、`footerClassName` 可供业务样式覆盖;也可在业务项目中覆盖 `--pmn-surface`、`--pmn-text`、`--pmn-border` 等 CSS 变量。自动注入 CSS 时请注意 CSS 优先级。若站点 CSP 禁止内联样式,可改用 `react-modal-navigation/style.css` 静态导入,并按需配置 CSP。
246
+
247
+ ## 事件可访问性和注意事项
248
+
249
+ - `closeOnOverlay` 默认 `false`;`closeOnEsc` 默认 `true`。
250
+ - 对话框有 `role="dialog"`、`aria-modal`、Tab 焦点约束、关闭后焦点恢复。
251
+ - 背景滚动被锁定,并补偿滚动条宽度。
252
+ - KeepAlive 页面隐藏时保持组件挂载,轮询/订阅请自行按焦点停止。
253
+ - 若多次调用 `open()` 或存在异步关闭守卫,建议 `await` 以避免竞态。
254
+ - 样式注入依赖浏览器 DOM;SSR 时不会直接访问 `document`。严格 CSP 环境可能需要改为静态 CSS。
255
+
256
+ ## TypeScript 和发布
257
+
258
+ 公开类型位于 `types/index.d.ts`,包括 `ModalOptions`、`ModalRegistry`、`ModalNavigation`、`ModalResult` 等。
259
+
260
+ ```tsx
261
+ import type { ModalRegistry } from 'react-modal-navigation';
262
+ const registry: ModalRegistry = {
263
+ demo: { initialRoute: 'Main', modalOptions: { placement: 'right', size: 'lg' }, screens: { Main: { component: Main } } },
264
+ };
265
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react/jsx-runtime"),n=require("react"),ye=require("react-dom"),ge=n.createContext(null),oe=n.createContext(null),ee=n.createContext(null),ae=n.createContext(null);let ke=0;const re=(e,t)=>({key:`modal-route-${++ke}`,name:e,params:t??{}}),be=(e,t)=>[re(e,t)];function we(e,t){switch(t.type){case"RESET":return be(t.name,t.params);case"NAVIGATE":{const r=e.findIndex(a=>a.name===t.name);return r<0?[...e,re(t.name,t.params)]:e.slice(0,r+1).map((a,s)=>s===r?{...a,params:t.params??{}}:a)}case"SET_PARAMS":return e.map((r,a)=>a===e.length-1?{...r,params:{...r.params??{},...t.params??{}}}:r);case"BACK":return e.length>1?e.slice(0,-1):e;case"REPLACE":return e.length?[...e.slice(0,-1),re(t.name,t.params)]:e;default:return e}}const fe=()=>{if(typeof document>"u")return"light";const e=document.documentElement,t=document.body;return e.classList.contains("dark")||t.classList.contains("dark")||e.dataset.theme==="dark"||t.dataset.theme==="dark"?"dark":e.classList.contains("light")||t.classList.contains("light")||e.dataset.theme==="light"||t.dataset.theme==="light"?"light":window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"};let X=0;const Y=[];let te=null;function Ce(){if(X++,X===1){const t=document.documentElement,r=document.body,a={html:t.style.overflow,body:r.style.overflow,padding:r.style.paddingRight,width:r.style.getPropertyValue("--modal-scrollbar-width")},s=Math.max(0,window.innerWidth-t.clientWidth),y=parseFloat(getComputedStyle(r).paddingRight)||0;s&&(r.style.paddingRight=`${y+s}px`),r.style.setProperty("--modal-scrollbar-width",`${s}px`),t.style.overflow="hidden",r.style.overflow="hidden",te=()=>{t.style.overflow=a.html,r.style.overflow=a.body,r.style.paddingRight=a.padding,a.width?r.style.setProperty("--modal-scrollbar-width",a.width):r.style.removeProperty("--modal-scrollbar-width")}}let e=!1;return()=>{e||(e=!0,X=Math.max(0,X-1),X||(te?.(),te=null))}}const Ee='a[href],button:not([disabled]),input:not([disabled]),textarea:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])',Re=e=>!e.closest('[inert], [hidden], [aria-hidden="true"]')&&e.getClientRects().length>0&&getComputedStyle(e).visibility!=="hidden"&&getComputedStyle(e).display!=="none";function Me({dialogRef:e,options:t,requestClose:r,children:a}){const s=n.useRef(null),y=n.useRef(null),h=n.useRef(r);h.current=r;const m=n.useRef(t.closeOnEsc);m.current=t.closeOnEsc;const[g,M]=n.useState(fe),l=t.theme==="light"||t.theme==="dark"?t.theme:g;n.useEffect(()=>{if(t.theme==="light"||t.theme==="dark")return;const j=()=>M(fe()),b=new MutationObserver(j);for(const H of[document.documentElement,document.body])b.observe(H,{attributes:!0,attributeFilter:["class","data-theme"]});const E=window.matchMedia?.("(prefers-color-scheme: dark)");return E?.addEventListener?.("change",j),j(),()=>{b.disconnect(),E?.removeEventListener?.("change",j)}},[t.theme]),n.useEffect(()=>{y.current=document.activeElement;const j=Ce(),b=s.current;Y.push(b),e.current?.focus({preventScroll:!0});const E=w=>{const S=e.current;if(!S||Y.at(-1)!==b)return;if(w.key==="Escape"&&m.current!==!1){w.preventDefault(),h.current("escape");return}if(w.key!=="Tab")return;const B=[...S.querySelectorAll(Ee)].filter(Re);if(!B.length){w.preventDefault(),S.focus();return}const $=B[0],K=B.at(-1);S.contains(document.activeElement)?w.shiftKey&&(document.activeElement===$||document.activeElement===S)?(w.preventDefault(),K.focus()):!w.shiftKey&&(document.activeElement===K||document.activeElement===S)&&(w.preventDefault(),$.focus()):(w.preventDefault(),(w.shiftKey?K:$).focus())},H=w=>{Y.at(-1)===b&&e.current&&!e.current.contains(w.target)&&e.current.focus({preventScroll:!0})};return document.addEventListener("keydown",E),document.addEventListener("focusin",H),()=>{document.removeEventListener("keydown",E),document.removeEventListener("focusin",H);const w=Y.at(-1)===b,S=Y.indexOf(b);if(S!==-1&&Y.splice(S,1),j(),w){const B=y.current;B?.isConnected&&!B.closest("[inert], [hidden]")?B.focus?.({preventScroll:!0}):Y.at(-1)?.querySelector("[role=dialog]")?.focus?.({preventScroll:!0})}}},[e]);const u=t.backgroundColor??t.backgroudColor,f=typeof u=="string"?u:u?.[l],x=typeof f=="string"&&/^(#|rgb\(|rgba\(|hsl\(|hsla\(|oklch\(|color\(|var\()/.test(f.trim())?f:null,N={sm:400,md:560,lg:720,xl:960,full:"100%"},O=["center","left","right","top","bottom"].includes(t.placement)?t.placement:"right",P=j=>typeof j=="number"?`${j}px`:j,v=P(t.width??N[t.size]??460),T=P(t.height),R=P(t.maxHeight),q=P(t.maxWidth),k=Number(t.viewportGap??5),A=Number.isFinite(k)?Math.max(0,k):5,z=typeof t.borderRadius=="number"?`${t.borderRadius}px`:t.borderRadius??"12px";return ye.createPortal(c.jsx("div",{ref:s,className:`pmn-overlay pmn-place-${O} ${t.mobileFullscreen?"pmn-mobile-fullscreen":""}`,style:{padding:A},onMouseDown:j=>{j.target===j.currentTarget&&t.closeOnOverlay===!0&&h.current("overlay")},children:c.jsx("section",{ref:e,tabIndex:-1,role:"dialog","aria-modal":"true","aria-label":t.ariaLabel??"Dialog","data-modal-theme":l,className:`pmn-dialog ${l==="dark"?"dark":""} ${!x&&f?f:""} ${t.className??""}`,style:{"--pmn-width":v,"--pmn-gap":`${A}px`,...T!==void 0?{"--pmn-height":T}:{},...R!==void 0?{"--pmn-max-height":R}:{},...q!==void 0?{"--pmn-max-width":q}:{},borderRadius:z,...x?{backgroundColor:x}:{}},children:a})}),document.body)}function pe({back:e}){return c.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e?c.jsx("path",{d:"m15 18-6-6 6-6"}):c.jsx("path",{d:"M18 6 6 18M6 6l12 12"})})}function je({options:e,screen:t,route:r,navigation:a,requestClose:s,translate:y}){if(e.showHeader===!1)return null;const h=y??(f=>f),m=t.showTitle??e.showTitle??!0,g=typeof t.title=="function"?t.title({t:h,route:r,navigation:a}):t.title??r.name,M={route:r,navigation:a,close:s,canGoBack:a.canGoBack,title:g,t:h},l=t.renderHeader??e.renderHeader;if(l)return l(M);const u=t.renderHeaderRight??e.renderHeaderRight;return c.jsxs("header",{className:`pmn-header ${t.showHeaderBorder??e.showHeaderBorder?"pmn-border-bottom":""} ${e.headerClassName??""}`,children:[e.showBackButton!==!1&&a.canGoBack&&c.jsx("button",{type:"button",className:"pmn-icon-button","aria-label":h("modal.back"),onClick:()=>a.goBack(),children:c.jsx(pe,{back:!0})}),m?c.jsx("h2",{children:g}):c.jsx("div",{className:"pmn-header-spacer"}),u?.(M),e.showCloseButton!==!1&&c.jsx("button",{type:"button",className:"pmn-icon-button","aria-label":h("modal.close"),onClick:()=>s("header"),children:c.jsx(pe,{})})]})}function Se({screen:e,options:t,override:r,route:a,navigation:s,requestClose:y,translate:h,onError:m}){const[g,M]=n.useState(!1),l=h??(k=>k),u={...t,...e,...r},{showFooter:f,renderFooter:x,done:N,cancel:O,cancle:P}=u,v=O??P,T={route:a,navigation:s,close:y,t:l};if(f===!1)return null;const R=`pmn-footer ${u.showFooterBorder?"pmn-border-top":""} ${u.footerClassName??""}`;if(typeof x=="function")return c.jsx("footer",{className:R,children:x({...T,pending:g})});if(typeof N!="function"&&typeof v!="function")return null;const q=async k=>{if(!(g||typeof k!="function")){M(!0);try{await k(T)}catch(A){m?.(A,{phase:"footer",route:a})}finally{M(!1)}}};return c.jsxs("footer",{className:R,children:[typeof v=="function"&&c.jsx("button",{type:"button",disabled:g,onClick:()=>q(v),className:"pmn-button pmn-button-secondary",children:u.cancelText??l("modal.cancel")}),typeof N=="function"&&c.jsx("button",{type:"button",disabled:g||u.doneDisabled===!0,onClick:()=>q(N),className:"pmn-button pmn-button-primary",children:g?u.loadingText??l("modal.processing"):u.doneText??l("modal.done")})]})}function Le({loading:e,translate:t}){if(!e.visible)return null;const a=(t??(y=>y))("modal.loading"),s=e.text??(a==="modal.loading"?"加载中...":a);return c.jsx("div",{className:"pmn-loading-overlay",role:"status","aria-live":"polite","aria-busy":"true",children:c.jsxs("div",{className:"pmn-loading-card",children:[c.jsx("span",{className:"pmn-spinner","aria-hidden":"true"}),c.jsx("span",{children:s})]})})}class Ne extends n.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){this.props.onError?.(t,{phase:"render",route:this.props.route,componentStack:r.componentStack})}componentDidUpdate(t){t.route?.key!==this.props.route?.key&&this.state.error&&this.setState({error:null})}render(){return this.state.error?c.jsxs("div",{role:"alert",className:"pmn-error-screen",children:[c.jsx("strong",{children:"页面加载失败"}),c.jsx("p",{children:this.state.error.message}),c.jsx("button",{type:"button",className:"pmn-button pmn-button-secondary",onClick:()=>this.setState({error:null}),children:"重试"})]}):this.props.children}}function Te({route:e,screen:t,navigation:r,focused:a,resultEvent:s,setFooter:y,loadingApi:h,bodyClassName:m,notifyError:g}){const M=t.component,l=n.useMemo(()=>({isFocused:a,resultEvent:s,routeKey:e.key,setFooter:y}),[a,s,e.key,y]),u=n.useMemo(()=>({isLoading:a&&h.isLoading,setLoading:(f,x)=>h.setScreenLoading(e.key,f,x),showLoading:f=>h.begin(e.key,f),hideLoading:f=>h.end(e.key,f)}),[a,h,e.key]);return c.jsx(ee.Provider,{value:l,children:c.jsx(ae.Provider,{value:u,children:c.jsx("div",{hidden:!a,inert:!a,"data-modal-route-key":e.key,tabIndex:-1,className:`pmn-body ${m??""}`,children:c.jsx(Ne,{route:e,onError:g,children:c.jsx(M,{route:e,navigation:r})})})})})}function xe({config:e,params:t,options:r,translate:a,onRequestClose:s,onOpened:y,registerLoading:h,notifyError:m,error:g,clearError:M}){const[l,u]=n.useReducer(we,null,()=>be(e.initialRoute,t)),[f,x]=n.useState({}),[N,O]=n.useState({}),[,P]=n.useState(0),v=n.useRef(new Map),T=n.useRef(0),R=n.useRef(new Map),q=n.useRef(null),k=n.useRef(null),A=n.useRef(!1),z=n.useRef(!1),j=n.useRef(0),b=l.at(-1),E=b.key,H=n.useRef(E);H.current=E;const w=e.screens,S=n.useCallback(()=>P(o=>o+1),[]),B=n.useCallback((o,i)=>{if(o!=="global"&&H.current!==o)return null;const p=++T.current;return v.current.set(p,{owner:o,text:i}),S(),p},[S]),$=n.useCallback((o,i)=>{if(i!=null)v.current.get(i)?.owner===o&&v.current.delete(i);else for(const[p,V]of v.current)V.owner===o&&v.current.delete(p);S()},[S]),K=n.useCallback((o,i)=>{o?($("global"),B("global",i)):$("global")},[B,$]),d=n.useCallback((o,i,p)=>{i?($(o),B(o,p)):$(o)},[B,$]),C=[...v.current.values()],L={visible:C.length>0,text:C.at(-1)?.text??null,count:C.length},F=n.useRef(L);F.current=L;const D=n.useMemo(()=>({isLoading:L.visible,setLoading:K,setScreenLoading:d,begin:B,end:$}),[L.visible,K,d,B,$]),G=n.useRef(h);G.current=h,n.useEffect(()=>(G.current?.({setLoading:K}),()=>G.current?.(null)),[K]);const I=n.useCallback((o,i)=>O(p=>{if(i===null){if(!(o in p))return p;const V={...p};return delete V[o],V}return p[o]===i?p:{...p,[o]:i}}),[]),U=n.useCallback(()=>{const o=document.activeElement;if(!(o instanceof HTMLElement)||!q.current?.contains(o))return;const i=o.closest("[data-modal-route-key]");i&&R.current.set(i.dataset.modalRouteKey,o),q.current.focus({preventScroll:!0})},[]),J=n.useCallback(o=>{if(!Object.prototype.hasOwnProperty.call(w,o))throw new Error(`[react-modal-navigation] Unknown modal screen: ${o}`)},[w]),_=n.useCallback((o,i)=>{try{Promise.resolve(r[o]?.(i)).catch(p=>m(p,{phase:o}))}catch(p){m(p,{phase:o})}},[r,m]),W=n.useCallback((o,i,p)=>{J(i),U(),u({type:o,name:i,params:p})},[J,U]),ce=n.useCallback((o,i)=>W("NAVIGATE",o,i),[W]),le=n.useCallback((o,i)=>W("REPLACE",o,i),[W]),ie=n.useCallback((o,i)=>{x({}),W("RESET",o,i)},[W]),ue=n.useCallback(o=>{if(!o||typeof o!="object"||Array.isArray(o))throw new TypeError("[react-modal-navigation] setParams expects an object");u({type:"SET_PARAMS",params:o})},[]),de=n.useCallback(o=>{if(l.length<=1||A.current)return!1;if(A.current=!0,o!==void 0){const i=l.at(-2);x(p=>({...p,[i.key]:{id:++j.current,data:o}}))}return U(),u({type:"BACK"}),!0},[l,U]),Q=n.useCallback((o,i)=>F.current.visible&&r.lockCloseWhileLoading!==!1?Promise.resolve(!1):s(o,i,{route:b,stack:l}),[r.lockCloseWhileLoading,s,b,l]),me=n.useCallback(o=>Q("api",o),[Q]),Z=n.useMemo(()=>({navigate:ce,replace:le,reset:ie,setParams:ue,goBack:de,close:me,setLoading:K,canGoBack:l.length>1,stack:l,currentRoute:b}),[ce,le,ie,ue,de,me,K,l,b]);return n.useLayoutEffect(()=>{A.current=!1;const o=[...q.current?.querySelectorAll("[data-modal-route-key]")??[]].find(V=>V.dataset.modalRouteKey===E);if(!o)return;const i=R.current.get(E);(i?.isConnected&&o.contains(i)&&!i.matches(":disabled")&&!i.closest("[inert], [hidden]")?i:o).focus({preventScroll:!0})},[E]),n.useEffect(()=>{let o=!1;for(const[p,V]of v.current)V.owner!=="global"&&V.owner!==E&&(v.current.delete(p),o=!0);o&&S();const i=new Set(l.map(p=>p.key));for(const p of R.current.keys())i.has(p)||R.current.delete(p)},[E,l,S]),n.useEffect(()=>{if(k.current?.key!==E){if(k.current){const o={from:k.current,to:b,stack:l};_("onBlur",{route:k.current,...o}),_("onNavigate",o),_("onRouteChange",o)}_("onFocus",{route:b,stack:l}),k.current=b}},[b,E,l,_]),n.useEffect(()=>()=>{v.current.clear(),R.current.clear()},[]),n.useEffect(()=>{z.current||(z.current=!0,y?.({route:b,stack:l}))},[]),c.jsx(oe.Provider,{value:Z,children:c.jsx(ae.Provider,{value:D,children:c.jsxs(Me,{dialogRef:q,options:r,requestClose:Q,children:[c.jsx(je,{options:r,screen:w[b.name],route:b,navigation:Z,requestClose:Q,translate:a}),c.jsx("main",{className:"pmn-main",children:l.map(o=>c.jsx(Te,{route:o,screen:w[o.name],navigation:Z,focused:o.key===E,resultEvent:f[o.key]??null,bodyClassName:r.bodyClassName,setFooter:I,loadingApi:D,notifyError:m},o.key))}),c.jsx(Se,{screen:w[b.name],options:r,override:N[E],route:b,navigation:Z,requestClose:Q,translate:a,onError:m},E),c.jsx(Le,{loading:L,translate:a}),g&&c.jsxs("div",{className:"pmn-error",role:"alert",children:[c.jsx("span",{children:g.message||String(g)}),c.jsx("button",{type:"button",onClick:M,"aria-label":"Dismiss error",children:"×"})]})]})})})}const Fe=".pmn-overlay,.pmn-dialog,.pmn-dialog *{box-sizing:border-box}.pmn-overlay{position:fixed;inset:0;z-index:1000;display:flex;overscroll-behavior:none;background:#00000073}.pmn-place-right{justify-content:flex-end;align-items:stretch}.pmn-place-left{justify-content:flex-start;align-items:stretch}.pmn-place-center{justify-content:center;align-items:center}.pmn-place-top{justify-content:center;align-items:flex-start}.pmn-place-bottom{justify-content:center;align-items:flex-end}.pmn-dialog{--pmn-surface:#fff;--pmn-body:#fff;--pmn-text:#0f172a;--pmn-muted:#475569;--pmn-border:#e2e8f0;--pmn-hover:#f1f5f9;--pmn-overlay-card:rgba(255,255,255,.92);color-scheme:light;position:relative;display:flex;flex-direction:column;min-height:0;width:100%;max-width:min(calc(100vw - var(--pmn-gap)*2),var(--pmn-max-width, var(--pmn-width)));max-height:min(calc(100dvh - var(--pmn-gap)*2),var(--pmn-max-height, 100dvh));height:var(--pmn-height, 100%);overflow:hidden;outline:none;box-shadow:0 25px 50px -12px #00000040;background:var(--pmn-surface);color:var(--pmn-text)}.pmn-place-left .pmn-dialog,.pmn-place-right .pmn-dialog{height:calc(100dvh - var(--pmn-gap)*2);max-height:calc(100dvh - var(--pmn-gap)*2)}.pmn-place-center .pmn-dialog{height:var(--pmn-height, auto);min-height:150px}.pmn-place-top .pmn-dialog,.pmn-place-bottom .pmn-dialog{height:var(--pmn-height, auto);min-height:0}.pmn-dialog[data-modal-theme=dark]{--pmn-surface:#334155;--pmn-body:#334155;--pmn-text:#f1f5f9;--pmn-muted:#cbd5e1;--pmn-border:#475569;--pmn-hover:#1e293b;--pmn-overlay-card:rgba(51,65,85,.94);color-scheme:dark}.pmn-main{min-height:0;flex:1;overflow:hidden;display:flex;flex-direction:column;background:transparent}.pmn-body{height:100%;min-height:0;overflow-y:auto;overscroll-behavior:contain;padding:16px;flex:1}.pmn-body[hidden]{display:none!important}.pmn-header{display:flex;flex-shrink:0;height:64px;align-items:center;gap:12px;padding:0 20px;background:transparent}.pmn-header h2{font-size:18px;font-weight:600;min-width:0;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin:0}.pmn-header-spacer{flex:1}.pmn-border-bottom{border-bottom:1px solid var(--pmn-border)}.pmn-icon-button{display:inline-flex;align-items:center;justify-content:center;padding:8px;border:0;background:transparent;color:inherit;border-radius:8px;cursor:pointer}.pmn-icon-button:hover{background:var(--pmn-hover)}.pmn-footer{display:flex;flex-shrink:0;align-items:center;justify-content:flex-end;gap:12px;padding:16px 20px;background:transparent}.pmn-border-top{border-top:1px solid var(--pmn-border)}.pmn-button{padding:8px 16px;border-radius:8px;font-size:14px;font-weight:500;cursor:pointer}.pmn-button:disabled{opacity:.5;cursor:not-allowed}.pmn-button-secondary{border:1px solid var(--pmn-border);background:transparent;color:var(--pmn-text)}.pmn-button-secondary:hover:not(:disabled){background:var(--pmn-hover)}.pmn-button-primary{border:1px solid #2563eb;background:#2563eb;color:#fff}.pmn-button-primary:hover:not(:disabled){background:#1d4ed8}.pmn-loading-overlay{position:absolute;inset:0;z-index:50;display:flex;align-items:center;justify-content:center;background:var(--pmn-overlay-card);-webkit-backdrop-filter:blur(1px);backdrop-filter:blur(1px)}.pmn-loading-card{display:flex;flex-direction:column;align-items:center;gap:12px;max-width:85%;padding:20px 28px;border-radius:12px;background:var(--pmn-surface);box-shadow:0 10px 20px #00000026}.pmn-spinner{width:36px;height:36px;border:3px solid #2563eb;border-top-color:transparent;border-radius:50%;animation:pmn-spin 1s linear infinite}@keyframes pmn-spin{to{transform:rotate(360deg)}}.pmn-error{position:absolute;z-index:60;bottom:8px;left:12px;right:12px;display:flex;justify-content:space-between;gap:12px;padding:12px;border:1px solid #fca5a5;border-radius:8px;background:#fef2f2;color:#991b1b;font-size:13px}.pmn-error button{border:0;background:transparent;font-size:20px;cursor:pointer;color:inherit}.pmn-dialog input:not([type=checkbox]):not([type=radio]),.pmn-dialog textarea,.pmn-dialog select{color:var(--pmn-text);border-color:var(--pmn-border)}.pmn-error-screen{padding:24px;color:var(--pmn-text)}.pmn-error-screen p{color:#dc2626;overflow-wrap:anywhere}@media(max-width:640px){.pmn-overlay.pmn-mobile-fullscreen{padding:0!important}.pmn-mobile-fullscreen .pmn-dialog{max-width:100%;width:100%;height:100dvh;max-height:100dvh;border-radius:0!important}}@media(prefers-reduced-motion:reduce){.pmn-spinner{animation-duration:2s}}",he="react-modal-navigation-styles",ne=new WeakMap;function Be(){n.useInsertionEffect(()=>{if(typeof document>"u")return;const e=document;let t=ne.get(e);if(!t){let r=e.getElementById(he);const a=!r;r||(r=e.createElement("style"),r.id=he,r.setAttribute("data-react-modal-navigation",""),r.textContent=Fe,e.head.appendChild(r)),t={element:r,owned:a,count:0},ne.set(e,t)}return t.count+=1,()=>{t.count-=1,t.count===0&&(t.owned&&t.element.remove(),ne.delete(e))}},[])}const Pe={placement:"right",showHeader:!0,showBackButton:!0,showCloseButton:!0,viewportGap:5,borderRadius:12,closeOnOverlay:!1,closeOnEsc:!0},Oe=e=>({"modal.loading":"加载中...","modal.processing":"处理中...","modal.back":"返回","modal.close":"关闭","modal.cancel":"取消","modal.done":"完成"})[e]??e;function $e({registry:e,children:t,defaultOptions:r={},backgroundColor:a,theme:s,translate:y=Oe,onError:h}){Be();const[m,g]=n.useState(null),[M,l]=n.useState(null),u=n.useRef(null),f=n.useRef(new Map),x=n.useRef(0),N=n.useRef(null),O=n.useRef(!1),P=n.useRef(0),v=n.useRef(null),T=n.useRef(!0),R=n.useRef(null),q=n.useRef(h);q.current=h;const k=n.useCallback((d,C)=>{T.current&&l(d);try{q.current?q.current(d,C):console.error("[react-modal-navigation]",d)}catch(L){console.error("[react-modal-navigation] onError failed",L)}},[]),A=n.useCallback((d,C)=>{const L=f.current.get(d);f.current.delete(d),L?.(C)},[]),z=n.useCallback(d=>({...Pe,...r,...s!==void 0?{theme:s}:{},...a!==void 0?{backgroundColor:a}:{},...d.config.modalOptions,...d.overrides}),[r,s,a]),j=m?z(m):null,b=n.useRef(null);b.current=j,R.current=j;const E=n.useCallback(async(d="api",C,L={})=>{const F=u.current;if(!F||N.current||O.current)return!1;N.current=F.id,O.current=!0;const D=R.current??z(F),G={...L,reason:d,result:C,name:F.name};try{if(await D.onBeforeClose?.(G)===!1||u.current?.id!==F.id||!T.current)return!1;u.current=null,v.current=null,g(null),A(F.id,C===void 0?{status:"dismissed",reason:d}:{status:"confirmed",value:C,reason:d});try{await D.onClose?.(G)}catch(I){k(I,{phase:"onClose",name:F.name})}return!0}catch(I){return k(I,{phase:"onBeforeClose",name:F.name}),!1}finally{N.current===F.id&&(N.current=null),O.current=!1}},[z,k,A]),H=n.useCallback(async(d,C={},L={},F)=>{const D=e?.[d];if(!D)throw new Error(`[react-modal-navigation] Unknown modal: ${d}`);if(!D.screens?.[D.initialRoute])throw new Error(`[react-modal-navigation] Missing initial screen '${D.initialRoute}' in '${d}'`);if(!T.current||O.current||N.current)return null;O.current=!0;const G=P.current;try{const I=u.current;if(I){const J=R.current??z(I),_={reason:"replace",name:I.name,nextName:d};try{if(await J.onBeforeClose?.(_)===!1)return null}catch(W){return k(W,{phase:"onBeforeClose",name:I.name}),null}if(!T.current||G!==P.current||u.current?.id!==I.id)return null;u.current=null,v.current=null,g(null),A(I.id,{status:"replaced",reason:"replace"});try{await J.onClose?.(_)}catch(W){k(W,{phase:"onClose",name:I.name})}if(!T.current||G!==P.current)return null}const U={id:++x.current,name:d,params:C,config:D,overrides:L};return u.current=U,v.current=null,F&&f.current.set(U.id,F),l(null),g(U),U.id}finally{O.current=!1}},[e,z,k,A]),w=n.useCallback((d,C,L)=>H(d,C,L),[H]),S=n.useCallback((d,C,L)=>new Promise((F,D)=>{H(d,C,L,F).then(G=>{G===null&&F({status:"dismissed",reason:"blocked"})},D)}),[H]),B=n.useCallback(d=>E("api",d),[E]),$=n.useCallback((d,C)=>v.current?.setLoading(d,C),[]),K=n.useMemo(()=>({open:w,openAsync:S,close:B,setLoading:$,isOpen:!!m,activeName:m?.name??null,error:M,clearError:()=>l(null)}),[w,S,B,$,m,M]);return n.useEffect(()=>(T.current=!0,()=>{T.current=!1,P.current+=1,u.current=null;for(const d of f.current.values())d({status:"dismissed",reason:"unmount"});f.current.clear()}),[]),c.jsxs(ge.Provider,{value:K,children:[t,m&&c.jsx(xe,{config:m.config,params:m.params,options:j,translate:y,notifyError:k,error:M,clearError:()=>l(null),registerLoading:d=>{v.current=d},onRequestClose:E,onOpened:d=>{try{const C=b.current?.onOpen?.(d);Promise.resolve(C).catch(L=>k(L,{phase:"onOpen"}))}catch(C){k(C,{phase:"onOpen"})}}},m.id)]})}function qe(){const e=n.useContext(ge),t=n.useContext(oe);if(!e)throw new Error("[react-modal-navigation] useModal requires <ModalProvider>");return n.useMemo(()=>{const r=()=>{if(!t)throw new Error("[react-modal-navigation] navigation requires an active modal screen; use modal.open() outside a modal");return t};return{...e,modal:e,navigation:{navigate:(...s)=>r().navigate(...s),replace:(...s)=>r().replace(...s),reset:(...s)=>r().reset(...s),setParams:(...s)=>r().setParams(...s),goBack:(...s)=>r().goBack(...s),close:(...s)=>r().close(...s),get canGoBack(){return t?.canGoBack??!1},get stack(){return t?.stack??[]},get currentRoute(){return t?.currentRoute??null}}}},[e,t])}function Ae(){const e=n.useContext(oe);if(!e)throw new Error("useModalNavigation requires an active modal screen");return e}function se(){const e=n.useContext(ee);if(!e)throw new Error("useIsFocused must be called inside a modal screen");return e.isFocused}function De(e){const t=se();n.useEffect(()=>{if(t)return e()},[t,e])}function Ie(e){const t=n.useContext(ee);if(!t)throw new Error("useNavigationResult requires an active modal screen");const r=n.useRef(e),a=n.useRef(null);n.useEffect(()=>{r.current=e},[e]),n.useEffect(()=>{!t.isFocused||!t.resultEvent||a.current!==t.resultEvent.id&&(a.current=t.resultEvent.id,r.current(t.resultEvent.data))},[t.isFocused,t.resultEvent])}function He(e={}){const t=n.useContext(ee);if(!t)throw new Error("[react-modal-navigation] useModalFooter requires an active modal screen");const{setFooter:r,routeKey:a}=t,s=n.useRef(e);s.current=e;const y=n.useMemo(()=>(...R)=>s.current.done?.(...R),[]),h=n.useMemo(()=>(...R)=>(s.current.cancel??s.current.cancle)?.(...R),[]),m=n.useMemo(()=>(...R)=>s.current.renderFooter?.(...R),[]),g=typeof e.done=="function",M=typeof(e.cancel??e.cancle)=="function",l=typeof e.renderFooter=="function",{showFooter:u,showFooterBorder:f,doneDisabled:x,doneText:N,cancelText:O,loadingText:P,footerClassName:v}=e,T=n.useMemo(()=>({showFooter:u,showFooterBorder:f,doneDisabled:x,doneText:N,cancelText:O,loadingText:P,footerClassName:v,...g?{done:y}:{},...M?{cancel:h}:{},...l?{renderFooter:m}:{}}),[u,f,x,N,O,P,v,g,M,l,y,h,m]);n.useEffect(()=>{r(a,T)},[a,r,T]),n.useEffect(()=>()=>r(a,null),[a,r])}function ve(){const e=n.useContext(ae);if(!e)throw new Error("[react-modal-navigation] useModalLoading requires an active modal screen");return e}function Ke(){const e=ve(),t=se(),r=n.useRef(!0),a=n.useRef(!1),[s,y]=n.useState(!1),[h,m]=n.useState(null),g=n.useRef(e);return g.current=e,n.useEffect(()=>(r.current=!0,()=>{r.current=!1}),[]),{run:n.useCallback(async(l,u={})=>{if(a.current)return{status:"busy"};if(typeof l!="function")throw new TypeError("[react-modal-navigation] run requires a function");a.current=!0,r.current&&(y(!0),m(null));const f=g.current.showLoading(u.loadingText);try{const x=await l();return r.current&&await u.onSuccess?.(x),{status:"success",value:x}}catch(x){if(r.current){m(x);try{await u.onError?.(x)}catch(N){console.error("[react-modal-navigation] onError failed",N)}}if(u.throwOnError)throw x;return{status:"error",error:x}}finally{f!=null&&g.current.hideLoading(f),a.current=!1,r.current&&y(!1)}},[]),pending:s,error:h,clearError:()=>m(null),isFocused:t}}exports.ModalNavigator=xe;exports.ModalProvider=$e;exports.useFocusEffect=De;exports.useIsFocused=se;exports.useModal=qe;exports.useModalFooter=He;exports.useModalLoading=ve;exports.useModalNavigation=Ae;exports.useModalTask=Ke;exports.useNavigationResult=Ie;
@@ -0,0 +1,131 @@
1
+ import type { ComponentType, ReactNode } from 'react';
2
+ export type ModalTheme = 'auto' | 'light' | 'dark';
3
+ export type ModalBackground = string | { light?: string; dark?: string };
4
+ export interface ModalRoute<P = unknown> { key: string; name: string; params: P }
5
+ export type ModalResult<T = unknown> = { status: 'confirmed'; value: T; reason: string } | { status: 'dismissed' | 'replaced'; reason: string };
6
+ export interface ModalEventContext<T = unknown> { route?: ModalRoute; stack?: ModalRoute[]; from?: ModalRoute; to?: ModalRoute; reason?: string; result?: T; name?: string }
7
+ export interface ModalNavigation {
8
+ navigate(name: string, params?: unknown): void;
9
+ replace(name: string, params?: unknown): void;
10
+ reset(name: string, params?: unknown): void;
11
+ setParams(params: Record<string, unknown>): void;
12
+ goBack(result?: unknown): boolean;
13
+ close(result?: unknown): Promise<boolean>;
14
+ setLoading(value: boolean, text?: string): void;
15
+ readonly canGoBack: boolean;
16
+ readonly stack: ModalRoute[];
17
+ readonly currentRoute: ModalRoute | null;
18
+ }
19
+ export interface ModalOptions {
20
+ /** Dialog width in px or CSS units; takes precedence over size. */
21
+ width?: number | string;
22
+ /** Preset dialog width (sm=400, md=560, lg=720, xl=960, full=100%). */
23
+ size?: 'sm' | 'md' | 'lg' | 'xl' | 'full';
24
+ /** Dialog height. For left/right drawers viewport height minus twice viewportGap is enforced. */
25
+ height?: number | string;
26
+ /** Optional CSS maximum width; when provided, overrides the preset maximum. */
27
+ maxWidth?: number | string;
28
+ /** Maximum height for center/top/bottom dialogs. */
29
+ maxHeight?: number | string;
30
+ /** Display as fullscreen on viewports up to 640px. */
31
+ mobileFullscreen?: boolean;
32
+ /** Position: centered modal, side drawer, or top/bottom sheet. Default: right. */
33
+ placement?: 'left' | 'right' | 'center' | 'top' | 'bottom';
34
+ theme?: ModalTheme;
35
+ backgroundColor?: ModalBackground;
36
+ /** @deprecated Use backgroundColor */
37
+ backgroudColor?: ModalBackground;
38
+ /** Gap in pixels between dialog and viewport edges. Default: 5. */
39
+ viewportGap?: number;
40
+ borderRadius?: number | string;
41
+ closeOnOverlay?: boolean;
42
+ closeOnEsc?: boolean;
43
+ showHeader?: boolean;
44
+ showTitle?: boolean;
45
+ showBackButton?: boolean;
46
+ showCloseButton?: boolean;
47
+ showHeaderBorder?: boolean;
48
+ showFooterBorder?: boolean;
49
+ showFooter?: boolean;
50
+ lockCloseWhileLoading?: boolean;
51
+ className?: string;
52
+ bodyClassName?: string;
53
+ headerClassName?: string;
54
+ footerClassName?: string;
55
+ ariaLabel?: string;
56
+ onBeforeClose?: (context: ModalEventContext) => boolean | void | Promise<boolean | void>;
57
+ onClose?: (context: ModalEventContext) => void;
58
+ onOpen?: (context: ModalEventContext) => void;
59
+ onNavigate?: (context: ModalEventContext) => void;
60
+ onRouteChange?: (context: ModalEventContext) => void;
61
+ onFocus?: (context: ModalEventContext) => void;
62
+ onBlur?: (context: ModalEventContext) => void;
63
+ done?: (context: ModalActionContext) => void | Promise<void>;
64
+ cancel?: (context: ModalActionContext) => void | Promise<void>;
65
+ cancle?: (context: ModalActionContext) => void | Promise<void>;
66
+ doneDisabled?: boolean;
67
+ doneText?: string;
68
+ cancelText?: string;
69
+ loadingText?: string;
70
+ renderFooter?: (context: ModalActionContext & { pending: boolean }) => ReactNode;
71
+ renderHeader?: (context: ModalActionContext) => ReactNode;
72
+ renderHeaderRight?: (context: ModalActionContext) => ReactNode;
73
+ }
74
+ export interface ModalActionContext { route: ModalRoute; navigation: ModalNavigation; close: (reason?: string, result?: unknown) => Promise<boolean>; t: (key: string) => string }
75
+ export interface ModalScreen extends ModalOptions {
76
+ component: ComponentType<any>;
77
+ title?: string | ((context: { t: (key: string) => string; route: ModalRoute; navigation: ModalNavigation }) => ReactNode);
78
+ }
79
+ export interface ModalRegistryItem { initialRoute: string; modalOptions?: ModalOptions; screens: Record<string, ModalScreen> }
80
+ export type ModalRegistry = Record<string, ModalRegistryItem>;
81
+ export interface ModalProviderProps {
82
+ registry: ModalRegistry;
83
+ children: ReactNode;
84
+ defaultOptions?: ModalOptions;
85
+ backgroundColor?: ModalBackground;
86
+ theme?: ModalTheme;
87
+ translate?: (key: string) => string;
88
+ onError?: (error: unknown, context: { phase: string; [key: string]: unknown }) => void;
89
+ }
90
+ export interface ModalActions {
91
+ open(name: string, params?: unknown, overrides?: ModalOptions): Promise<number | null>;
92
+ openAsync<T = unknown>(name: string, params?: unknown, overrides?: ModalOptions): Promise<ModalResult<T>>;
93
+ close(result?: unknown): Promise<boolean>;
94
+ setLoading(value: boolean, text?: string): void;
95
+ readonly isOpen: boolean;
96
+ readonly activeName: string | null;
97
+ readonly error: unknown;
98
+ clearError(): void;
99
+ }
100
+ export interface UseModalReturn extends ModalActions { modal: ModalActions; navigation: ModalNavigation }
101
+ export function ModalProvider(props: ModalProviderProps): ReactNode;
102
+ export function ModalNavigator(props: Record<string, unknown>): ReactNode;
103
+ export function useModal(): UseModalReturn;
104
+ export function useModalNavigation(): ModalNavigation;
105
+ export function useIsFocused(): boolean;
106
+ export function useFocusEffect(callback: () => void | (() => void)): void;
107
+ export function useNavigationResult(callback: (result: unknown) => void): void;
108
+ export function useModalFooter(config: Partial<ModalOptions>): void;
109
+ export interface ModalLoadingActions {
110
+ isLoading: boolean;
111
+ setLoading(value: boolean, text?: string): void;
112
+ showLoading(text?: string): number | null;
113
+ hideLoading(token?: number | null): void;
114
+ }
115
+ export function useModalLoading(): ModalLoadingActions;
116
+
117
+ export type ModalTaskResult<T> = { status: 'success'; value: T } | { status: 'error'; error: unknown } | { status: 'busy' };
118
+ export interface ModalTaskOptions<T> {
119
+ loadingText?: string;
120
+ throwOnError?: boolean;
121
+ onSuccess?: (value: T) => void | Promise<void>;
122
+ onError?: (error: unknown) => void | Promise<void>;
123
+ }
124
+ export interface ModalTaskActions {
125
+ run<T>(task: () => T | Promise<T>, options?: ModalTaskOptions<T>): Promise<ModalTaskResult<T>>;
126
+ readonly pending: boolean;
127
+ readonly error: unknown;
128
+ clearError(): void;
129
+ readonly isFocused: boolean;
130
+ }
131
+ export function useModalTask(): ModalTaskActions;
package/dist/index.js ADDED
@@ -0,0 +1,550 @@
1
+ import { jsx as d, jsxs as ee } from "react/jsx-runtime";
2
+ import Re, { createContext as ce, useRef as u, useState as Q, useEffect as I, useReducer as Se, useCallback as b, useMemo as _, useLayoutEffect as Le, useInsertionEffect as Me, useContext as te } from "react";
3
+ import { createPortal as Ne } from "react-dom";
4
+ const ke = ce(null), ue = ce(null), se = ce(null), me = ce(null);
5
+ let Be = 0;
6
+ const de = (e, t) => ({ key: `modal-route-${++Be}`, name: e, params: t ?? {} }), Ee = (e, t) => [de(e, t)];
7
+ function Te(e, t) {
8
+ switch (t.type) {
9
+ case "RESET":
10
+ return Ee(t.name, t.params);
11
+ case "NAVIGATE": {
12
+ const n = e.findIndex((o) => o.name === t.name);
13
+ return n < 0 ? [...e, de(t.name, t.params)] : e.slice(0, n + 1).map((o, a) => a === n ? { ...o, params: t.params ?? {} } : o);
14
+ }
15
+ case "SET_PARAMS":
16
+ return e.map((n, o) => o === e.length - 1 ? { ...n, params: { ...n.params ?? {}, ...t.params ?? {} } } : n);
17
+ case "BACK":
18
+ return e.length > 1 ? e.slice(0, -1) : e;
19
+ case "REPLACE":
20
+ return e.length ? [...e.slice(0, -1), de(t.name, t.params)] : e;
21
+ default:
22
+ return e;
23
+ }
24
+ }
25
+ const ye = () => {
26
+ if (typeof document > "u") return "light";
27
+ const e = document.documentElement, t = document.body;
28
+ return e.classList.contains("dark") || t.classList.contains("dark") || e.dataset.theme === "dark" || t.dataset.theme === "dark" ? "dark" : e.classList.contains("light") || t.classList.contains("light") || e.dataset.theme === "light" || t.dataset.theme === "light" ? "light" : window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
29
+ };
30
+ let oe = 0;
31
+ const Z = [];
32
+ let le = null;
33
+ function Fe() {
34
+ if (oe++, oe === 1) {
35
+ const t = document.documentElement, n = document.body, o = { html: t.style.overflow, body: n.style.overflow, padding: n.style.paddingRight, width: n.style.getPropertyValue("--modal-scrollbar-width") }, a = Math.max(0, window.innerWidth - t.clientWidth), w = parseFloat(getComputedStyle(n).paddingRight) || 0;
36
+ a && (n.style.paddingRight = `${w + a}px`), n.style.setProperty("--modal-scrollbar-width", `${a}px`), t.style.overflow = "hidden", n.style.overflow = "hidden", le = () => {
37
+ t.style.overflow = o.html, n.style.overflow = o.body, n.style.paddingRight = o.padding, o.width ? n.style.setProperty("--modal-scrollbar-width", o.width) : n.style.removeProperty("--modal-scrollbar-width");
38
+ };
39
+ }
40
+ let e = !1;
41
+ return () => {
42
+ e || (e = !0, oe = Math.max(0, oe - 1), oe || (le?.(), le = null));
43
+ };
44
+ }
45
+ const Pe = 'a[href],button:not([disabled]),input:not([disabled]),textarea:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])', Oe = (e) => !e.closest('[inert], [hidden], [aria-hidden="true"]') && e.getClientRects().length > 0 && getComputedStyle(e).visibility !== "hidden" && getComputedStyle(e).display !== "none";
46
+ function $e({ dialogRef: e, options: t, requestClose: n, children: o }) {
47
+ const a = u(null), w = u(null), h = u(n);
48
+ h.current = n;
49
+ const m = u(t.closeOnEsc);
50
+ m.current = t.closeOnEsc;
51
+ const [g, L] = Q(ye), c = t.theme === "light" || t.theme === "dark" ? t.theme : g;
52
+ I(() => {
53
+ if (t.theme === "light" || t.theme === "dark") return;
54
+ const M = () => L(ye()), v = new MutationObserver(M);
55
+ for (const G of [document.documentElement, document.body]) v.observe(G, { attributes: !0, attributeFilter: ["class", "data-theme"] });
56
+ const R = window.matchMedia?.("(prefers-color-scheme: dark)");
57
+ return R?.addEventListener?.("change", M), M(), () => {
58
+ v.disconnect(), R?.removeEventListener?.("change", M);
59
+ };
60
+ }, [t.theme]), I(() => {
61
+ w.current = document.activeElement;
62
+ const M = Fe(), v = a.current;
63
+ Z.push(v), e.current?.focus({ preventScroll: !0 });
64
+ const R = (E) => {
65
+ const N = e.current;
66
+ if (!N || Z.at(-1) !== v) return;
67
+ if (E.key === "Escape" && m.current !== !1) {
68
+ E.preventDefault(), h.current("escape");
69
+ return;
70
+ }
71
+ if (E.key !== "Tab") return;
72
+ const O = [...N.querySelectorAll(Pe)].filter(Oe);
73
+ if (!O.length) {
74
+ E.preventDefault(), N.focus();
75
+ return;
76
+ }
77
+ const D = O[0], z = O.at(-1);
78
+ N.contains(document.activeElement) ? E.shiftKey && (document.activeElement === D || document.activeElement === N) ? (E.preventDefault(), z.focus()) : !E.shiftKey && (document.activeElement === z || document.activeElement === N) && (E.preventDefault(), D.focus()) : (E.preventDefault(), (E.shiftKey ? z : D).focus());
79
+ }, G = (E) => {
80
+ Z.at(-1) === v && e.current && !e.current.contains(E.target) && e.current.focus({ preventScroll: !0 });
81
+ };
82
+ return document.addEventListener("keydown", R), document.addEventListener("focusin", G), () => {
83
+ document.removeEventListener("keydown", R), document.removeEventListener("focusin", G);
84
+ const E = Z.at(-1) === v, N = Z.indexOf(v);
85
+ if (N !== -1 && Z.splice(N, 1), M(), E) {
86
+ const O = w.current;
87
+ O?.isConnected && !O.closest("[inert], [hidden]") ? O.focus?.({ preventScroll: !0 }) : Z.at(-1)?.querySelector("[role=dialog]")?.focus?.({ preventScroll: !0 });
88
+ }
89
+ };
90
+ }, [e]);
91
+ const l = t.backgroundColor ?? t.backgroudColor, p = typeof l == "string" ? l : l?.[c], y = typeof p == "string" && /^(#|rgb\(|rgba\(|hsl\(|hsla\(|oklch\(|color\(|var\()/.test(p.trim()) ? p : null, T = { sm: 400, md: 560, lg: 720, xl: 960, full: "100%" }, A = ["center", "left", "right", "top", "bottom"].includes(t.placement) ? t.placement : "right", $ = (M) => typeof M == "number" ? `${M}px` : M, x = $(t.width ?? T[t.size] ?? 460), F = $(t.height), S = $(t.maxHeight), H = $(t.maxWidth), k = Number(t.viewportGap ?? 5), q = Number.isFinite(k) ? Math.max(0, k) : 5, U = typeof t.borderRadius == "number" ? `${t.borderRadius}px` : t.borderRadius ?? "12px";
92
+ return Ne(/* @__PURE__ */ d(
93
+ "div",
94
+ {
95
+ ref: a,
96
+ className: `pmn-overlay pmn-place-${A} ${t.mobileFullscreen ? "pmn-mobile-fullscreen" : ""}`,
97
+ style: { padding: q },
98
+ onMouseDown: (M) => {
99
+ M.target === M.currentTarget && t.closeOnOverlay === !0 && h.current("overlay");
100
+ },
101
+ children: /* @__PURE__ */ d(
102
+ "section",
103
+ {
104
+ ref: e,
105
+ tabIndex: -1,
106
+ role: "dialog",
107
+ "aria-modal": "true",
108
+ "aria-label": t.ariaLabel ?? "Dialog",
109
+ "data-modal-theme": c,
110
+ className: `pmn-dialog ${c === "dark" ? "dark" : ""} ${!y && p ? p : ""} ${t.className ?? ""}`,
111
+ style: { "--pmn-width": x, "--pmn-gap": `${q}px`, ...F !== void 0 ? { "--pmn-height": F } : {}, ...S !== void 0 ? { "--pmn-max-height": S } : {}, ...H !== void 0 ? { "--pmn-max-width": H } : {}, borderRadius: U, ...y ? { backgroundColor: y } : {} },
112
+ children: o
113
+ }
114
+ )
115
+ }
116
+ ), document.body);
117
+ }
118
+ function xe({ back: e }) {
119
+ return /* @__PURE__ */ d("svg", { "aria-hidden": "true", viewBox: "0 0 24 24", width: "20", height: "20", fill: "none", stroke: "currentColor", strokeWidth: "2", children: e ? /* @__PURE__ */ d("path", { d: "m15 18-6-6 6-6" }) : /* @__PURE__ */ d("path", { d: "M18 6 6 18M6 6l12 12" }) });
120
+ }
121
+ function Ae({ options: e, screen: t, route: n, navigation: o, requestClose: a, translate: w }) {
122
+ if (e.showHeader === !1) return null;
123
+ const h = w ?? ((p) => p), m = t.showTitle ?? e.showTitle ?? !0, g = typeof t.title == "function" ? t.title({ t: h, route: n, navigation: o }) : t.title ?? n.name, L = { route: n, navigation: o, close: a, canGoBack: o.canGoBack, title: g, t: h }, c = t.renderHeader ?? e.renderHeader;
124
+ if (c) return c(L);
125
+ const l = t.renderHeaderRight ?? e.renderHeaderRight;
126
+ return /* @__PURE__ */ ee("header", { className: `pmn-header ${t.showHeaderBorder ?? e.showHeaderBorder ? "pmn-border-bottom" : ""} ${e.headerClassName ?? ""}`, children: [
127
+ e.showBackButton !== !1 && o.canGoBack && /* @__PURE__ */ d("button", { type: "button", className: "pmn-icon-button", "aria-label": h("modal.back"), onClick: () => o.goBack(), children: /* @__PURE__ */ d(xe, { back: !0 }) }),
128
+ m ? /* @__PURE__ */ d("h2", { children: g }) : /* @__PURE__ */ d("div", { className: "pmn-header-spacer" }),
129
+ l?.(L),
130
+ e.showCloseButton !== !1 && /* @__PURE__ */ d("button", { type: "button", className: "pmn-icon-button", "aria-label": h("modal.close"), onClick: () => a("header"), children: /* @__PURE__ */ d(xe, {}) })
131
+ ] });
132
+ }
133
+ function De({ screen: e, options: t, override: n, route: o, navigation: a, requestClose: w, translate: h, onError: m }) {
134
+ const [g, L] = Q(!1), c = h ?? ((k) => k), l = { ...t, ...e, ...n }, { showFooter: p, renderFooter: y, done: T, cancel: A, cancle: $ } = l, x = A ?? $, F = { route: o, navigation: a, close: w, t: c };
135
+ if (p === !1) return null;
136
+ const S = `pmn-footer ${l.showFooterBorder ? "pmn-border-top" : ""} ${l.footerClassName ?? ""}`;
137
+ if (typeof y == "function") return /* @__PURE__ */ d("footer", { className: S, children: y({ ...F, pending: g }) });
138
+ if (typeof T != "function" && typeof x != "function") return null;
139
+ const H = async (k) => {
140
+ if (!(g || typeof k != "function")) {
141
+ L(!0);
142
+ try {
143
+ await k(F);
144
+ } catch (q) {
145
+ m?.(q, { phase: "footer", route: o });
146
+ } finally {
147
+ L(!1);
148
+ }
149
+ }
150
+ };
151
+ return /* @__PURE__ */ ee("footer", { className: S, children: [
152
+ typeof x == "function" && /* @__PURE__ */ d("button", { type: "button", disabled: g, onClick: () => H(x), className: "pmn-button pmn-button-secondary", children: l.cancelText ?? c("modal.cancel") }),
153
+ typeof T == "function" && /* @__PURE__ */ d("button", { type: "button", disabled: g || l.doneDisabled === !0, onClick: () => H(T), className: "pmn-button pmn-button-primary", children: g ? l.loadingText ?? c("modal.processing") : l.doneText ?? c("modal.done") })
154
+ ] });
155
+ }
156
+ function He({ loading: e, translate: t }) {
157
+ if (!e.visible) return null;
158
+ const o = (t ?? ((w) => w))("modal.loading"), a = e.text ?? (o === "modal.loading" ? "加载中..." : o);
159
+ return /* @__PURE__ */ d("div", { className: "pmn-loading-overlay", role: "status", "aria-live": "polite", "aria-busy": "true", children: /* @__PURE__ */ ee("div", { className: "pmn-loading-card", children: [
160
+ /* @__PURE__ */ d("span", { className: "pmn-spinner", "aria-hidden": "true" }),
161
+ /* @__PURE__ */ d("span", { children: a })
162
+ ] }) });
163
+ }
164
+ class Ie extends Re.Component {
165
+ state = { error: null };
166
+ static getDerivedStateFromError(t) {
167
+ return { error: t };
168
+ }
169
+ componentDidCatch(t, n) {
170
+ this.props.onError?.(t, { phase: "render", route: this.props.route, componentStack: n.componentStack });
171
+ }
172
+ componentDidUpdate(t) {
173
+ t.route?.key !== this.props.route?.key && this.state.error && this.setState({ error: null });
174
+ }
175
+ render() {
176
+ return this.state.error ? /* @__PURE__ */ ee("div", { role: "alert", className: "pmn-error-screen", children: [
177
+ /* @__PURE__ */ d("strong", { children: "页面加载失败" }),
178
+ /* @__PURE__ */ d("p", { children: this.state.error.message }),
179
+ /* @__PURE__ */ d("button", { type: "button", className: "pmn-button pmn-button-secondary", onClick: () => this.setState({ error: null }), children: "重试" })
180
+ ] }) : this.props.children;
181
+ }
182
+ }
183
+ function qe({ route: e, screen: t, navigation: n, focused: o, resultEvent: a, setFooter: w, loadingApi: h, bodyClassName: m, notifyError: g }) {
184
+ const L = t.component, c = _(() => ({ isFocused: o, resultEvent: a, routeKey: e.key, setFooter: w }), [o, a, e.key, w]), l = _(() => ({
185
+ isLoading: o && h.isLoading,
186
+ setLoading: (p, y) => h.setScreenLoading(e.key, p, y),
187
+ showLoading: (p) => h.begin(e.key, p),
188
+ hideLoading: (p) => h.end(e.key, p)
189
+ }), [o, h, e.key]);
190
+ return /* @__PURE__ */ d(se.Provider, { value: c, children: /* @__PURE__ */ d(me.Provider, { value: l, children: /* @__PURE__ */ d("div", { hidden: !o, inert: !o, "data-modal-route-key": e.key, tabIndex: -1, className: `pmn-body ${m ?? ""}`, children: /* @__PURE__ */ d(Ie, { route: e, onError: g, children: /* @__PURE__ */ d(L, { route: e, navigation: n }) }) }) }) });
191
+ }
192
+ function je({ config: e, params: t, options: n, translate: o, onRequestClose: a, onOpened: w, registerLoading: h, notifyError: m, error: g, clearError: L }) {
193
+ const [c, l] = Se(Te, null, () => Ee(e.initialRoute, t)), [p, y] = Q({}), [T, A] = Q({}), [, $] = Q(0), x = u(/* @__PURE__ */ new Map()), F = u(0), S = u(/* @__PURE__ */ new Map()), H = u(null), k = u(null), q = u(!1), U = u(!1), M = u(0), v = c.at(-1), R = v.key, G = u(R);
194
+ G.current = R;
195
+ const E = e.screens, N = b(() => $((r) => r + 1), []), O = b((r, s) => {
196
+ if (r !== "global" && G.current !== r) return null;
197
+ const f = ++F.current;
198
+ return x.current.set(f, { owner: r, text: s }), N(), f;
199
+ }, [N]), D = b((r, s) => {
200
+ if (s != null)
201
+ x.current.get(s)?.owner === r && x.current.delete(s);
202
+ else
203
+ for (const [f, J] of x.current) J.owner === r && x.current.delete(f);
204
+ N();
205
+ }, [N]), z = b((r, s) => {
206
+ r ? (D("global"), O("global", s)) : D("global");
207
+ }, [O, D]), i = b((r, s, f) => {
208
+ s ? (D(r), O(r, f)) : D(r);
209
+ }, [O, D]), C = [...x.current.values()], B = { visible: C.length > 0, text: C.at(-1)?.text ?? null, count: C.length }, P = u(B);
210
+ P.current = B;
211
+ const j = _(() => ({ isLoading: B.visible, setLoading: z, setScreenLoading: i, begin: O, end: D }), [B.visible, z, i, O, D]), W = u(h);
212
+ W.current = h, I(() => (W.current?.({ setLoading: z }), () => W.current?.(null)), [z]);
213
+ const K = b((r, s) => A((f) => {
214
+ if (s === null) {
215
+ if (!(r in f)) return f;
216
+ const J = { ...f };
217
+ return delete J[r], J;
218
+ }
219
+ return f[r] === s ? f : { ...f, [r]: s };
220
+ }), []), Y = b(() => {
221
+ const r = document.activeElement;
222
+ if (!(r instanceof HTMLElement) || !H.current?.contains(r)) return;
223
+ const s = r.closest("[data-modal-route-key]");
224
+ s && S.current.set(s.dataset.modalRouteKey, r), H.current.focus({ preventScroll: !0 });
225
+ }, []), ne = b((r) => {
226
+ if (!Object.prototype.hasOwnProperty.call(E, r)) throw new Error(`[react-modal-navigation] Unknown modal screen: ${r}`);
227
+ }, [E]), X = b((r, s) => {
228
+ try {
229
+ Promise.resolve(n[r]?.(s)).catch((f) => m(f, { phase: r }));
230
+ } catch (f) {
231
+ m(f, { phase: r });
232
+ }
233
+ }, [n, m]), V = b((r, s, f) => {
234
+ ne(s), Y(), l({ type: r, name: s, params: f });
235
+ }, [ne, Y]), pe = b((r, s) => V("NAVIGATE", r, s), [V]), fe = b((r, s) => V("REPLACE", r, s), [V]), he = b((r, s) => {
236
+ y({}), V("RESET", r, s);
237
+ }, [V]), ge = b((r) => {
238
+ if (!r || typeof r != "object" || Array.isArray(r)) throw new TypeError("[react-modal-navigation] setParams expects an object");
239
+ l({ type: "SET_PARAMS", params: r });
240
+ }, []), be = b((r) => {
241
+ if (c.length <= 1 || q.current) return !1;
242
+ if (q.current = !0, r !== void 0) {
243
+ const s = c.at(-2);
244
+ y((f) => ({ ...f, [s.key]: { id: ++M.current, data: r } }));
245
+ }
246
+ return Y(), l({ type: "BACK" }), !0;
247
+ }, [c, Y]), re = b((r, s) => P.current.visible && n.lockCloseWhileLoading !== !1 ? Promise.resolve(!1) : a(r, s, { route: v, stack: c }), [n.lockCloseWhileLoading, a, v, c]), ve = b((r) => re("api", r), [re]), ae = _(() => ({ navigate: pe, replace: fe, reset: he, setParams: ge, goBack: be, close: ve, setLoading: z, canGoBack: c.length > 1, stack: c, currentRoute: v }), [pe, fe, he, ge, be, ve, z, c, v]);
248
+ return Le(() => {
249
+ q.current = !1;
250
+ const r = [...H.current?.querySelectorAll("[data-modal-route-key]") ?? []].find((J) => J.dataset.modalRouteKey === R);
251
+ if (!r) return;
252
+ const s = S.current.get(R);
253
+ (s?.isConnected && r.contains(s) && !s.matches(":disabled") && !s.closest("[inert], [hidden]") ? s : r).focus({ preventScroll: !0 });
254
+ }, [R]), I(() => {
255
+ let r = !1;
256
+ for (const [f, J] of x.current)
257
+ J.owner !== "global" && J.owner !== R && (x.current.delete(f), r = !0);
258
+ r && N();
259
+ const s = new Set(c.map((f) => f.key));
260
+ for (const f of S.current.keys()) s.has(f) || S.current.delete(f);
261
+ }, [R, c, N]), I(() => {
262
+ if (k.current?.key !== R) {
263
+ if (k.current) {
264
+ const r = { from: k.current, to: v, stack: c };
265
+ X("onBlur", { route: k.current, ...r }), X("onNavigate", r), X("onRouteChange", r);
266
+ }
267
+ X("onFocus", { route: v, stack: c }), k.current = v;
268
+ }
269
+ }, [v, R, c, X]), I(() => () => {
270
+ x.current.clear(), S.current.clear();
271
+ }, []), I(() => {
272
+ U.current || (U.current = !0, w?.({ route: v, stack: c }));
273
+ }, []), /* @__PURE__ */ d(ue.Provider, { value: ae, children: /* @__PURE__ */ d(me.Provider, { value: j, children: /* @__PURE__ */ ee($e, { dialogRef: H, options: n, requestClose: re, children: [
274
+ /* @__PURE__ */ d(Ae, { options: n, screen: E[v.name], route: v, navigation: ae, requestClose: re, translate: o }),
275
+ /* @__PURE__ */ d("main", { className: "pmn-main", children: c.map((r) => /* @__PURE__ */ d(
276
+ qe,
277
+ {
278
+ route: r,
279
+ screen: E[r.name],
280
+ navigation: ae,
281
+ focused: r.key === R,
282
+ resultEvent: p[r.key] ?? null,
283
+ bodyClassName: n.bodyClassName,
284
+ setFooter: K,
285
+ loadingApi: j,
286
+ notifyError: m
287
+ },
288
+ r.key
289
+ )) }),
290
+ /* @__PURE__ */ d(
291
+ De,
292
+ {
293
+ screen: E[v.name],
294
+ options: n,
295
+ override: T[R],
296
+ route: v,
297
+ navigation: ae,
298
+ requestClose: re,
299
+ translate: o,
300
+ onError: m
301
+ },
302
+ R
303
+ ),
304
+ /* @__PURE__ */ d(He, { loading: B, translate: o }),
305
+ g && /* @__PURE__ */ ee("div", { className: "pmn-error", role: "alert", children: [
306
+ /* @__PURE__ */ d("span", { children: g.message || String(g) }),
307
+ /* @__PURE__ */ d("button", { type: "button", onClick: L, "aria-label": "Dismiss error", children: "×" })
308
+ ] })
309
+ ] }) }) });
310
+ }
311
+ const Ke = ".pmn-overlay,.pmn-dialog,.pmn-dialog *{box-sizing:border-box}.pmn-overlay{position:fixed;inset:0;z-index:1000;display:flex;overscroll-behavior:none;background:#00000073}.pmn-place-right{justify-content:flex-end;align-items:stretch}.pmn-place-left{justify-content:flex-start;align-items:stretch}.pmn-place-center{justify-content:center;align-items:center}.pmn-place-top{justify-content:center;align-items:flex-start}.pmn-place-bottom{justify-content:center;align-items:flex-end}.pmn-dialog{--pmn-surface:#fff;--pmn-body:#fff;--pmn-text:#0f172a;--pmn-muted:#475569;--pmn-border:#e2e8f0;--pmn-hover:#f1f5f9;--pmn-overlay-card:rgba(255,255,255,.92);color-scheme:light;position:relative;display:flex;flex-direction:column;min-height:0;width:100%;max-width:min(calc(100vw - var(--pmn-gap)*2),var(--pmn-max-width, var(--pmn-width)));max-height:min(calc(100dvh - var(--pmn-gap)*2),var(--pmn-max-height, 100dvh));height:var(--pmn-height, 100%);overflow:hidden;outline:none;box-shadow:0 25px 50px -12px #00000040;background:var(--pmn-surface);color:var(--pmn-text)}.pmn-place-left .pmn-dialog,.pmn-place-right .pmn-dialog{height:calc(100dvh - var(--pmn-gap)*2);max-height:calc(100dvh - var(--pmn-gap)*2)}.pmn-place-center .pmn-dialog{height:var(--pmn-height, auto);min-height:150px}.pmn-place-top .pmn-dialog,.pmn-place-bottom .pmn-dialog{height:var(--pmn-height, auto);min-height:0}.pmn-dialog[data-modal-theme=dark]{--pmn-surface:#334155;--pmn-body:#334155;--pmn-text:#f1f5f9;--pmn-muted:#cbd5e1;--pmn-border:#475569;--pmn-hover:#1e293b;--pmn-overlay-card:rgba(51,65,85,.94);color-scheme:dark}.pmn-main{min-height:0;flex:1;overflow:hidden;display:flex;flex-direction:column;background:transparent}.pmn-body{height:100%;min-height:0;overflow-y:auto;overscroll-behavior:contain;padding:16px;flex:1}.pmn-body[hidden]{display:none!important}.pmn-header{display:flex;flex-shrink:0;height:64px;align-items:center;gap:12px;padding:0 20px;background:transparent}.pmn-header h2{font-size:18px;font-weight:600;min-width:0;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin:0}.pmn-header-spacer{flex:1}.pmn-border-bottom{border-bottom:1px solid var(--pmn-border)}.pmn-icon-button{display:inline-flex;align-items:center;justify-content:center;padding:8px;border:0;background:transparent;color:inherit;border-radius:8px;cursor:pointer}.pmn-icon-button:hover{background:var(--pmn-hover)}.pmn-footer{display:flex;flex-shrink:0;align-items:center;justify-content:flex-end;gap:12px;padding:16px 20px;background:transparent}.pmn-border-top{border-top:1px solid var(--pmn-border)}.pmn-button{padding:8px 16px;border-radius:8px;font-size:14px;font-weight:500;cursor:pointer}.pmn-button:disabled{opacity:.5;cursor:not-allowed}.pmn-button-secondary{border:1px solid var(--pmn-border);background:transparent;color:var(--pmn-text)}.pmn-button-secondary:hover:not(:disabled){background:var(--pmn-hover)}.pmn-button-primary{border:1px solid #2563eb;background:#2563eb;color:#fff}.pmn-button-primary:hover:not(:disabled){background:#1d4ed8}.pmn-loading-overlay{position:absolute;inset:0;z-index:50;display:flex;align-items:center;justify-content:center;background:var(--pmn-overlay-card);-webkit-backdrop-filter:blur(1px);backdrop-filter:blur(1px)}.pmn-loading-card{display:flex;flex-direction:column;align-items:center;gap:12px;max-width:85%;padding:20px 28px;border-radius:12px;background:var(--pmn-surface);box-shadow:0 10px 20px #00000026}.pmn-spinner{width:36px;height:36px;border:3px solid #2563eb;border-top-color:transparent;border-radius:50%;animation:pmn-spin 1s linear infinite}@keyframes pmn-spin{to{transform:rotate(360deg)}}.pmn-error{position:absolute;z-index:60;bottom:8px;left:12px;right:12px;display:flex;justify-content:space-between;gap:12px;padding:12px;border:1px solid #fca5a5;border-radius:8px;background:#fef2f2;color:#991b1b;font-size:13px}.pmn-error button{border:0;background:transparent;font-size:20px;cursor:pointer;color:inherit}.pmn-dialog input:not([type=checkbox]):not([type=radio]),.pmn-dialog textarea,.pmn-dialog select{color:var(--pmn-text);border-color:var(--pmn-border)}.pmn-error-screen{padding:24px;color:var(--pmn-text)}.pmn-error-screen p{color:#dc2626;overflow-wrap:anywhere}@media(max-width:640px){.pmn-overlay.pmn-mobile-fullscreen{padding:0!important}.pmn-mobile-fullscreen .pmn-dialog{max-width:100%;width:100%;height:100dvh;max-height:100dvh;border-radius:0!important}}@media(prefers-reduced-motion:reduce){.pmn-spinner{animation-duration:2s}}", we = "react-modal-navigation-styles", ie = /* @__PURE__ */ new WeakMap();
312
+ function Ge() {
313
+ Me(() => {
314
+ if (typeof document > "u") return;
315
+ const e = document;
316
+ let t = ie.get(e);
317
+ if (!t) {
318
+ let n = e.getElementById(we);
319
+ const o = !n;
320
+ n || (n = e.createElement("style"), n.id = we, n.setAttribute("data-react-modal-navigation", ""), n.textContent = Ke, e.head.appendChild(n)), t = { element: n, owned: o, count: 0 }, ie.set(e, t);
321
+ }
322
+ return t.count += 1, () => {
323
+ t.count -= 1, t.count === 0 && (t.owned && t.element.remove(), ie.delete(e));
324
+ };
325
+ }, []);
326
+ }
327
+ const ze = { placement: "right", showHeader: !0, showBackButton: !0, showCloseButton: !0, viewportGap: 5, borderRadius: 12, closeOnOverlay: !1, closeOnEsc: !0 }, We = (e) => ({ "modal.loading": "加载中...", "modal.processing": "处理中...", "modal.back": "返回", "modal.close": "关闭", "modal.cancel": "取消", "modal.done": "完成" })[e] ?? e;
328
+ function Je({ registry: e, children: t, defaultOptions: n = {}, backgroundColor: o, theme: a, translate: w = We, onError: h }) {
329
+ Ge();
330
+ const [m, g] = Q(null), [L, c] = Q(null), l = u(null), p = u(/* @__PURE__ */ new Map()), y = u(0), T = u(null), A = u(!1), $ = u(0), x = u(null), F = u(!0), S = u(null), H = u(h);
331
+ H.current = h;
332
+ const k = b((i, C) => {
333
+ F.current && c(i);
334
+ try {
335
+ H.current ? H.current(i, C) : console.error("[react-modal-navigation]", i);
336
+ } catch (B) {
337
+ console.error("[react-modal-navigation] onError failed", B);
338
+ }
339
+ }, []), q = b((i, C) => {
340
+ const B = p.current.get(i);
341
+ p.current.delete(i), B?.(C);
342
+ }, []), U = b((i) => ({ ...ze, ...n, ...a !== void 0 ? { theme: a } : {}, ...o !== void 0 ? { backgroundColor: o } : {}, ...i.config.modalOptions, ...i.overrides }), [n, a, o]), M = m ? U(m) : null, v = u(null);
343
+ v.current = M, S.current = M;
344
+ const R = b(async (i = "api", C, B = {}) => {
345
+ const P = l.current;
346
+ if (!P || T.current || A.current) return !1;
347
+ T.current = P.id, A.current = !0;
348
+ const j = S.current ?? U(P), W = { ...B, reason: i, result: C, name: P.name };
349
+ try {
350
+ if (await j.onBeforeClose?.(W) === !1 || l.current?.id !== P.id || !F.current) return !1;
351
+ l.current = null, x.current = null, g(null), q(P.id, C === void 0 ? { status: "dismissed", reason: i } : { status: "confirmed", value: C, reason: i });
352
+ try {
353
+ await j.onClose?.(W);
354
+ } catch (K) {
355
+ k(K, { phase: "onClose", name: P.name });
356
+ }
357
+ return !0;
358
+ } catch (K) {
359
+ return k(K, { phase: "onBeforeClose", name: P.name }), !1;
360
+ } finally {
361
+ T.current === P.id && (T.current = null), A.current = !1;
362
+ }
363
+ }, [U, k, q]), G = b(async (i, C = {}, B = {}, P) => {
364
+ const j = e?.[i];
365
+ if (!j) throw new Error(`[react-modal-navigation] Unknown modal: ${i}`);
366
+ if (!j.screens?.[j.initialRoute]) throw new Error(`[react-modal-navigation] Missing initial screen '${j.initialRoute}' in '${i}'`);
367
+ if (!F.current || A.current || T.current) return null;
368
+ A.current = !0;
369
+ const W = $.current;
370
+ try {
371
+ const K = l.current;
372
+ if (K) {
373
+ const ne = S.current ?? U(K), X = { reason: "replace", name: K.name, nextName: i };
374
+ try {
375
+ if (await ne.onBeforeClose?.(X) === !1) return null;
376
+ } catch (V) {
377
+ return k(V, { phase: "onBeforeClose", name: K.name }), null;
378
+ }
379
+ if (!F.current || W !== $.current || l.current?.id !== K.id) return null;
380
+ l.current = null, x.current = null, g(null), q(K.id, { status: "replaced", reason: "replace" });
381
+ try {
382
+ await ne.onClose?.(X);
383
+ } catch (V) {
384
+ k(V, { phase: "onClose", name: K.name });
385
+ }
386
+ if (!F.current || W !== $.current) return null;
387
+ }
388
+ const Y = { id: ++y.current, name: i, params: C, config: j, overrides: B };
389
+ return l.current = Y, x.current = null, P && p.current.set(Y.id, P), c(null), g(Y), Y.id;
390
+ } finally {
391
+ A.current = !1;
392
+ }
393
+ }, [e, U, k, q]), E = b((i, C, B) => G(i, C, B), [G]), N = b((i, C, B) => new Promise((P, j) => {
394
+ G(i, C, B, P).then((W) => {
395
+ W === null && P({ status: "dismissed", reason: "blocked" });
396
+ }, j);
397
+ }), [G]), O = b((i) => R("api", i), [R]), D = b((i, C) => x.current?.setLoading(i, C), []), z = _(() => ({ open: E, openAsync: N, close: O, setLoading: D, isOpen: !!m, activeName: m?.name ?? null, error: L, clearError: () => c(null) }), [E, N, O, D, m, L]);
398
+ return I(() => (F.current = !0, () => {
399
+ F.current = !1, $.current += 1, l.current = null;
400
+ for (const i of p.current.values()) i({ status: "dismissed", reason: "unmount" });
401
+ p.current.clear();
402
+ }), []), /* @__PURE__ */ ee(ke.Provider, { value: z, children: [
403
+ t,
404
+ m && /* @__PURE__ */ d(
405
+ je,
406
+ {
407
+ config: m.config,
408
+ params: m.params,
409
+ options: M,
410
+ translate: w,
411
+ notifyError: k,
412
+ error: L,
413
+ clearError: () => c(null),
414
+ registerLoading: (i) => {
415
+ x.current = i;
416
+ },
417
+ onRequestClose: R,
418
+ onOpened: (i) => {
419
+ try {
420
+ const C = v.current?.onOpen?.(i);
421
+ Promise.resolve(C).catch((B) => k(B, { phase: "onOpen" }));
422
+ } catch (C) {
423
+ k(C, { phase: "onOpen" });
424
+ }
425
+ }
426
+ },
427
+ m.id
428
+ )
429
+ ] });
430
+ }
431
+ function Qe() {
432
+ const e = te(ke), t = te(ue);
433
+ if (!e) throw new Error("[react-modal-navigation] useModal requires <ModalProvider>");
434
+ return _(() => {
435
+ const n = () => {
436
+ if (!t) throw new Error("[react-modal-navigation] navigation requires an active modal screen; use modal.open() outside a modal");
437
+ return t;
438
+ };
439
+ return { ...e, modal: e, navigation: {
440
+ navigate: (...a) => n().navigate(...a),
441
+ replace: (...a) => n().replace(...a),
442
+ reset: (...a) => n().reset(...a),
443
+ setParams: (...a) => n().setParams(...a),
444
+ goBack: (...a) => n().goBack(...a),
445
+ close: (...a) => n().close(...a),
446
+ get canGoBack() {
447
+ return t?.canGoBack ?? !1;
448
+ },
449
+ get stack() {
450
+ return t?.stack ?? [];
451
+ },
452
+ get currentRoute() {
453
+ return t?.currentRoute ?? null;
454
+ }
455
+ } };
456
+ }, [e, t]);
457
+ }
458
+ function Xe() {
459
+ const e = te(ue);
460
+ if (!e) throw new Error("useModalNavigation requires an active modal screen");
461
+ return e;
462
+ }
463
+ function Ce() {
464
+ const e = te(se);
465
+ if (!e) throw new Error("useIsFocused must be called inside a modal screen");
466
+ return e.isFocused;
467
+ }
468
+ function Ze(e) {
469
+ const t = Ce();
470
+ I(() => {
471
+ if (t)
472
+ return e();
473
+ }, [t, e]);
474
+ }
475
+ function et(e) {
476
+ const t = te(se);
477
+ if (!t) throw new Error("useNavigationResult requires an active modal screen");
478
+ const n = u(e), o = u(null);
479
+ I(() => {
480
+ n.current = e;
481
+ }, [e]), I(() => {
482
+ !t.isFocused || !t.resultEvent || o.current !== t.resultEvent.id && (o.current = t.resultEvent.id, n.current(t.resultEvent.data));
483
+ }, [t.isFocused, t.resultEvent]);
484
+ }
485
+ function tt(e = {}) {
486
+ const t = te(se);
487
+ if (!t) throw new Error("[react-modal-navigation] useModalFooter requires an active modal screen");
488
+ const { setFooter: n, routeKey: o } = t, a = u(e);
489
+ a.current = e;
490
+ const w = _(() => (...S) => a.current.done?.(...S), []), h = _(() => (...S) => (a.current.cancel ?? a.current.cancle)?.(...S), []), m = _(() => (...S) => a.current.renderFooter?.(...S), []), g = typeof e.done == "function", L = typeof (e.cancel ?? e.cancle) == "function", c = typeof e.renderFooter == "function", { showFooter: l, showFooterBorder: p, doneDisabled: y, doneText: T, cancelText: A, loadingText: $, footerClassName: x } = e, F = _(() => ({
491
+ showFooter: l,
492
+ showFooterBorder: p,
493
+ doneDisabled: y,
494
+ doneText: T,
495
+ cancelText: A,
496
+ loadingText: $,
497
+ footerClassName: x,
498
+ ...g ? { done: w } : {},
499
+ ...L ? { cancel: h } : {},
500
+ ...c ? { renderFooter: m } : {}
501
+ }), [l, p, y, T, A, $, x, g, L, c, w, h, m]);
502
+ I(() => {
503
+ n(o, F);
504
+ }, [o, n, F]), I(() => () => n(o, null), [o, n]);
505
+ }
506
+ function Ue() {
507
+ const e = te(me);
508
+ if (!e) throw new Error("[react-modal-navigation] useModalLoading requires an active modal screen");
509
+ return e;
510
+ }
511
+ function nt() {
512
+ const e = Ue(), t = Ce(), n = u(!0), o = u(!1), [a, w] = Q(!1), [h, m] = Q(null), g = u(e);
513
+ return g.current = e, I(() => (n.current = !0, () => {
514
+ n.current = !1;
515
+ }), []), { run: b(async (c, l = {}) => {
516
+ if (o.current) return { status: "busy" };
517
+ if (typeof c != "function") throw new TypeError("[react-modal-navigation] run requires a function");
518
+ o.current = !0, n.current && (w(!0), m(null));
519
+ const p = g.current.showLoading(l.loadingText);
520
+ try {
521
+ const y = await c();
522
+ return n.current && await l.onSuccess?.(y), { status: "success", value: y };
523
+ } catch (y) {
524
+ if (n.current) {
525
+ m(y);
526
+ try {
527
+ await l.onError?.(y);
528
+ } catch (T) {
529
+ console.error("[react-modal-navigation] onError failed", T);
530
+ }
531
+ }
532
+ if (l.throwOnError) throw y;
533
+ return { status: "error", error: y };
534
+ } finally {
535
+ p != null && g.current.hideLoading(p), o.current = !1, n.current && w(!1);
536
+ }
537
+ }, []), pending: a, error: h, clearError: () => m(null), isFocused: t };
538
+ }
539
+ export {
540
+ je as ModalNavigator,
541
+ Je as ModalProvider,
542
+ Ze as useFocusEffect,
543
+ Ce as useIsFocused,
544
+ Qe as useModal,
545
+ tt as useModalFooter,
546
+ Ue as useModalLoading,
547
+ Xe as useModalNavigation,
548
+ nt as useModalTask,
549
+ et as useNavigationResult
550
+ };
package/dist/style.css ADDED
@@ -0,0 +1,31 @@
1
+ /* Precompiled component styles. No Tailwind installation is required by the consumer. */
2
+ .pmn-overlay,.pmn-dialog,.pmn-dialog *{box-sizing:border-box}
3
+ .pmn-overlay{position:fixed;inset:0;z-index:1000;display:flex;overscroll-behavior:none;background:rgba(0,0,0,.45)}
4
+ .pmn-place-right{justify-content:flex-end;align-items:stretch}.pmn-place-left{justify-content:flex-start;align-items:stretch}.pmn-place-center{justify-content:center;align-items:center}.pmn-place-top{justify-content:center;align-items:flex-start}.pmn-place-bottom{justify-content:center;align-items:flex-end}
5
+ .pmn-dialog{--pmn-surface:#fff;--pmn-body:#fff;--pmn-text:#0f172a;--pmn-muted:#475569;--pmn-border:#e2e8f0;--pmn-hover:#f1f5f9;--pmn-overlay-card:rgba(255,255,255,.92);color-scheme:light;position:relative;display:flex;flex-direction:column;min-height:0;width:100%;max-width:min(calc(100vw - var(--pmn-gap)*2),var(--pmn-max-width, var(--pmn-width)));max-height:min(calc(100dvh - var(--pmn-gap)*2),var(--pmn-max-height, 100dvh));height:var(--pmn-height, 100%);overflow:hidden;outline:none;box-shadow:0 25px 50px -12px rgba(0,0,0,.25);background:var(--pmn-surface);color:var(--pmn-text)}
6
+ /* Side drawers fill the available viewport height with a 5px gap by default.
7
+ The overlay padding controls the gap on all four edges. */
8
+ .pmn-place-left .pmn-dialog,.pmn-place-right .pmn-dialog{height:calc(100dvh - var(--pmn-gap)*2);max-height:calc(100dvh - var(--pmn-gap)*2)}
9
+ .pmn-place-center .pmn-dialog{height:var(--pmn-height, auto);min-height:150px}
10
+ .pmn-place-top .pmn-dialog,.pmn-place-bottom .pmn-dialog{height:var(--pmn-height, auto);min-height:0}
11
+ .pmn-dialog[data-modal-theme=dark]{--pmn-surface:#334155;--pmn-body:#334155;--pmn-text:#f1f5f9;--pmn-muted:#cbd5e1;--pmn-border:#475569;--pmn-hover:#1e293b;--pmn-overlay-card:rgba(51,65,85,.94);color-scheme:dark}
12
+ .pmn-main{min-height:0;flex:1;overflow:hidden;display:flex;flex-direction:column;background:transparent}
13
+ .pmn-body{height:100%;min-height:0;overflow-y:auto;overscroll-behavior:contain;padding:16px;flex:1}.pmn-body[hidden]{display:none!important}
14
+ .pmn-header{display:flex;flex-shrink:0;height:64px;align-items:center;gap:12px;padding:0 20px;background:transparent}.pmn-header h2{font-size:18px;font-weight:600;min-width:0;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin:0}.pmn-header-spacer{flex:1}.pmn-border-bottom{border-bottom:1px solid var(--pmn-border)}
15
+ .pmn-icon-button{display:inline-flex;align-items:center;justify-content:center;padding:8px;border:0;background:transparent;color:inherit;border-radius:8px;cursor:pointer}.pmn-icon-button:hover{background:var(--pmn-hover)}
16
+ .pmn-footer{display:flex;flex-shrink:0;align-items:center;justify-content:flex-end;gap:12px;padding:16px 20px;background:transparent}.pmn-border-top{border-top:1px solid var(--pmn-border)}
17
+ .pmn-button{padding:8px 16px;border-radius:8px;font-size:14px;font-weight:500;cursor:pointer}.pmn-button:disabled{opacity:.5;cursor:not-allowed}.pmn-button-secondary{border:1px solid var(--pmn-border);background:transparent;color:var(--pmn-text)}.pmn-button-secondary:hover:not(:disabled){background:var(--pmn-hover)}.pmn-button-primary{border:1px solid #2563eb;background:#2563eb;color:white}.pmn-button-primary:hover:not(:disabled){background:#1d4ed8}
18
+ .pmn-loading-overlay{position:absolute;inset:0;z-index:50;display:flex;align-items:center;justify-content:center;background:var(--pmn-overlay-card);backdrop-filter:blur(1px)}.pmn-loading-card{display:flex;flex-direction:column;align-items:center;gap:12px;max-width:85%;padding:20px 28px;border-radius:12px;background:var(--pmn-surface);box-shadow:0 10px 20px rgba(0,0,0,.15)}.pmn-spinner{width:36px;height:36px;border:3px solid #2563eb;border-top-color:transparent;border-radius:50%;animation:pmn-spin 1s linear infinite}@keyframes pmn-spin{to{transform:rotate(360deg)}}
19
+ .pmn-error{position:absolute;z-index:60;bottom:8px;left:12px;right:12px;display:flex;justify-content:space-between;gap:12px;padding:12px;border:1px solid #fca5a5;border-radius:8px;background:#fef2f2;color:#991b1b;font-size:13px}.pmn-error button{border:0;background:transparent;font-size:20px;cursor:pointer;color:inherit}
20
+ .pmn-dialog input:not([type=checkbox]):not([type=radio]),.pmn-dialog textarea,.pmn-dialog select{color:var(--pmn-text);border-color:var(--pmn-border)}
21
+
22
+ .pmn-error-screen{padding:24px;color:var(--pmn-text)}.pmn-error-screen p{color:#dc2626;overflow-wrap:anywhere}
23
+
24
+ /* Opt-in mobile fullscreen for practical forms and multi-step flows. */
25
+ @media (max-width: 640px) {
26
+ .pmn-overlay.pmn-mobile-fullscreen { padding: 0 !important; }
27
+ .pmn-mobile-fullscreen .pmn-dialog { max-width: 100%; width: 100%; height: 100dvh; max-height: 100dvh; border-radius: 0 !important; }
28
+ }
29
+ @media (prefers-reduced-motion: reduce) {
30
+ .pmn-spinner { animation-duration: 2s; }
31
+ }
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "react-modal-navigation",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "React 19 modal navigation with automatic built-in CSS, Promise results and typed hooks",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "require": "./dist/index.cjs"
15
+ },
16
+ "./style.css": "./dist/style.css"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "sideEffects": false,
24
+ "scripts": {
25
+ "build": "vite build && node scripts/copy-types.mjs",
26
+ "prepublishOnly": "npm run build",
27
+ "pack:check": "npm pack --dry-run",
28
+ "typecheck": "tsc --noEmit --skipLibCheck --strict types/index.d.ts",
29
+ "test": "node --test tests/*.test.mjs"
30
+ },
31
+ "peerDependencies": {
32
+ "react": "^19.0.0",
33
+ "react-dom": "^19.0.0"
34
+ },
35
+ "devDependencies": {
36
+ "@vitejs/plugin-react": "^5.0.0",
37
+ "vite": "^7.0.0",
38
+ "react": "^19.0.0",
39
+ "react-dom": "^19.0.0",
40
+ "typescript": "^5.0.0",
41
+ "@types/react": "^19.0.0"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ }
46
+ }