react-modal-navigation 0.0.0-stage → 1.0.1

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,307 @@
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
+ 3. [配置优先级与响应式](#配置优先级与响应式)
13
+ 4. [页面导航与传参](#页面导航与传参)
14
+ 5. [Promise 结果与关闭守卫](#promise-结果与关闭守卫)
15
+ 6. [异步提交与 Loading](#异步提交与-loading)
16
+ 7. [主题与样式覆盖](#主题与样式覆盖)
17
+ 8. [事件、可访问性和注意事项](#事件可访问性和注意事项)
18
+ 9. [TypeScript 和发布](#typescript-和发布)
19
+
20
+ ## 安装和快速开始
21
+
22
+ ```bash
23
+ npm install react-modal-navigation
24
+ ```
25
+
26
+ ```jsx
27
+ import { ModalProvider, useModal } from 'react-modal-navigation';
28
+
29
+ function Home() {
30
+ const { modal } = useModal();
31
+ return <>
32
+ <button onClick={() => modal.open('editUser')}>居中编辑</button>
33
+ <button onClick={() => modal.open('deviceDrawer')}>右侧设备抽屉</button>
34
+ </>;
35
+ }
36
+
37
+ function UserForm() {
38
+ const { navigation } = useModal();
39
+ return <button onClick={() => navigation.close({ id: 1, name: 'Ada' })}>完成</button>;
40
+ }
41
+
42
+ function DeviceHome() {
43
+ const { navigation } = useModal();
44
+ return <button onClick={() => navigation.navigate('DeviceDetail', { id: 123 })}>查看详情</button>;
45
+ }
46
+
47
+ function DeviceDetail() {
48
+ const { navigation } = useModal();
49
+ return <button onClick={() => navigation.goBack()}>返回</button>;
50
+ }
51
+
52
+ const registry = {
53
+ editUser: {
54
+ initialRoute: 'UserForm',
55
+ modalOptions: { placement: 'center', width: 600, maxHeight: '85dvh' },
56
+ screens: { UserForm: { title: '编辑用户', component: UserForm } },
57
+ },
58
+ deviceDrawer: {
59
+ initialRoute: 'DeviceHome',
60
+ modalOptions: { placement: 'right', width: 520 },
61
+ screens: {
62
+ DeviceHome: { title: '设备', component: DeviceHome },
63
+ DeviceDetail: { title: '设备详情', component: DeviceDetail },
64
+ },
65
+ },
66
+ };
67
+
68
+ export default function App() {
69
+ return <ModalProvider registry={registry}><Home /></ModalProvider>;
70
+ }
71
+ ```
72
+
73
+ ## 推荐:对象形式打开弹窗
74
+
75
+ `modal.open()` 和 `modal.openAsync()` 现在都支持**字符串位置参数**及**对象参数**两种写法,原有代码不需要修改。推荐新项目采用对象形式,避免为了设置位置而传入无意义的 `{}`。
76
+
77
+ ```jsx
78
+ const { modal } = useModal();
79
+
80
+ // 推荐:只有名称和布局配置,不需要空的 params
81
+ await modal.open({
82
+ name: 'editUser',
83
+ options: { placement: 'bottom', width: '100%', height: '55dvh' },
84
+ });
85
+
86
+ // 带页面参数
87
+ await modal.open({
88
+ name: 'editUser',
89
+ params: { userId: 1001 },
90
+ options: { placement: 'center', width: 640 },
91
+ });
92
+
93
+ // Promise 弹窗也支持同样的对象形式
94
+ const result = await modal.openAsync({
95
+ name: 'editUser',
96
+ params: { userId: 1001 },
97
+ options: { placement: 'right', width: 520 },
98
+ });
99
+
100
+ // 旧 API 保持兼容
101
+ await modal.open('editUser');
102
+ await modal.open('editUser', { userId: 1001 });
103
+ await modal.open('editUser', {}, { placement: 'bottom', height: '55dvh' });
104
+ ```
105
+
106
+ 对象字段说明:
107
+
108
+ | 字段 | 类型 | 必填 | 说明 |
109
+ | --- | --- | --- | --- |
110
+ | `name` | `string` | 是 | registry 中注册的弹窗名称 |
111
+ | `params` | `unknown` | 否 | 传给初始 Screen 的页面参数,默认 `{}` |
112
+ | `options` | `ModalOptions` | 否 | 本次打开覆盖的布局、尺寸、主题和事件配置 |
113
+
114
+ **兼容规则:** 第一个参数是字符串时继续使用 `open(name, params?, overrides?)`;第一个参数是对象时使用 `open({ name, params?, options? })`。对象形式不需要再传第二、第三个参数。配置优先级仍为 `defaultOptions → modalOptions → options`。`openAsync` 的结果结构不变。
115
+
116
+ ## 弹窗位置与尺寸
117
+
118
+ ### placement 可选值
119
+
120
+ | placement | 说明 | 默认高度 | 推荐场景 |
121
+ | --- | --- | --- | --- |
122
+ | `center` | 居中弹窗 | 内容高度,受 maxHeight 限制 | 表单、确认框、详情 |
123
+ | `left` | 左侧抽屉 | 视口高度减去上下缝隙 | 导航、筛选 |
124
+ | `right` | 右侧抽屉(默认) | 视口高度减去上下缝隙 | 设备设置、编辑页 |
125
+ | `top` | 顶部弹出层 | 内容高度 | 顶部操作面板 |
126
+ | `bottom` | 底部弹出层 | 内容高度 | 移动端操作、筛选 |
127
+
128
+ ### 右侧抽屉:上下左右与视口保持 5px
129
+
130
+ ```jsx
131
+ modal.open('deviceDrawer', { deviceId: 123 }, {
132
+ placement: 'right',
133
+ width: 520,
134
+ viewportGap: 5,
135
+ });
136
+ ```
137
+
138
+ **左右抽屉的高度固定为 `calc(100dvh - 10px)`**(`viewportGap: 5` 时),即距视口顶部、底部各 5px;同时距左右视口边缘至少 5px。无需传 `height: '100dvh'`,即使传入 `height`,左右抽屉仍遵循视口高度规则。
139
+
140
+ ```jsx
141
+ // 左侧抽屉
142
+ modal.open('deviceDrawer', {}, { placement: 'left', width: '35vw' });
143
+
144
+ // 居中弹窗
145
+ modal.open('editUser', {}, {
146
+ placement: 'center', width: 680, height: '70dvh', maxHeight: '85dvh',
147
+ });
148
+
149
+ // 底部 Sheet
150
+ modal.open('editUser', {}, {
151
+ placement: 'bottom', width: '100%', height: '55dvh',
152
+ });
153
+
154
+ // 顶部 Sheet
155
+ modal.open('editUser', {}, {
156
+ placement: 'top', width: 800, height: 320,
157
+ });
158
+ ```
159
+
160
+ ### 尺寸预设
161
+
162
+ `size` 仅控制**宽度**,可选 `sm`(400px)、`md`(560px)、`lg`(720px)、`xl`(960px)、`full`(100%)。显式 `width` 优先于 `size`。不传时默认宽度 460px。
163
+
164
+ ```jsx
165
+ modal.open('editUser', {}, { placement: 'center', size: 'lg' });
166
+ modal.open('editUser', {}, { placement: 'center', size: 'lg', width: 640 }); // width 优先
167
+ ```
168
+
169
+ | 属性 | 类型 | 默认 | 作用 |
170
+ | --- | --- | --- | --- |
171
+ | `placement` | `center \| left \| right \| top \| bottom` | `right` | 弹窗位置 |
172
+ | `size` | `sm \| md \| lg \| xl \| full` | 未设置 | 预设宽度 |
173
+ | `width` | `number \| string` | `460` | 弹窗宽度,数字单位 px |
174
+ | `height` | `number \| string` | 自动 | 居中/顶部/底部高度;左右抽屉强制视口高度 |
175
+ | `maxWidth` | `number \| string` | 同 width | 最大宽度 |
176
+ | `maxHeight` | `number \| string` | 视口减去缝隙 | 最大高度;左右抽屉强制视口高度 |
177
+ | `viewportGap` | `number` | `5` | 视口四周留白,单位 px |
178
+ | `borderRadius` | `number \| string` | `12` | 圆角 |
179
+ | `mobileFullscreen` | `boolean` | `false` | 宽度 ≤640px 时铺满屏幕,覆盖缝隙规则 |
180
+
181
+ 视口边界使用 `100dvh`(动态视口高度),适应移动端浏览器地址栏;内容区域单独滚动,Header / Footer 不跟随内容滚动。`viewportGap` 应使用有限的非负数字。
182
+
183
+ ## 配置优先级与响应式
184
+
185
+ 从低到高:`ModalProvider.defaultOptions` → `registry[name].modalOptions` → `modal.open(name, params, overrides)`。
186
+
187
+ ```jsx
188
+ <ModalProvider registry={registry} defaultOptions={{ placement: 'center', size: 'md', viewportGap: 5 }}>
189
+ <App />
190
+ </ModalProvider>
191
+ ```
192
+
193
+ ```jsx
194
+ const registry = {
195
+ users: {
196
+ initialRoute: 'List',
197
+ modalOptions: { placement: 'right', width: 520 },
198
+ screens: { List: { title: '用户列表', component: UserList } },
199
+ },
200
+ };
201
+
202
+ modal.open('users'); // 默认右侧 520px
203
+ modal.open('users', {}, { placement: 'center', width: 700 }); // 本次临时居中
204
+ modal.open('users', {}, { mobileFullscreen: true }); // 手机端全屏
205
+ ```
206
+
207
+ 注意:`mobileFullscreen: true` 在宽度 ≤640px 时会覆盖 placement 与 viewportGap,故**不再保留 5px 缝隙**;需要缝隙时不要启用此项。
208
+
209
+ ## 页面导航与传参
210
+
211
+ ```jsx
212
+ function UserList() {
213
+ const { navigation } = useModal();
214
+ return <button onClick={() => navigation.navigate('UserDetail', { id: 8 })}>详情</button>;
215
+ }
216
+
217
+ function UserDetail() {
218
+ const { navigation } = useModal();
219
+ const id = navigation.currentRoute?.params?.id;
220
+ return <>
221
+ <p>用户 ID:{id}</p>
222
+ <button onClick={() => navigation.setParams({ tab: 'settings' })}>切换标签</button>
223
+ <button onClick={() => navigation.goBack({ updated: true })}>返回</button>
224
+ </>;
225
+ }
226
+ ```
227
+
228
+ `navigate` 进入路由,`goBack(result?)` 返回上一页,`replace` 替换当前页,`reset` 重置栈,`setParams` 合并当前页参数。隐藏页面 KeepAlive 保留状态;建议用 `useFocusEffect` 管理轮询和订阅。
229
+
230
+ ## Promise 结果与关闭守卫
231
+
232
+ ```jsx
233
+ const { modal } = useModal();
234
+ const result = await modal.openAsync('editUser');
235
+ if (result.status === 'confirmed') console.log(result.value);
236
+ else console.log(result.status, result.reason);
237
+ ```
238
+
239
+ 弹窗内部:`await navigation.close({ id: 1 })` 返回确认结果。`modal.open()` 返回 `Promise<number | null>`(弹窗实例 ID 或阻止打开时 null),不是 `openAsync` 的业务结果。
240
+
241
+ ```jsx
242
+ modalOptions: {
243
+ onBeforeClose: async ({ reason }) => {
244
+ if (hasUnsavedChanges()) return window.confirm('未保存,确定关闭吗?');
245
+ return true;
246
+ },
247
+ onOpen: ctx => console.log('opened', ctx),
248
+ onClose: ctx => console.log('closed', ctx.reason),
249
+ onNavigate: ctx => console.log('navigated', ctx),
250
+ onFocus: ctx => console.log('focused', ctx),
251
+ onBlur: ctx => console.log('blurred', ctx),
252
+ }
253
+ ```
254
+
255
+ 关闭被拒绝时弹窗继续存在。替换、取消和 Provider 卸载等情况,`openAsync()` 返回不同状态与 reason。不要将 `onClose` 当作弹窗仍处于活动状态的回调。
256
+
257
+ ## 异步提交与 Loading
258
+
259
+ ```jsx
260
+ import { useModal, useModalTask, useModalLoading } from 'react-modal-navigation';
261
+
262
+ function SaveScreen() {
263
+ const { navigation } = useModal();
264
+ const { run, pending, error } = useModalTask();
265
+ const save = async () => {
266
+ const result = await run(() => Promise.resolve({ id: 10 }), { loadingText: '保存中...' });
267
+ if (result.status === 'success') await navigation.close(result.value);
268
+ };
269
+ return <>
270
+ {error && <p role="alert">保存失败,请重试</p>}
271
+ <button disabled={pending} onClick={save}>保存</button>
272
+ </>;
273
+ }
274
+ ```
275
+
276
+ `useModalLoading().showLoading()` 返回任务 token,使用 `hideLoading(token)` 结束对应任务;多个任务并发不会相互误关。`useModalTask` 阻止同一 Hook 的重复提交,但**不会自动取消网络请求**。
277
+
278
+ ## 主题与样式覆盖
279
+
280
+ ```jsx
281
+ <ModalProvider registry={registry} theme="auto"
282
+ backgroundColor={{ light: '#fff', dark: '#334155' }}>
283
+ <App />
284
+ </ModalProvider>
285
+ ```
286
+
287
+ 不需要导入库的 CSS。已有 `className`、`bodyClassName`、`headerClassName`、`footerClassName` 可供业务样式覆盖;也可在业务项目中覆盖 `--pmn-surface`、`--pmn-text`、`--pmn-border` 等 CSS 变量。自动注入 CSS 时请注意 CSS 优先级。若站点 CSP 禁止内联样式,可改用 `react-modal-navigation/style.css` 静态导入,并按需配置 CSP。
288
+
289
+ ## 事件可访问性和注意事项
290
+
291
+ - `closeOnOverlay` 默认 `false`;`closeOnEsc` 默认 `true`。
292
+ - 对话框有 `role="dialog"`、`aria-modal`、Tab 焦点约束、关闭后焦点恢复。
293
+ - 背景滚动被锁定,并补偿滚动条宽度。
294
+ - KeepAlive 页面隐藏时保持组件挂载,轮询/订阅请自行按焦点停止。
295
+ - 若多次调用 `open()` 或存在异步关闭守卫,建议 `await` 以避免竞态。
296
+ - 样式注入依赖浏览器 DOM;SSR 时不会直接访问 `document`。严格 CSP 环境可能需要改为静态 CSS。
297
+
298
+ ## TypeScript 和发布
299
+
300
+ 公开类型位于 `types/index.d.ts`,包括 `ModalOptions`、`ModalRegistry`、`ModalNavigation`、`ModalResult` 等。
301
+
302
+ ```tsx
303
+ import type { ModalRegistry } from 'react-modal-navigation';
304
+ const registry: ModalRegistry = {
305
+ demo: { initialRoute: 'Main', modalOptions: { placement: 'right', size: 'lg' }, screens: { Main: { component: Main } } },
306
+ };
307
+ ```
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"),we=require("react-dom"),be=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??{}}),xe=(e,t)=>[re(e,t)];function Ee(e,t){switch(t.type){case"RESET":return xe(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),h=parseFloat(getComputedStyle(r).paddingRight)||0;s&&(r.style.paddingRight=`${h+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 Re='a[href],button:not([disabled]),input:not([disabled]),textarea:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])',je=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),h=n.useRef(null),g=n.useRef(r);g.current=r;const m=n.useRef(t.closeOnEsc);m.current=t.closeOnEsc;const[b,M]=n.useState(fe),l=t.theme==="light"||t.theme==="dark"?t.theme:b;n.useEffect(()=>{if(t.theme==="light"||t.theme==="dark")return;const S=()=>M(fe()),x=new MutationObserver(S);for(const H of[document.documentElement,document.body])x.observe(H,{attributes:!0,attributeFilter:["class","data-theme"]});const R=window.matchMedia?.("(prefers-color-scheme: dark)");return R?.addEventListener?.("change",S),S(),()=>{x.disconnect(),R?.removeEventListener?.("change",S)}},[t.theme]),n.useEffect(()=>{h.current=document.activeElement;const S=Ce(),x=s.current;Y.push(x),e.current?.focus({preventScroll:!0});const R=k=>{const L=e.current;if(!L||Y.at(-1)!==x)return;if(k.key==="Escape"&&m.current!==!1){k.preventDefault(),g.current("escape");return}if(k.key!=="Tab")return;const B=[...L.querySelectorAll(Re)].filter(je);if(!B.length){k.preventDefault(),L.focus();return}const O=B[0],K=B.at(-1);L.contains(document.activeElement)?k.shiftKey&&(document.activeElement===O||document.activeElement===L)?(k.preventDefault(),K.focus()):!k.shiftKey&&(document.activeElement===K||document.activeElement===L)&&(k.preventDefault(),O.focus()):(k.preventDefault(),(k.shiftKey?K:O).focus())},H=k=>{Y.at(-1)===x&&e.current&&!e.current.contains(k.target)&&e.current.focus({preventScroll:!0})};return document.addEventListener("keydown",R),document.addEventListener("focusin",H),()=>{document.removeEventListener("keydown",R),document.removeEventListener("focusin",H);const k=Y.at(-1)===x,L=Y.indexOf(x);if(L!==-1&&Y.splice(L,1),S(),k){const B=h.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],y=typeof f=="string"&&/^(#|rgb\(|rgba\(|hsl\(|hsla\(|oklch\(|color\(|var\()/.test(f.trim())?f:null,T={sm:400,md:560,lg:720,xl:960,full:"100%"},A=["center","left","right","top","bottom"].includes(t.placement)?t.placement:"right",P=S=>typeof S=="number"?`${S}px`:S,v=P(t.width??T[t.size]??460),F=P(t.height),j=P(t.maxHeight),q=P(t.maxWidth),w=Number(t.viewportGap??5),I=Number.isFinite(w)?Math.max(0,w):5,G=typeof t.borderRadius=="number"?`${t.borderRadius}px`:t.borderRadius??"12px";return we.createPortal(c.jsx("div",{ref:s,className:`pmn-overlay pmn-place-${A} ${t.mobileFullscreen?"pmn-mobile-fullscreen":""}`,style:{padding:I},onMouseDown:S=>{S.target===S.currentTarget&&t.closeOnOverlay===!0&&g.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":""} ${!y&&f?f:""} ${t.className??""}`,style:{"--pmn-width":v,"--pmn-gap":`${I}px`,...F!==void 0?{"--pmn-height":F}:{},...j!==void 0?{"--pmn-max-height":j}:{},...q!==void 0?{"--pmn-max-width":q}:{},borderRadius:G,...y?{backgroundColor:y}:{}},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 Se({options:e,screen:t,route:r,navigation:a,requestClose:s,translate:h}){if(e.showHeader===!1)return null;const g=h??(f=>f),m=t.showTitle??e.showTitle??!0,b=typeof t.title=="function"?t.title({t:g,route:r,navigation:a}):t.title??r.name,M={route:r,navigation:a,close:s,canGoBack:a.canGoBack,title:b,t:g},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":g("modal.back"),onClick:()=>a.goBack(),children:c.jsx(pe,{back:!0})}),m?c.jsx("h2",{children:b}):c.jsx("div",{className:"pmn-header-spacer"}),u?.(M),e.showCloseButton!==!1&&c.jsx("button",{type:"button",className:"pmn-icon-button","aria-label":g("modal.close"),onClick:()=>s("header"),children:c.jsx(pe,{})})]})}function Le({screen:e,options:t,override:r,route:a,navigation:s,requestClose:h,translate:g,onError:m}){const[b,M]=n.useState(!1),l=g??(w=>w),u={...t,...e,...r},{showFooter:f,renderFooter:y,done:T,cancel:A,cancle:P}=u,v=A??P,F={route:a,navigation:s,close:h,t:l};if(f===!1)return null;const j=`pmn-footer ${u.showFooterBorder?"pmn-border-top":""} ${u.footerClassName??""}`;if(typeof y=="function")return c.jsx("footer",{className:j,children:y({...F,pending:b})});if(typeof T!="function"&&typeof v!="function")return null;const q=async w=>{if(!(b||typeof w!="function")){M(!0);try{await w(F)}catch(I){m?.(I,{phase:"footer",route:a})}finally{M(!1)}}};return c.jsxs("footer",{className:j,children:[typeof v=="function"&&c.jsx("button",{type:"button",disabled:b,onClick:()=>q(v),className:"pmn-button pmn-button-secondary",children:u.cancelText??l("modal.cancel")}),typeof T=="function"&&c.jsx("button",{type:"button",disabled:b||u.doneDisabled===!0,onClick:()=>q(T),className:"pmn-button pmn-button-primary",children:b?u.loadingText??l("modal.processing"):u.doneText??l("modal.done")})]})}function Ne({loading:e,translate:t}){if(!e.visible)return null;const a=(t??(h=>h))("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 Te 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 Fe({route:e,screen:t,navigation:r,focused:a,resultEvent:s,setFooter:h,loadingApi:g,bodyClassName:m,notifyError:b}){const M=t.component,l=n.useMemo(()=>({isFocused:a,resultEvent:s,routeKey:e.key,setFooter:h}),[a,s,e.key,h]),u=n.useMemo(()=>({isLoading:a&&g.isLoading,setLoading:(f,y)=>g.setScreenLoading(e.key,f,y),showLoading:f=>g.begin(e.key,f),hideLoading:f=>g.end(e.key,f)}),[a,g,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(Te,{route:e,onError:b,children:c.jsx(M,{route:e,navigation:r})})})})})}function ye({config:e,params:t,options:r,translate:a,onRequestClose:s,onOpened:h,registerLoading:g,notifyError:m,error:b,clearError:M}){const[l,u]=n.useReducer(Ee,null,()=>xe(e.initialRoute,t)),[f,y]=n.useState({}),[T,A]=n.useState({}),[,P]=n.useState(0),v=n.useRef(new Map),F=n.useRef(0),j=n.useRef(new Map),q=n.useRef(null),w=n.useRef(null),I=n.useRef(!1),G=n.useRef(!1),S=n.useRef(0),x=l.at(-1),R=x.key,H=n.useRef(R);H.current=R;const k=e.screens,L=n.useCallback(()=>P(o=>o+1),[]),B=n.useCallback((o,i)=>{if(o!=="global"&&H.current!==o)return null;const p=++F.current;return v.current.set(p,{owner:o,text:i}),L(),p},[L]),O=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);L()},[L]),K=n.useCallback((o,i)=>{o?(O("global"),B("global",i)):O("global")},[B,O]),d=n.useCallback((o,i,p)=>{i?(O(o),B(o,p)):O(o)},[B,O]),E=[...v.current.values()],N={visible:E.length>0,text:E.at(-1)?.text??null,count:E.length},C=n.useRef(N);C.current=N;const D=n.useMemo(()=>({isLoading:N.visible,setLoading:K,setScreenLoading:d,begin:B,end:O}),[N.visible,K,d,B,O]),z=n.useRef(g);z.current=g,n.useEffect(()=>(z.current?.({setLoading:K}),()=>z.current?.(null)),[K]);const $=n.useCallback((o,i)=>A(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&&j.current.set(i.dataset.modalRouteKey,o),q.current.focus({preventScroll:!0})},[]),J=n.useCallback(o=>{if(!Object.prototype.hasOwnProperty.call(k,o))throw new Error(`[react-modal-navigation] Unknown modal screen: ${o}`)},[k]),_=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)=>{y({}),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||I.current)return!1;if(I.current=!0,o!==void 0){const i=l.at(-2);y(p=>({...p,[i.key]:{id:++S.current,data:o}}))}return U(),u({type:"BACK"}),!0},[l,U]),Q=n.useCallback((o,i)=>C.current.visible&&r.lockCloseWhileLoading!==!1?Promise.resolve(!1):s(o,i,{route:x,stack:l}),[r.lockCloseWhileLoading,s,x,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:x}),[ce,le,ie,ue,de,me,K,l,x]);return n.useLayoutEffect(()=>{I.current=!1;const o=[...q.current?.querySelectorAll("[data-modal-route-key]")??[]].find(V=>V.dataset.modalRouteKey===R);if(!o)return;const i=j.current.get(R);(i?.isConnected&&o.contains(i)&&!i.matches(":disabled")&&!i.closest("[inert], [hidden]")?i:o).focus({preventScroll:!0})},[R]),n.useEffect(()=>{let o=!1;for(const[p,V]of v.current)V.owner!=="global"&&V.owner!==R&&(v.current.delete(p),o=!0);o&&L();const i=new Set(l.map(p=>p.key));for(const p of j.current.keys())i.has(p)||j.current.delete(p)},[R,l,L]),n.useEffect(()=>{if(w.current?.key!==R){if(w.current){const o={from:w.current,to:x,stack:l};_("onBlur",{route:w.current,...o}),_("onNavigate",o),_("onRouteChange",o)}_("onFocus",{route:x,stack:l}),w.current=x}},[x,R,l,_]),n.useEffect(()=>()=>{v.current.clear(),j.current.clear()},[]),n.useEffect(()=>{G.current||(G.current=!0,h?.({route:x,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(Se,{options:r,screen:k[x.name],route:x,navigation:Z,requestClose:Q,translate:a}),c.jsx("main",{className:"pmn-main",children:l.map(o=>c.jsx(Fe,{route:o,screen:k[o.name],navigation:Z,focused:o.key===R,resultEvent:f[o.key]??null,bodyClassName:r.bodyClassName,setFooter:$,loadingApi:D,notifyError:m},o.key))}),c.jsx(Le,{screen:k[x.name],options:r,override:T[R],route:x,navigation:Z,requestClose:Q,translate:a,onError:m},R),c.jsx(Ne,{loading:N,translate:a}),b&&c.jsxs("div",{className:"pmn-error",role:"alert",children:[c.jsx("span",{children:b.message||String(b)}),c.jsx("button",{type:"button",onClick:M,"aria-label":"Dismiss error",children:"×"})]})]})})})}const Be=".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 Pe(){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=Be,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))}},[])}function ge(e,t,r){if(typeof e=="string"){if(!e.trim())throw new TypeError("[react-modal-navigation] modal name must not be empty");return{name:e,params:t??{},options:r??{}}}if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("[react-modal-navigation] open expects a modal name or { name, params?, options? }");const{name:a,params:s={},options:h={}}=e;if(typeof a!="string"||!a.trim())throw new TypeError("[react-modal-navigation] open config requires a non-empty string name");if(h===null||typeof h!="object"||Array.isArray(h))throw new TypeError("[react-modal-navigation] open config options must be an object");return{name:a,params:s,options:h}}const Ae={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:h=Oe,onError:g}){Pe();const[m,b]=n.useState(null),[M,l]=n.useState(null),u=n.useRef(null),f=n.useRef(new Map),y=n.useRef(0),T=n.useRef(null),A=n.useRef(!1),P=n.useRef(0),v=n.useRef(null),F=n.useRef(!0),j=n.useRef(null),q=n.useRef(g);q.current=g;const w=n.useCallback((d,E)=>{F.current&&l(d);try{q.current?q.current(d,E):console.error("[react-modal-navigation]",d)}catch(N){console.error("[react-modal-navigation] onError failed",N)}},[]),I=n.useCallback((d,E)=>{const N=f.current.get(d);f.current.delete(d),N?.(E)},[]),G=n.useCallback(d=>({...Ae,...r,...s!==void 0?{theme:s}:{},...a!==void 0?{backgroundColor:a}:{},...d.config.modalOptions,...d.overrides}),[r,s,a]),S=m?G(m):null,x=n.useRef(null);x.current=S,j.current=S;const R=n.useCallback(async(d="api",E,N={})=>{const C=u.current;if(!C||T.current||A.current)return!1;T.current=C.id,A.current=!0;const D=j.current??G(C),z={...N,reason:d,result:E,name:C.name};try{if(await D.onBeforeClose?.(z)===!1||u.current?.id!==C.id||!F.current)return!1;u.current=null,v.current=null,b(null),I(C.id,E===void 0?{status:"dismissed",reason:d}:{status:"confirmed",value:E,reason:d});try{await D.onClose?.(z)}catch($){w($,{phase:"onClose",name:C.name})}return!0}catch($){return w($,{phase:"onBeforeClose",name:C.name}),!1}finally{T.current===C.id&&(T.current=null),A.current=!1}},[G,w,I]),H=n.useCallback(async(d,E={},N={},C)=>{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(!F.current||A.current||T.current)return null;A.current=!0;const z=P.current;try{const $=u.current;if($){const J=j.current??G($),_={reason:"replace",name:$.name,nextName:d};try{if(await J.onBeforeClose?.(_)===!1)return null}catch(W){return w(W,{phase:"onBeforeClose",name:$.name}),null}if(!F.current||z!==P.current||u.current?.id!==$.id)return null;u.current=null,v.current=null,b(null),I($.id,{status:"replaced",reason:"replace"});try{await J.onClose?.(_)}catch(W){w(W,{phase:"onClose",name:$.name})}if(!F.current||z!==P.current)return null}const U={id:++y.current,name:d,params:E,config:D,overrides:N};return u.current=U,v.current=null,C&&f.current.set(U.id,C),l(null),b(U),U.id}finally{A.current=!1}},[e,G,w,I]),k=n.useCallback((d,E,N)=>{const C=ge(d,E,N);return H(C.name,C.params,C.options)},[H]),L=n.useCallback((d,E,N)=>{const C=ge(d,E,N);return new Promise((D,z)=>{H(C.name,C.params,C.options,D).then($=>{$===null&&D({status:"dismissed",reason:"blocked"})},z)})},[H]),B=n.useCallback(d=>R("api",d),[R]),O=n.useCallback((d,E)=>v.current?.setLoading(d,E),[]),K=n.useMemo(()=>({open:k,openAsync:L,close:B,setLoading:O,isOpen:!!m,activeName:m?.name??null,error:M,clearError:()=>l(null)}),[k,L,B,O,m,M]);return n.useEffect(()=>(F.current=!0,()=>{F.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(be.Provider,{value:K,children:[t,m&&c.jsx(ye,{config:m.config,params:m.params,options:S,translate:h,notifyError:w,error:M,clearError:()=>l(null),registerLoading:d=>{v.current=d},onRequestClose:R,onOpened:d=>{try{const E=x.current?.onOpen?.(d);Promise.resolve(E).catch(N=>w(N,{phase:"onOpen"}))}catch(E){w(E,{phase:"onOpen"})}}},m.id)]})}function qe(){const e=n.useContext(be),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 De(){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 Ie(e){const t=se();n.useEffect(()=>{if(t)return e()},[t,e])}function He(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 Ke(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 h=n.useMemo(()=>(...j)=>s.current.done?.(...j),[]),g=n.useMemo(()=>(...j)=>(s.current.cancel??s.current.cancle)?.(...j),[]),m=n.useMemo(()=>(...j)=>s.current.renderFooter?.(...j),[]),b=typeof e.done=="function",M=typeof(e.cancel??e.cancle)=="function",l=typeof e.renderFooter=="function",{showFooter:u,showFooterBorder:f,doneDisabled:y,doneText:T,cancelText:A,loadingText:P,footerClassName:v}=e,F=n.useMemo(()=>({showFooter:u,showFooterBorder:f,doneDisabled:y,doneText:T,cancelText:A,loadingText:P,footerClassName:v,...b?{done:h}:{},...M?{cancel:g}:{},...l?{renderFooter:m}:{}}),[u,f,y,T,A,P,v,b,M,l,h,g,m]);n.useEffect(()=>{r(a,F)},[a,r,F]),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 ze(){const e=ve(),t=se(),r=n.useRef(!0),a=n.useRef(!1),[s,h]=n.useState(!1),[g,m]=n.useState(null),b=n.useRef(e);return b.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&&(h(!0),m(null));const f=b.current.showLoading(u.loadingText);try{const y=await l();return r.current&&await u.onSuccess?.(y),{status:"success",value:y}}catch(y){if(r.current){m(y);try{await u.onError?.(y)}catch(T){console.error("[react-modal-navigation] onError failed",T)}}if(u.throwOnError)throw y;return{status:"error",error:y}}finally{f!=null&&b.current.hideLoading(f),a.current=!1,r.current&&h(!1)}},[]),pending:s,error:g,clearError:()=>m(null),isFocused:t}}exports.ModalNavigator=ye;exports.ModalProvider=$e;exports.useFocusEffect=Ie;exports.useIsFocused=se;exports.useModal=qe;exports.useModalFooter=Ke;exports.useModalLoading=ve;exports.useModalNavigation=De;exports.useModalTask=ze;exports.useNavigationResult=He;
@@ -0,0 +1,141 @@
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
+ /** Named-object form for opening a modal without positional placeholders. */
91
+ export interface ModalOpenConfig<P = unknown> {
92
+ name: string;
93
+ params?: P;
94
+ options?: ModalOptions;
95
+ }
96
+ export interface ModalActions {
97
+ /** Legacy positional call; preserved for backwards compatibility. */
98
+ open(name: string, params?: unknown, overrides?: ModalOptions): Promise<number | null>;
99
+ /** Recommended object call. */
100
+ open(config: ModalOpenConfig): Promise<number | null>;
101
+ openAsync<T = unknown>(name: string, params?: unknown, overrides?: ModalOptions): Promise<ModalResult<T>>;
102
+ openAsync<T = unknown>(config: ModalOpenConfig): Promise<ModalResult<T>>;
103
+ close(result?: unknown): Promise<boolean>;
104
+ setLoading(value: boolean, text?: string): void;
105
+ readonly isOpen: boolean;
106
+ readonly activeName: string | null;
107
+ readonly error: unknown;
108
+ clearError(): void;
109
+ }
110
+ export interface UseModalReturn extends ModalActions { modal: ModalActions; navigation: ModalNavigation }
111
+ export function ModalProvider(props: ModalProviderProps): ReactNode;
112
+ export function ModalNavigator(props: Record<string, unknown>): ReactNode;
113
+ export function useModal(): UseModalReturn;
114
+ export function useModalNavigation(): ModalNavigation;
115
+ export function useIsFocused(): boolean;
116
+ export function useFocusEffect(callback: () => void | (() => void)): void;
117
+ export function useNavigationResult(callback: (result: unknown) => void): void;
118
+ export function useModalFooter(config: Partial<ModalOptions>): void;
119
+ export interface ModalLoadingActions {
120
+ isLoading: boolean;
121
+ setLoading(value: boolean, text?: string): void;
122
+ showLoading(text?: string): number | null;
123
+ hideLoading(token?: number | null): void;
124
+ }
125
+ export function useModalLoading(): ModalLoadingActions;
126
+
127
+ export type ModalTaskResult<T> = { status: 'success'; value: T } | { status: 'error'; error: unknown } | { status: 'busy' };
128
+ export interface ModalTaskOptions<T> {
129
+ loadingText?: string;
130
+ throwOnError?: boolean;
131
+ onSuccess?: (value: T) => void | Promise<void>;
132
+ onError?: (error: unknown) => void | Promise<void>;
133
+ }
134
+ export interface ModalTaskActions {
135
+ run<T>(task: () => T | Promise<T>, options?: ModalTaskOptions<T>): Promise<ModalTaskResult<T>>;
136
+ readonly pending: boolean;
137
+ readonly error: unknown;
138
+ clearError(): void;
139
+ readonly isFocused: boolean;
140
+ }
141
+ export function useModalTask(): ModalTaskActions;
package/dist/index.js ADDED
@@ -0,0 +1,570 @@
1
+ import { jsx as d, jsxs as ee } from "react/jsx-runtime";
2
+ import Se, { createContext as ce, useRef as u, useState as Q, useEffect as I, useReducer as Le, useCallback as y, useMemo as _, useLayoutEffect as Me, useInsertionEffect as Ne, useContext as te } from "react";
3
+ import { createPortal as Te } from "react-dom";
4
+ const Ee = 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 ?? {} }), Re = (e, t) => [de(e, t)];
7
+ function Fe(e, t) {
8
+ switch (t.type) {
9
+ case "RESET":
10
+ return Re(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 ve = () => {
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 ie = null;
33
+ function Pe() {
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), h = parseFloat(getComputedStyle(n).paddingRight) || 0;
36
+ a && (n.style.paddingRight = `${h + a}px`), n.style.setProperty("--modal-scrollbar-width", `${a}px`), t.style.overflow = "hidden", n.style.overflow = "hidden", ie = () => {
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 || (ie?.(), ie = null));
43
+ };
44
+ }
45
+ const Ae = '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), h = u(null), g = u(n);
48
+ g.current = n;
49
+ const m = u(t.closeOnEsc);
50
+ m.current = t.closeOnEsc;
51
+ const [b, M] = Q(ve), c = t.theme === "light" || t.theme === "dark" ? t.theme : b;
52
+ I(() => {
53
+ if (t.theme === "light" || t.theme === "dark") return;
54
+ const N = () => M(ve()), v = new MutationObserver(N);
55
+ for (const z of [document.documentElement, document.body]) v.observe(z, { attributes: !0, attributeFilter: ["class", "data-theme"] });
56
+ const S = window.matchMedia?.("(prefers-color-scheme: dark)");
57
+ return S?.addEventListener?.("change", N), N(), () => {
58
+ v.disconnect(), S?.removeEventListener?.("change", N);
59
+ };
60
+ }, [t.theme]), I(() => {
61
+ h.current = document.activeElement;
62
+ const N = Pe(), v = a.current;
63
+ Z.push(v), e.current?.focus({ preventScroll: !0 });
64
+ const S = (E) => {
65
+ const T = e.current;
66
+ if (!T || Z.at(-1) !== v) return;
67
+ if (E.key === "Escape" && m.current !== !1) {
68
+ E.preventDefault(), g.current("escape");
69
+ return;
70
+ }
71
+ if (E.key !== "Tab") return;
72
+ const A = [...T.querySelectorAll(Ae)].filter(Oe);
73
+ if (!A.length) {
74
+ E.preventDefault(), T.focus();
75
+ return;
76
+ }
77
+ const j = A[0], G = A.at(-1);
78
+ T.contains(document.activeElement) ? E.shiftKey && (document.activeElement === j || document.activeElement === T) ? (E.preventDefault(), G.focus()) : !E.shiftKey && (document.activeElement === G || document.activeElement === T) && (E.preventDefault(), j.focus()) : (E.preventDefault(), (E.shiftKey ? G : j).focus());
79
+ }, z = (E) => {
80
+ Z.at(-1) === v && e.current && !e.current.contains(E.target) && e.current.focus({ preventScroll: !0 });
81
+ };
82
+ return document.addEventListener("keydown", S), document.addEventListener("focusin", z), () => {
83
+ document.removeEventListener("keydown", S), document.removeEventListener("focusin", z);
84
+ const E = Z.at(-1) === v, T = Z.indexOf(v);
85
+ if (T !== -1 && Z.splice(T, 1), N(), E) {
86
+ const A = h.current;
87
+ A?.isConnected && !A.closest("[inert], [hidden]") ? A.focus?.({ preventScroll: !0 }) : Z.at(-1)?.querySelector("[role=dialog]")?.focus?.({ preventScroll: !0 });
88
+ }
89
+ };
90
+ }, [e]);
91
+ const i = t.backgroundColor ?? t.backgroudColor, p = typeof i == "string" ? i : i?.[c], x = typeof p == "string" && /^(#|rgb\(|rgba\(|hsl\(|hsla\(|oklch\(|color\(|var\()/.test(p.trim()) ? p : null, F = { sm: 400, md: 560, lg: 720, xl: 960, full: "100%" }, $ = ["center", "left", "right", "top", "bottom"].includes(t.placement) ? t.placement : "right", O = (N) => typeof N == "number" ? `${N}px` : N, w = O(t.width ?? F[t.size] ?? 460), P = O(t.height), L = O(t.maxHeight), q = O(t.maxWidth), k = Number(t.viewportGap ?? 5), K = Number.isFinite(k) ? Math.max(0, k) : 5, U = typeof t.borderRadius == "number" ? `${t.borderRadius}px` : t.borderRadius ?? "12px";
92
+ return Te(/* @__PURE__ */ d(
93
+ "div",
94
+ {
95
+ ref: a,
96
+ className: `pmn-overlay pmn-place-${$} ${t.mobileFullscreen ? "pmn-mobile-fullscreen" : ""}`,
97
+ style: { padding: K },
98
+ onMouseDown: (N) => {
99
+ N.target === N.currentTarget && t.closeOnOverlay === !0 && g.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" : ""} ${!x && p ? p : ""} ${t.className ?? ""}`,
111
+ style: { "--pmn-width": w, "--pmn-gap": `${K}px`, ...P !== void 0 ? { "--pmn-height": P } : {}, ...L !== void 0 ? { "--pmn-max-height": L } : {}, ...q !== void 0 ? { "--pmn-max-width": q } : {}, borderRadius: U, ...x ? { backgroundColor: x } : {} },
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 je({ options: e, screen: t, route: n, navigation: o, requestClose: a, translate: h }) {
122
+ if (e.showHeader === !1) return null;
123
+ const g = h ?? ((p) => p), m = t.showTitle ?? e.showTitle ?? !0, b = typeof t.title == "function" ? t.title({ t: g, route: n, navigation: o }) : t.title ?? n.name, M = { route: n, navigation: o, close: a, canGoBack: o.canGoBack, title: b, t: g }, c = t.renderHeader ?? e.renderHeader;
124
+ if (c) return c(M);
125
+ const i = 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": g("modal.back"), onClick: () => o.goBack(), children: /* @__PURE__ */ d(xe, { back: !0 }) }),
128
+ m ? /* @__PURE__ */ d("h2", { children: b }) : /* @__PURE__ */ d("div", { className: "pmn-header-spacer" }),
129
+ i?.(M),
130
+ e.showCloseButton !== !1 && /* @__PURE__ */ d("button", { type: "button", className: "pmn-icon-button", "aria-label": g("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: h, translate: g, onError: m }) {
134
+ const [b, M] = Q(!1), c = g ?? ((k) => k), i = { ...t, ...e, ...n }, { showFooter: p, renderFooter: x, done: F, cancel: $, cancle: O } = i, w = $ ?? O, P = { route: o, navigation: a, close: h, t: c };
135
+ if (p === !1) return null;
136
+ const L = `pmn-footer ${i.showFooterBorder ? "pmn-border-top" : ""} ${i.footerClassName ?? ""}`;
137
+ if (typeof x == "function") return /* @__PURE__ */ d("footer", { className: L, children: x({ ...P, pending: b }) });
138
+ if (typeof F != "function" && typeof w != "function") return null;
139
+ const q = async (k) => {
140
+ if (!(b || typeof k != "function")) {
141
+ M(!0);
142
+ try {
143
+ await k(P);
144
+ } catch (K) {
145
+ m?.(K, { phase: "footer", route: o });
146
+ } finally {
147
+ M(!1);
148
+ }
149
+ }
150
+ };
151
+ return /* @__PURE__ */ ee("footer", { className: L, children: [
152
+ typeof w == "function" && /* @__PURE__ */ d("button", { type: "button", disabled: b, onClick: () => q(w), className: "pmn-button pmn-button-secondary", children: i.cancelText ?? c("modal.cancel") }),
153
+ typeof F == "function" && /* @__PURE__ */ d("button", { type: "button", disabled: b || i.doneDisabled === !0, onClick: () => q(F), className: "pmn-button pmn-button-primary", children: b ? i.loadingText ?? c("modal.processing") : i.doneText ?? c("modal.done") })
154
+ ] });
155
+ }
156
+ function qe({ loading: e, translate: t }) {
157
+ if (!e.visible) return null;
158
+ const o = (t ?? ((h) => h))("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 He extends Se.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 Ie({ route: e, screen: t, navigation: n, focused: o, resultEvent: a, setFooter: h, loadingApi: g, bodyClassName: m, notifyError: b }) {
184
+ const M = t.component, c = _(() => ({ isFocused: o, resultEvent: a, routeKey: e.key, setFooter: h }), [o, a, e.key, h]), i = _(() => ({
185
+ isLoading: o && g.isLoading,
186
+ setLoading: (p, x) => g.setScreenLoading(e.key, p, x),
187
+ showLoading: (p) => g.begin(e.key, p),
188
+ hideLoading: (p) => g.end(e.key, p)
189
+ }), [o, g, e.key]);
190
+ return /* @__PURE__ */ d(se.Provider, { value: c, children: /* @__PURE__ */ d(me.Provider, { value: i, children: /* @__PURE__ */ d("div", { hidden: !o, inert: !o, "data-modal-route-key": e.key, tabIndex: -1, className: `pmn-body ${m ?? ""}`, children: /* @__PURE__ */ d(He, { route: e, onError: b, children: /* @__PURE__ */ d(M, { route: e, navigation: n }) }) }) }) });
191
+ }
192
+ function Ke({ config: e, params: t, options: n, translate: o, onRequestClose: a, onOpened: h, registerLoading: g, notifyError: m, error: b, clearError: M }) {
193
+ const [c, i] = Le(Fe, null, () => Re(e.initialRoute, t)), [p, x] = Q({}), [F, $] = Q({}), [, O] = Q(0), w = u(/* @__PURE__ */ new Map()), P = u(0), L = u(/* @__PURE__ */ new Map()), q = u(null), k = u(null), K = u(!1), U = u(!1), N = u(0), v = c.at(-1), S = v.key, z = u(S);
194
+ z.current = S;
195
+ const E = e.screens, T = y(() => O((r) => r + 1), []), A = y((r, s) => {
196
+ if (r !== "global" && z.current !== r) return null;
197
+ const f = ++P.current;
198
+ return w.current.set(f, { owner: r, text: s }), T(), f;
199
+ }, [T]), j = y((r, s) => {
200
+ if (s != null)
201
+ w.current.get(s)?.owner === r && w.current.delete(s);
202
+ else
203
+ for (const [f, J] of w.current) J.owner === r && w.current.delete(f);
204
+ T();
205
+ }, [T]), G = y((r, s) => {
206
+ r ? (j("global"), A("global", s)) : j("global");
207
+ }, [A, j]), l = y((r, s, f) => {
208
+ s ? (j(r), A(r, f)) : j(r);
209
+ }, [A, j]), R = [...w.current.values()], B = { visible: R.length > 0, text: R.at(-1)?.text ?? null, count: R.length }, C = u(B);
210
+ C.current = B;
211
+ const H = _(() => ({ isLoading: B.visible, setLoading: G, setScreenLoading: l, begin: A, end: j }), [B.visible, G, l, A, j]), W = u(g);
212
+ W.current = g, I(() => (W.current?.({ setLoading: G }), () => W.current?.(null)), [G]);
213
+ const D = y((r, s) => $((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 = y(() => {
221
+ const r = document.activeElement;
222
+ if (!(r instanceof HTMLElement) || !q.current?.contains(r)) return;
223
+ const s = r.closest("[data-modal-route-key]");
224
+ s && L.current.set(s.dataset.modalRouteKey, r), q.current.focus({ preventScroll: !0 });
225
+ }, []), ne = y((r) => {
226
+ if (!Object.prototype.hasOwnProperty.call(E, r)) throw new Error(`[react-modal-navigation] Unknown modal screen: ${r}`);
227
+ }, [E]), X = y((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 = y((r, s, f) => {
234
+ ne(s), Y(), i({ type: r, name: s, params: f });
235
+ }, [ne, Y]), pe = y((r, s) => V("NAVIGATE", r, s), [V]), fe = y((r, s) => V("REPLACE", r, s), [V]), he = y((r, s) => {
236
+ x({}), V("RESET", r, s);
237
+ }, [V]), ge = y((r) => {
238
+ if (!r || typeof r != "object" || Array.isArray(r)) throw new TypeError("[react-modal-navigation] setParams expects an object");
239
+ i({ type: "SET_PARAMS", params: r });
240
+ }, []), be = y((r) => {
241
+ if (c.length <= 1 || K.current) return !1;
242
+ if (K.current = !0, r !== void 0) {
243
+ const s = c.at(-2);
244
+ x((f) => ({ ...f, [s.key]: { id: ++N.current, data: r } }));
245
+ }
246
+ return Y(), i({ type: "BACK" }), !0;
247
+ }, [c, Y]), re = y((r, s) => C.current.visible && n.lockCloseWhileLoading !== !1 ? Promise.resolve(!1) : a(r, s, { route: v, stack: c }), [n.lockCloseWhileLoading, a, v, c]), ye = y((r) => re("api", r), [re]), ae = _(() => ({ navigate: pe, replace: fe, reset: he, setParams: ge, goBack: be, close: ye, setLoading: G, canGoBack: c.length > 1, stack: c, currentRoute: v }), [pe, fe, he, ge, be, ye, G, c, v]);
248
+ return Me(() => {
249
+ K.current = !1;
250
+ const r = [...q.current?.querySelectorAll("[data-modal-route-key]") ?? []].find((J) => J.dataset.modalRouteKey === S);
251
+ if (!r) return;
252
+ const s = L.current.get(S);
253
+ (s?.isConnected && r.contains(s) && !s.matches(":disabled") && !s.closest("[inert], [hidden]") ? s : r).focus({ preventScroll: !0 });
254
+ }, [S]), I(() => {
255
+ let r = !1;
256
+ for (const [f, J] of w.current)
257
+ J.owner !== "global" && J.owner !== S && (w.current.delete(f), r = !0);
258
+ r && T();
259
+ const s = new Set(c.map((f) => f.key));
260
+ for (const f of L.current.keys()) s.has(f) || L.current.delete(f);
261
+ }, [S, c, T]), I(() => {
262
+ if (k.current?.key !== S) {
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, S, c, X]), I(() => () => {
270
+ w.current.clear(), L.current.clear();
271
+ }, []), I(() => {
272
+ U.current || (U.current = !0, h?.({ route: v, stack: c }));
273
+ }, []), /* @__PURE__ */ d(ue.Provider, { value: ae, children: /* @__PURE__ */ d(me.Provider, { value: H, children: /* @__PURE__ */ ee($e, { dialogRef: q, options: n, requestClose: re, children: [
274
+ /* @__PURE__ */ d(je, { 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
+ Ie,
277
+ {
278
+ route: r,
279
+ screen: E[r.name],
280
+ navigation: ae,
281
+ focused: r.key === S,
282
+ resultEvent: p[r.key] ?? null,
283
+ bodyClassName: n.bodyClassName,
284
+ setFooter: D,
285
+ loadingApi: H,
286
+ notifyError: m
287
+ },
288
+ r.key
289
+ )) }),
290
+ /* @__PURE__ */ d(
291
+ De,
292
+ {
293
+ screen: E[v.name],
294
+ options: n,
295
+ override: F[S],
296
+ route: v,
297
+ navigation: ae,
298
+ requestClose: re,
299
+ translate: o,
300
+ onError: m
301
+ },
302
+ S
303
+ ),
304
+ /* @__PURE__ */ d(qe, { loading: B, translate: o }),
305
+ b && /* @__PURE__ */ ee("div", { className: "pmn-error", role: "alert", children: [
306
+ /* @__PURE__ */ d("span", { children: b.message || String(b) }),
307
+ /* @__PURE__ */ d("button", { type: "button", onClick: M, "aria-label": "Dismiss error", children: "×" })
308
+ ] })
309
+ ] }) }) });
310
+ }
311
+ const ze = ".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", le = /* @__PURE__ */ new WeakMap();
312
+ function Ge() {
313
+ Ne(() => {
314
+ if (typeof document > "u") return;
315
+ const e = document;
316
+ let t = le.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 = ze, e.head.appendChild(n)), t = { element: n, owned: o, count: 0 }, le.set(e, t);
321
+ }
322
+ return t.count += 1, () => {
323
+ t.count -= 1, t.count === 0 && (t.owned && t.element.remove(), le.delete(e));
324
+ };
325
+ }, []);
326
+ }
327
+ function ke(e, t, n) {
328
+ if (typeof e == "string") {
329
+ if (!e.trim()) throw new TypeError("[react-modal-navigation] modal name must not be empty");
330
+ return { name: e, params: t ?? {}, options: n ?? {} };
331
+ }
332
+ if (e === null || typeof e != "object" || Array.isArray(e))
333
+ throw new TypeError("[react-modal-navigation] open expects a modal name or { name, params?, options? }");
334
+ const { name: o, params: a = {}, options: h = {} } = e;
335
+ if (typeof o != "string" || !o.trim())
336
+ throw new TypeError("[react-modal-navigation] open config requires a non-empty string name");
337
+ if (h === null || typeof h != "object" || Array.isArray(h))
338
+ throw new TypeError("[react-modal-navigation] open config options must be an object");
339
+ return { name: o, params: a, options: h };
340
+ }
341
+ const We = { placement: "right", showHeader: !0, showBackButton: !0, showCloseButton: !0, viewportGap: 5, borderRadius: 12, closeOnOverlay: !1, closeOnEsc: !0 }, Ue = (e) => ({ "modal.loading": "加载中...", "modal.processing": "处理中...", "modal.back": "返回", "modal.close": "关闭", "modal.cancel": "取消", "modal.done": "完成" })[e] ?? e;
342
+ function Qe({ registry: e, children: t, defaultOptions: n = {}, backgroundColor: o, theme: a, translate: h = Ue, onError: g }) {
343
+ Ge();
344
+ const [m, b] = Q(null), [M, c] = Q(null), i = u(null), p = u(/* @__PURE__ */ new Map()), x = u(0), F = u(null), $ = u(!1), O = u(0), w = u(null), P = u(!0), L = u(null), q = u(g);
345
+ q.current = g;
346
+ const k = y((l, R) => {
347
+ P.current && c(l);
348
+ try {
349
+ q.current ? q.current(l, R) : console.error("[react-modal-navigation]", l);
350
+ } catch (B) {
351
+ console.error("[react-modal-navigation] onError failed", B);
352
+ }
353
+ }, []), K = y((l, R) => {
354
+ const B = p.current.get(l);
355
+ p.current.delete(l), B?.(R);
356
+ }, []), U = y((l) => ({ ...We, ...n, ...a !== void 0 ? { theme: a } : {}, ...o !== void 0 ? { backgroundColor: o } : {}, ...l.config.modalOptions, ...l.overrides }), [n, a, o]), N = m ? U(m) : null, v = u(null);
357
+ v.current = N, L.current = N;
358
+ const S = y(async (l = "api", R, B = {}) => {
359
+ const C = i.current;
360
+ if (!C || F.current || $.current) return !1;
361
+ F.current = C.id, $.current = !0;
362
+ const H = L.current ?? U(C), W = { ...B, reason: l, result: R, name: C.name };
363
+ try {
364
+ if (await H.onBeforeClose?.(W) === !1 || i.current?.id !== C.id || !P.current) return !1;
365
+ i.current = null, w.current = null, b(null), K(C.id, R === void 0 ? { status: "dismissed", reason: l } : { status: "confirmed", value: R, reason: l });
366
+ try {
367
+ await H.onClose?.(W);
368
+ } catch (D) {
369
+ k(D, { phase: "onClose", name: C.name });
370
+ }
371
+ return !0;
372
+ } catch (D) {
373
+ return k(D, { phase: "onBeforeClose", name: C.name }), !1;
374
+ } finally {
375
+ F.current === C.id && (F.current = null), $.current = !1;
376
+ }
377
+ }, [U, k, K]), z = y(async (l, R = {}, B = {}, C) => {
378
+ const H = e?.[l];
379
+ if (!H) throw new Error(`[react-modal-navigation] Unknown modal: ${l}`);
380
+ if (!H.screens?.[H.initialRoute]) throw new Error(`[react-modal-navigation] Missing initial screen '${H.initialRoute}' in '${l}'`);
381
+ if (!P.current || $.current || F.current) return null;
382
+ $.current = !0;
383
+ const W = O.current;
384
+ try {
385
+ const D = i.current;
386
+ if (D) {
387
+ const ne = L.current ?? U(D), X = { reason: "replace", name: D.name, nextName: l };
388
+ try {
389
+ if (await ne.onBeforeClose?.(X) === !1) return null;
390
+ } catch (V) {
391
+ return k(V, { phase: "onBeforeClose", name: D.name }), null;
392
+ }
393
+ if (!P.current || W !== O.current || i.current?.id !== D.id) return null;
394
+ i.current = null, w.current = null, b(null), K(D.id, { status: "replaced", reason: "replace" });
395
+ try {
396
+ await ne.onClose?.(X);
397
+ } catch (V) {
398
+ k(V, { phase: "onClose", name: D.name });
399
+ }
400
+ if (!P.current || W !== O.current) return null;
401
+ }
402
+ const Y = { id: ++x.current, name: l, params: R, config: H, overrides: B };
403
+ return i.current = Y, w.current = null, C && p.current.set(Y.id, C), c(null), b(Y), Y.id;
404
+ } finally {
405
+ $.current = !1;
406
+ }
407
+ }, [e, U, k, K]), E = y((l, R, B) => {
408
+ const C = ke(l, R, B);
409
+ return z(C.name, C.params, C.options);
410
+ }, [z]), T = y((l, R, B) => {
411
+ const C = ke(l, R, B);
412
+ return new Promise((H, W) => {
413
+ z(C.name, C.params, C.options, H).then((D) => {
414
+ D === null && H({ status: "dismissed", reason: "blocked" });
415
+ }, W);
416
+ });
417
+ }, [z]), A = y((l) => S("api", l), [S]), j = y((l, R) => w.current?.setLoading(l, R), []), G = _(() => ({ open: E, openAsync: T, close: A, setLoading: j, isOpen: !!m, activeName: m?.name ?? null, error: M, clearError: () => c(null) }), [E, T, A, j, m, M]);
418
+ return I(() => (P.current = !0, () => {
419
+ P.current = !1, O.current += 1, i.current = null;
420
+ for (const l of p.current.values()) l({ status: "dismissed", reason: "unmount" });
421
+ p.current.clear();
422
+ }), []), /* @__PURE__ */ ee(Ee.Provider, { value: G, children: [
423
+ t,
424
+ m && /* @__PURE__ */ d(
425
+ Ke,
426
+ {
427
+ config: m.config,
428
+ params: m.params,
429
+ options: N,
430
+ translate: h,
431
+ notifyError: k,
432
+ error: M,
433
+ clearError: () => c(null),
434
+ registerLoading: (l) => {
435
+ w.current = l;
436
+ },
437
+ onRequestClose: S,
438
+ onOpened: (l) => {
439
+ try {
440
+ const R = v.current?.onOpen?.(l);
441
+ Promise.resolve(R).catch((B) => k(B, { phase: "onOpen" }));
442
+ } catch (R) {
443
+ k(R, { phase: "onOpen" });
444
+ }
445
+ }
446
+ },
447
+ m.id
448
+ )
449
+ ] });
450
+ }
451
+ function Xe() {
452
+ const e = te(Ee), t = te(ue);
453
+ if (!e) throw new Error("[react-modal-navigation] useModal requires <ModalProvider>");
454
+ return _(() => {
455
+ const n = () => {
456
+ if (!t) throw new Error("[react-modal-navigation] navigation requires an active modal screen; use modal.open() outside a modal");
457
+ return t;
458
+ };
459
+ return { ...e, modal: e, navigation: {
460
+ navigate: (...a) => n().navigate(...a),
461
+ replace: (...a) => n().replace(...a),
462
+ reset: (...a) => n().reset(...a),
463
+ setParams: (...a) => n().setParams(...a),
464
+ goBack: (...a) => n().goBack(...a),
465
+ close: (...a) => n().close(...a),
466
+ get canGoBack() {
467
+ return t?.canGoBack ?? !1;
468
+ },
469
+ get stack() {
470
+ return t?.stack ?? [];
471
+ },
472
+ get currentRoute() {
473
+ return t?.currentRoute ?? null;
474
+ }
475
+ } };
476
+ }, [e, t]);
477
+ }
478
+ function Ze() {
479
+ const e = te(ue);
480
+ if (!e) throw new Error("useModalNavigation requires an active modal screen");
481
+ return e;
482
+ }
483
+ function Ce() {
484
+ const e = te(se);
485
+ if (!e) throw new Error("useIsFocused must be called inside a modal screen");
486
+ return e.isFocused;
487
+ }
488
+ function et(e) {
489
+ const t = Ce();
490
+ I(() => {
491
+ if (t)
492
+ return e();
493
+ }, [t, e]);
494
+ }
495
+ function tt(e) {
496
+ const t = te(se);
497
+ if (!t) throw new Error("useNavigationResult requires an active modal screen");
498
+ const n = u(e), o = u(null);
499
+ I(() => {
500
+ n.current = e;
501
+ }, [e]), I(() => {
502
+ !t.isFocused || !t.resultEvent || o.current !== t.resultEvent.id && (o.current = t.resultEvent.id, n.current(t.resultEvent.data));
503
+ }, [t.isFocused, t.resultEvent]);
504
+ }
505
+ function nt(e = {}) {
506
+ const t = te(se);
507
+ if (!t) throw new Error("[react-modal-navigation] useModalFooter requires an active modal screen");
508
+ const { setFooter: n, routeKey: o } = t, a = u(e);
509
+ a.current = e;
510
+ const h = _(() => (...L) => a.current.done?.(...L), []), g = _(() => (...L) => (a.current.cancel ?? a.current.cancle)?.(...L), []), m = _(() => (...L) => a.current.renderFooter?.(...L), []), b = typeof e.done == "function", M = typeof (e.cancel ?? e.cancle) == "function", c = typeof e.renderFooter == "function", { showFooter: i, showFooterBorder: p, doneDisabled: x, doneText: F, cancelText: $, loadingText: O, footerClassName: w } = e, P = _(() => ({
511
+ showFooter: i,
512
+ showFooterBorder: p,
513
+ doneDisabled: x,
514
+ doneText: F,
515
+ cancelText: $,
516
+ loadingText: O,
517
+ footerClassName: w,
518
+ ...b ? { done: h } : {},
519
+ ...M ? { cancel: g } : {},
520
+ ...c ? { renderFooter: m } : {}
521
+ }), [i, p, x, F, $, O, w, b, M, c, h, g, m]);
522
+ I(() => {
523
+ n(o, P);
524
+ }, [o, n, P]), I(() => () => n(o, null), [o, n]);
525
+ }
526
+ function Ve() {
527
+ const e = te(me);
528
+ if (!e) throw new Error("[react-modal-navigation] useModalLoading requires an active modal screen");
529
+ return e;
530
+ }
531
+ function rt() {
532
+ const e = Ve(), t = Ce(), n = u(!0), o = u(!1), [a, h] = Q(!1), [g, m] = Q(null), b = u(e);
533
+ return b.current = e, I(() => (n.current = !0, () => {
534
+ n.current = !1;
535
+ }), []), { run: y(async (c, i = {}) => {
536
+ if (o.current) return { status: "busy" };
537
+ if (typeof c != "function") throw new TypeError("[react-modal-navigation] run requires a function");
538
+ o.current = !0, n.current && (h(!0), m(null));
539
+ const p = b.current.showLoading(i.loadingText);
540
+ try {
541
+ const x = await c();
542
+ return n.current && await i.onSuccess?.(x), { status: "success", value: x };
543
+ } catch (x) {
544
+ if (n.current) {
545
+ m(x);
546
+ try {
547
+ await i.onError?.(x);
548
+ } catch (F) {
549
+ console.error("[react-modal-navigation] onError failed", F);
550
+ }
551
+ }
552
+ if (i.throwOnError) throw x;
553
+ return { status: "error", error: x };
554
+ } finally {
555
+ p != null && b.current.hideLoading(p), o.current = !1, n.current && h(!1);
556
+ }
557
+ }, []), pending: a, error: g, clearError: () => m(null), isFocused: t };
558
+ }
559
+ export {
560
+ Ke as ModalNavigator,
561
+ Qe as ModalProvider,
562
+ et as useFocusEffect,
563
+ Ce as useIsFocused,
564
+ Xe as useModal,
565
+ nt as useModalFooter,
566
+ Ve as useModalLoading,
567
+ Ze as useModalNavigation,
568
+ rt as useModalTask,
569
+ tt as useNavigationResult
570
+ };
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.1",
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
+ }