react-modal-navigation 1.0.1 → 1.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0
4
+
5
+ ### Features
6
+
7
+ - Modal、Drawer、Sheet 布局,支持 center、left、right、top、bottom。
8
+ - 左右抽屉使用动态视口高度,默认与视口边缘保持 5px 间距。
9
+ - 支持尺寸预设、自定义宽高、移动端全屏和主题配置。
10
+ - 自动注入组件样式,无需手动导入 CSS。
11
+ - 多页面导航、KeepAlive、路由参数和页面间结果传递。
12
+ - `modal.open` / `modal.openAsync` 支持字符串和对象两种调用形式。
13
+ - `modal.confirm` / `modal.dismiss` 明确区分确认与取消。
14
+ - `modal.enqueue` / `modal.enqueueAsync` 支持弹窗队列。
15
+ - `modal.update` 支持运行时调整弹窗配置。
16
+ - `useModalUnsavedChanges` 提供未保存表单保护。
17
+ - 根据弹窗位置匹配进入与退出动画,并支持减少动态效果设置。
18
+ - 提供 TypeScript 类型声明和中文 API 参考文档。
package/README.md CHANGED
@@ -2,20 +2,20 @@
2
2
 
3
3
  React 19 多页面弹窗导航组件库。支持 **Modal / Drawer / Sheet**、页面堆栈、KeepAlive、Promise 返回结果、异步关闭守卫、Footer、Loading、暗黑主题与自动注入样式。
4
4
 
5
- > 包名 `react-modal-navigation`,源码版本 `1.0.0`。此源码包尚未代替你在 npm 上发布;请先运行构建及浏览器回归测试。**默认不需要导入 CSS 文件**。
5
+ > 默认自动注入样式,无需手动导入 CSS 文件。
6
6
 
7
7
  ## 目录
8
8
 
9
9
  1. [安装和快速开始](#安装和快速开始)
10
10
  2. [对象形式打开弹窗](#推荐对象形式打开弹窗)
11
11
  3. [弹窗位置与尺寸](#弹窗位置与尺寸)
12
- 3. [配置优先级与响应式](#配置优先级与响应式)
12
+ 4. [配置优先级与响应式](#配置优先级与响应式)
13
13
  4. [页面导航与传参](#页面导航与传参)
14
14
  5. [Promise 结果与关闭守卫](#promise-结果与关闭守卫)
15
15
  6. [异步提交与 Loading](#异步提交与-loading)
16
16
  7. [主题与样式覆盖](#主题与样式覆盖)
17
17
  8. [事件、可访问性和注意事项](#事件可访问性和注意事项)
18
- 9. [TypeScript 和发布](#typescript-和发布)
18
+ 9. [TypeScript](#typescript)
19
19
 
20
20
  ## 安装和快速开始
21
21
 
@@ -70,6 +70,8 @@ export default function App() {
70
70
  }
71
71
  ```
72
72
 
73
+ **不需要** `import 'react-modal-navigation/style.css'`,Provider 会自动注入组件样式;业务页面可以使用任意 CSS 方案。
74
+
73
75
  ## 推荐:对象形式打开弹窗
74
76
 
75
77
  `modal.open()` 和 `modal.openAsync()` 现在都支持**字符串位置参数**及**对象参数**两种写法,原有代码不需要修改。推荐新项目采用对象形式,避免为了设置位置而传入无意义的 `{}`。
@@ -109,7 +111,7 @@ await modal.open('editUser', {}, { placement: 'bottom', height: '55dvh' });
109
111
  | --- | --- | --- | --- |
110
112
  | `name` | `string` | 是 | registry 中注册的弹窗名称 |
111
113
  | `params` | `unknown` | 否 | 传给初始 Screen 的页面参数,默认 `{}` |
112
- | `options` | `ModalOptions` | 否 | 本次打开覆盖的布局、尺寸、主题和事件配置 |
114
+ | `options` | `ModalOptions` | 否 | 当前弹窗覆盖的布局、尺寸、主题和事件配置 |
113
115
 
114
116
  **兼容规则:** 第一个参数是字符串时继续使用 `open(name, params?, overrides?)`;第一个参数是对象时使用 `open({ name, params?, options? })`。对象形式不需要再传第二、第三个参数。配置优先级仍为 `defaultOptions → modalOptions → options`。`openAsync` 的结果结构不变。
115
117
 
@@ -295,7 +297,7 @@ function SaveScreen() {
295
297
  - 若多次调用 `open()` 或存在异步关闭守卫,建议 `await` 以避免竞态。
296
298
  - 样式注入依赖浏览器 DOM;SSR 时不会直接访问 `document`。严格 CSP 环境可能需要改为静态 CSS。
297
299
 
298
- ## TypeScript 和发布
300
+ ## TypeScript
299
301
 
300
302
  公开类型位于 `types/index.d.ts`,包括 `ModalOptions`、`ModalRegistry`、`ModalNavigation`、`ModalResult` 等。
301
303
 
@@ -305,3 +307,101 @@ const registry: ModalRegistry = {
305
307
  demo: { initialRoute: 'Main', modalOptions: { placement: 'right', size: 'lg' }, screens: { Main: { component: Main } } },
306
308
  };
307
309
  ```
310
+
311
+
312
+ 支持 `modal.open({ name, params, options })` 和 `modal.openAsync({ name, params, options })`,字符串形式继续兼容。
313
+
314
+ ## 简洁的对象调用
315
+
316
+ 对象调用现在还支持将布局配置直接放在顶层,`options` 不再是必需的:
317
+
318
+ ```jsx
319
+ const { modal } = useModal();
320
+
321
+ modal.open({ name: 'editUser', placement: 'bottom', width: '100%', height: '55dvh' });
322
+ modal.open({ name: 'editUser', params: { userId: 1001 }, placement: 'right', width: 520 });
323
+
324
+ // 原有嵌套 options 形式仍然可用
325
+ modal.open({ name: 'editUser', options: { placement: 'center', width: 640 } });
326
+ ```
327
+
328
+ 两种对象写法都适用于 `modal.openAsync()`。若同时提供顶层布局参数和 `options`,**`options` 中的同名配置优先**。字符串形式 `modal.open('editUser', params, options)` 保持兼容。
329
+
330
+ ### 明确区分确认和取消
331
+
332
+ 新增 `modal.confirm(value)` 和 `modal.dismiss(reason)`,使 Promise 结果语义更加清晰,尤其是确认时没有返回值的场景。
333
+
334
+ ```jsx
335
+ function EditUser() {
336
+ const { modal } = useModal();
337
+ return <>
338
+ <button onClick={() => modal.confirm({ saved: true })}>保存并关闭</button>
339
+ <button onClick={() => modal.confirm()}>仅确认,不返回数据</button>
340
+ <button onClick={() => modal.dismiss('cancel')}>取消</button>
341
+ </>;
342
+ }
343
+
344
+ const result = await modal.openAsync({ name: 'editUser', placement: 'right', width: 520 });
345
+ if (result.status === 'confirmed') {
346
+ // result.value 允许为 undefined,仍属于 confirmed
347
+ } else if (result.status === 'dismissed') {
348
+ // result.reason 可能是 cancel、api、escape 等
349
+ }
350
+ ```
351
+
352
+ `confirm` 和 `dismiss` 均遵守 `onBeforeClose` 异步关闭守卫;返回 `Promise<boolean>`,表示是否实际关闭。原有 `modal.close(result)` 保持不变:传入值视为确认,不传值视为取消。
353
+
354
+ ### 建议的业务实践
355
+
356
+ - **编辑表单**:用 `modal.openAsync()` 等待提交结果,用 `onBeforeClose` 检查未保存数据。
357
+ - **抽屉式详情**:用 `placement: 'right'`,高度自动适配视口,四周保留默认 5px 间距。
358
+ - **移动端筛选**:用 `placement: 'bottom'` 和 `height: '55dvh'`。
359
+ - **防止重复提交**:在弹窗页面中使用 `useModalTask()`,并在成功后 `modal.confirm(result)`。
360
+ - **导航返回值**:多页面流程中用 `navigation.goBack(result)`,最外层完成时用 `modal.confirm(result)`。
361
+
362
+
363
+
364
+ ## 表单未保存保护
365
+
366
+ 在任意弹窗页面调用 `useModalUnsavedChanges(isDirty)`。关闭、取消、ESC、遮罩关闭和替换弹窗时都会检查;用户拒绝放弃修改则保留当前弹窗。KeepAlive 页面即使暂时隐藏,保护仍然生效。
367
+
368
+ ```jsx
369
+ import { useState } from 'react';
370
+ import { useModal, useModalUnsavedChanges } from 'react-modal-navigation';
371
+
372
+ function EditUser() {
373
+ const { modal } = useModal();
374
+ const [name, setName] = useState('');
375
+ const [savedName, setSavedName] = useState('');
376
+ useModalUnsavedChanges(name !== savedName, { message: '修改尚未保存,确定退出?' });
377
+ async function save() {
378
+ await saveUser({ name });
379
+ setSavedName(name);
380
+ // 保存成功后 dirty 变为 false,再关闭;异步状态提交可能需要等待一次渲染
381
+ }
382
+ return <><input value={name} onChange={e => setName(e.target.value)} /><button onClick={save}>保存</button><button onClick={() => modal.dismiss('cancel')}>取消</button></>;
383
+ }
384
+ ```
385
+
386
+ 全局自定义确认对话框(支持异步):
387
+
388
+ ```jsx
389
+ <ModalProvider registry={registry} confirmDiscard={async ({ name, reason }) => {
390
+ return window.confirm(`弹窗 ${name} 有未保存的内容,确定放弃?`);
391
+ }}>
392
+ <App />
393
+ </ModalProvider>
394
+ ```
395
+
396
+ 也可以单页面传入 `onBeforeDiscard`,优先级高于全局 `confirmDiscard`。默认调用 `window.confirm`;SSR/非浏览器环境默认拒绝丢弃。**请注意**:本功能阻止关闭和弹窗替换,但不阻止弹窗内部 `navigation.navigate/goBack/reset`,也不自动保护浏览器刷新。
397
+
398
+ ## 动画(新增)
399
+
400
+ 默认 220ms,随 `placement` 自动切换:居中缩放淡入淡出、左右抽屉横向滑动、上下 Sheet 纵向滑动;遮罩渐变。
401
+
402
+ ```jsx
403
+ modal.open({ name: 'editUser', placement: 'right', width: 520, animation: true, animationDuration: 260 });
404
+ modal.open({ name: 'quickInfo', placement: 'center', animation: false });
405
+ ```
406
+
407
+ `animationDuration` 单位毫秒;系统启用 `prefers-reduced-motion: reduce` 时自动关闭动画。退出动画结束后才触发 `onClose` 和队列中的下一个弹窗。
package/dist/index.cjs CHANGED
@@ -1 +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;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),t=require("react"),Ne=require("react-dom"),Re=t.createContext(null),be=t.createContext(null),de=t.createContext(null),ye=t.createContext(null),Ee=t.createContext(null);let Le=0;const ge=(e,n)=>({key:`modal-route-${++Le}`,name:e,params:n??{}}),Me=(e,n)=>[ge(e,n)];function Te(e,n){switch(n.type){case"RESET":return Me(n.name,n.params);case"NAVIGATE":{const o=e.findIndex(c=>c.name===n.name);return o<0?[...e,ge(n.name,n.params)]:e.slice(0,o+1).map((c,l)=>l===o?{...c,params:n.params??{}}:c)}case"SET_PARAMS":return e.map((o,c)=>c===e.length-1?{...o,params:{...o.params??{},...n.params??{}}}:o);case"BACK":return e.length>1?e.slice(0,-1):e;case"REPLACE":return e.length?[...e.slice(0,-1),ge(n.name,n.params)]:e;default:return e}}const we=()=>{if(typeof document>"u")return"light";const e=document.documentElement,n=document.body;return e.classList.contains("dark")||n.classList.contains("dark")||e.dataset.theme==="dark"||n.dataset.theme==="dark"?"dark":e.classList.contains("light")||n.classList.contains("light")||e.dataset.theme==="light"||n.dataset.theme==="light"?"light":window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"};let ie=0;const Z=[];let pe=null;function Be(){if(ie++,ie===1){const n=document.documentElement,o=document.body,c={html:n.style.overflow,body:o.style.overflow,padding:o.style.paddingRight,width:o.style.getPropertyValue("--modal-scrollbar-width")},l=Math.max(0,window.innerWidth-n.clientWidth),h=parseFloat(getComputedStyle(o).paddingRight)||0;l&&(o.style.paddingRight=`${h+l}px`),o.style.setProperty("--modal-scrollbar-width",`${l}px`),n.style.overflow="hidden",o.style.overflow="hidden",pe=()=>{n.style.overflow=c.html,o.style.overflow=c.body,o.style.paddingRight=c.padding,c.width?o.style.setProperty("--modal-scrollbar-width",c.width):o.style.removeProperty("--modal-scrollbar-width")}}let e=!1;return()=>{e||(e=!0,ie=Math.max(0,ie-1),ie||(pe?.(),pe=null))}}const Pe='a[href],button:not([disabled]),input:not([disabled]),textarea:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])',Fe=e=>!e.closest('[inert], [hidden], [aria-hidden="true"]')&&e.getClientRects().length>0&&getComputedStyle(e).visibility!=="hidden"&&getComputedStyle(e).display!=="none";function qe({dialogRef:e,options:n,requestClose:o,children:c,exiting:l=!1}){const h=t.useRef(null),y=t.useRef(null),v=t.useRef(o);v.current=o;const f=t.useRef(n.closeOnEsc);f.current=n.closeOnEsc;const[S,k]=t.useState(we),g=n.theme==="light"||n.theme==="dark"?n.theme:S;t.useEffect(()=>{if(n.theme==="light"||n.theme==="dark")return;const T=()=>k(we()),G=new MutationObserver(T);for(const N of[document.documentElement,document.body])G.observe(N,{attributes:!0,attributeFilter:["class","data-theme"]});const w=window.matchMedia?.("(prefers-color-scheme: dark)");return w?.addEventListener?.("change",T),T(),()=>{G.disconnect(),w?.removeEventListener?.("change",T)}},[n.theme]),t.useEffect(()=>{y.current=document.activeElement;const T=Be(),G=h.current;Z.push(G),e.current?.focus({preventScroll:!0});const w=E=>{const x=e.current;if(!x||Z.at(-1)!==G)return;if(E.key==="Escape"&&f.current!==!1){E.preventDefault(),v.current("escape");return}if(E.key!=="Tab")return;const L=[...x.querySelectorAll(Pe)].filter(Fe);if(!L.length){E.preventDefault(),x.focus();return}const I=L[0],M=L.at(-1);x.contains(document.activeElement)?E.shiftKey&&(document.activeElement===I||document.activeElement===x)?(E.preventDefault(),M.focus()):!E.shiftKey&&(document.activeElement===M||document.activeElement===x)&&(E.preventDefault(),I.focus()):(E.preventDefault(),(E.shiftKey?M:I).focus())},N=E=>{Z.at(-1)===G&&e.current&&!e.current.contains(E.target)&&e.current.focus({preventScroll:!0})};return document.addEventListener("keydown",w),document.addEventListener("focusin",N),()=>{document.removeEventListener("keydown",w),document.removeEventListener("focusin",N);const E=Z.at(-1)===G,x=Z.indexOf(G);if(x!==-1&&Z.splice(x,1),T(),E){const L=y.current;L?.isConnected&&!L.closest("[inert], [hidden]")?L.focus?.({preventScroll:!0}):Z.at(-1)?.querySelector("[role=dialog]")?.focus?.({preventScroll:!0})}}},[e]);const m=n.backgroundColor??n.backgroudColor,p=typeof m=="string"?m:m?.[g],b=typeof p=="string"&&/^(#|rgb\(|rgba\(|hsl\(|hsla\(|oklch\(|color\(|var\()/.test(p.trim())?p:null,q={sm:400,md:560,lg:720,xl:960,full:"100%"},B=["center","left","right","top","bottom"].includes(n.placement)?n.placement:"right",P=T=>typeof T=="number"?`${T}px`:T,F=P(n.width??q[n.size]??460),C=P(n.height),A=P(n.maxHeight),R=P(n.maxWidth),O=Number(n.viewportGap??5),$=Number.isFinite(O)?Math.max(0,O):5,H=typeof n.borderRadius=="number"?`${n.borderRadius}px`:n.borderRadius??"12px";return Ne.createPortal(d.jsx("div",{ref:h,className:`pmn-overlay ${l?"pmn-exiting":"pmn-entering"} ${n.animation===!1?"pmn-no-animation":""} pmn-place-${B} ${n.mobileFullscreen?"pmn-mobile-fullscreen":""}`,style:{padding:$,"--pmn-animation-duration":`${Math.min(1e3,Math.max(0,Number(n.animationDuration??220)||0))}ms`},onMouseDown:T=>{T.target===T.currentTarget&&n.closeOnOverlay===!0&&v.current("overlay")},children:d.jsx("section",{ref:e,tabIndex:-1,role:"dialog","aria-modal":"true","aria-label":n.ariaLabel??"Dialog","data-modal-theme":g,className:`pmn-dialog ${g==="dark"?"dark":""} ${!b&&p?p:""} ${n.className??""}`,style:{"--pmn-width":F,"--pmn-gap":`${$}px`,...C!==void 0?{"--pmn-height":C}:{},...A!==void 0?{"--pmn-max-height":A}:{},...R!==void 0?{"--pmn-max-width":R}:{},borderRadius:H,...b?{backgroundColor:b}:{}},children:c})}),document.body)}function ke({back:e}){return d.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e?d.jsx("path",{d:"m15 18-6-6 6-6"}):d.jsx("path",{d:"M18 6 6 18M6 6l12 12"})})}function De({options:e,screen:n,route:o,navigation:c,requestClose:l,translate:h}){if(e.showHeader===!1)return null;const y=h??(m=>m),v=n.showTitle??e.showTitle??!0,f=typeof n.title=="function"?n.title({t:y,route:o,navigation:c}):n.title??o.name,S={route:o,navigation:c,close:l,canGoBack:c.canGoBack,title:f,t:y},k=n.renderHeader??e.renderHeader;if(k)return k(S);const g=n.renderHeaderRight??e.renderHeaderRight;return d.jsxs("header",{className:`pmn-header ${n.showHeaderBorder??e.showHeaderBorder?"pmn-border-bottom":""} ${e.headerClassName??""}`,children:[e.showBackButton!==!1&&c.canGoBack&&d.jsx("button",{type:"button",className:"pmn-icon-button","aria-label":y("modal.back"),onClick:()=>c.goBack(),children:d.jsx(ke,{back:!0})}),v?d.jsx("h2",{children:f}):d.jsx("div",{className:"pmn-header-spacer"}),g?.(S),e.showCloseButton!==!1&&d.jsx("button",{type:"button",className:"pmn-icon-button","aria-label":y("modal.close"),onClick:()=>l("header"),children:d.jsx(ke,{})})]})}function Ae({screen:e,options:n,override:o,route:c,navigation:l,requestClose:h,translate:y,onError:v}){const[f,S]=t.useState(!1),k=y??(R=>R),g={...n,...e,...o},{showFooter:m,renderFooter:p,done:b,cancel:q,cancle:B}=g,P=q??B,F={route:c,navigation:l,close:h,t:k};if(m===!1)return null;const C=`pmn-footer ${g.showFooterBorder?"pmn-border-top":""} ${g.footerClassName??""}`;if(typeof p=="function")return d.jsx("footer",{className:C,children:p({...F,pending:f})});if(typeof b!="function"&&typeof P!="function")return null;const A=async R=>{if(!(f||typeof R!="function")){S(!0);try{await R(F)}catch(O){v?.(O,{phase:"footer",route:c})}finally{S(!1)}}};return d.jsxs("footer",{className:C,children:[typeof P=="function"&&d.jsx("button",{type:"button",disabled:f,onClick:()=>A(P),className:"pmn-button pmn-button-secondary",children:g.cancelText??k("modal.cancel")}),typeof b=="function"&&d.jsx("button",{type:"button",disabled:f||g.doneDisabled===!0,onClick:()=>A(b),className:"pmn-button pmn-button-primary",children:f?g.loadingText??k("modal.processing"):g.doneText??k("modal.done")})]})}function Oe({loading:e,translate:n}){if(!e.visible)return null;const c=(n??(h=>h))("modal.loading"),l=e.text??(c==="modal.loading"?"加载中...":c);return d.jsx("div",{className:"pmn-loading-overlay",role:"status","aria-live":"polite","aria-busy":"true",children:d.jsxs("div",{className:"pmn-loading-card",children:[d.jsx("span",{className:"pmn-spinner","aria-hidden":"true"}),d.jsx("span",{children:l})]})})}class $e extends t.Component{state={error:null};static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,o){this.props.onError?.(n,{phase:"render",route:this.props.route,componentStack:o.componentStack})}componentDidUpdate(n){n.route?.key!==this.props.route?.key&&this.state.error&&this.setState({error:null})}render(){return this.state.error?d.jsxs("div",{role:"alert",className:"pmn-error-screen",children:[d.jsx("strong",{children:"页面加载失败"}),d.jsx("p",{children:this.state.error.message}),d.jsx("button",{type:"button",className:"pmn-button pmn-button-secondary",onClick:()=>this.setState({error:null}),children:"重试"})]}):this.props.children}}function Ie({route:e,screen:n,navigation:o,focused:c,resultEvent:l,setFooter:h,loadingApi:y,bodyClassName:v,notifyError:f,registerDirtyGuard:S}){const k=n.component,g=t.useMemo(()=>({isFocused:c,resultEvent:l,routeKey:e.key,setFooter:h}),[c,l,e.key,h]),m=t.useMemo(()=>({isLoading:c&&y.isLoading,setLoading:(p,b)=>y.setScreenLoading(e.key,p,b),showLoading:p=>y.begin(e.key,p),hideLoading:p=>y.end(e.key,p)}),[c,y,e.key]);return d.jsx(Ee.Provider,{value:{routeKey:e.key,registerDirtyGuard:S},children:d.jsx(de.Provider,{value:g,children:d.jsx(ye.Provider,{value:m,children:d.jsx("div",{hidden:!c,inert:!c,"data-modal-route-key":e.key,tabIndex:-1,className:`pmn-body ${v??""}`,children:d.jsx($e,{route:e,onError:f,children:d.jsx(k,{route:e,navigation:o})})})})})})}function je({config:e,params:n,options:o,translate:c,onRequestClose:l,onOpened:h,registerLoading:y,notifyError:v,error:f,clearError:S,registerDirtyGuard:k,exiting:g=!1}){const[m,p]=t.useReducer(Te,null,()=>Me(e.initialRoute,n)),[b,q]=t.useState({}),[B,P]=t.useState({}),[,F]=t.useState(0),C=t.useRef(new Map),A=t.useRef(0),R=t.useRef(new Map),O=t.useRef(null),$=t.useRef(null),H=t.useRef(!1),T=t.useRef(!1),G=t.useRef(0),w=m.at(-1),N=w.key,E=t.useRef(N);E.current=N;const x=e.screens,L=t.useCallback(()=>F(r=>r+1),[]),I=t.useCallback((r,a)=>{if(r!=="global"&&E.current!==r)return null;const u=++A.current;return C.current.set(u,{owner:r,text:a}),L(),u},[L]),M=t.useCallback((r,a)=>{if(a!=null)C.current.get(a)?.owner===r&&C.current.delete(a);else for(const[u,j]of C.current)j.owner===r&&C.current.delete(u);L()},[L]),z=t.useCallback((r,a)=>{r?(M("global"),I("global",a)):M("global")},[I,M]),K=t.useCallback((r,a,u)=>{a?(M(r),I(r,u)):M(r)},[I,M]),_=[...C.current.values()],Y={visible:_.length>0,text:_.at(-1)?.text??null,count:_.length},U=t.useRef(Y);U.current=Y;const Q=t.useMemo(()=>({isLoading:Y.visible,setLoading:z,setScreenLoading:K,begin:I,end:M}),[Y.visible,z,K,I,M]),te=t.useRef(y);te.current=y,t.useEffect(()=>(te.current?.({setLoading:z}),()=>te.current?.(null)),[z]);const le=t.useCallback((r,a)=>P(u=>{if(a===null){if(!(r in u))return u;const j={...u};return delete j[r],j}return u[r]===a?u:{...u,[r]:a}}),[]),J=t.useCallback(()=>{const r=document.activeElement;if(!(r instanceof HTMLElement)||!O.current?.contains(r))return;const a=r.closest("[data-modal-route-key]");a&&R.current.set(a.dataset.modalRouteKey,r),O.current.focus({preventScroll:!0})},[]),ne=t.useCallback(r=>{if(!Object.prototype.hasOwnProperty.call(x,r))throw new Error(`[react-modal-navigation] Unknown modal screen: ${r}`)},[x]),V=t.useCallback((r,a)=>{try{Promise.resolve(o[r]?.(a)).catch(u=>v(u,{phase:r}))}catch(u){v(u,{phase:r})}},[o,v]),W=t.useCallback((r,a,u)=>{ne(a),J(),p({type:r,name:a,params:u})},[ne,J]),re=t.useCallback((r,a)=>W("NAVIGATE",r,a),[W]),oe=t.useCallback((r,a)=>W("REPLACE",r,a),[W]),ae=t.useCallback((r,a)=>{q({}),W("RESET",r,a)},[W]),se=t.useCallback(r=>{if(!r||typeof r!="object"||Array.isArray(r))throw new TypeError("[react-modal-navigation] setParams expects an object");p({type:"SET_PARAMS",params:r})},[]),ce=t.useCallback(r=>{if(m.length<=1||H.current)return!1;if(H.current=!0,r!==void 0){const a=m.at(-2);q(u=>({...u,[a.key]:{id:++G.current,data:r}}))}return J(),p({type:"BACK"}),!0},[m,J]),X=t.useCallback((r,a)=>U.current.visible&&o.lockCloseWhileLoading!==!1?Promise.resolve(!1):l(r,a,{route:w,stack:m}),[o.lockCloseWhileLoading,l,w,m]),s=t.useCallback(r=>X("api",r),[X]),i=t.useMemo(()=>({navigate:re,replace:oe,reset:ae,setParams:se,goBack:ce,close:s,setLoading:z,canGoBack:m.length>1,stack:m,currentRoute:w}),[re,oe,ae,se,ce,s,z,m,w]);return t.useLayoutEffect(()=>{H.current=!1;const r=[...O.current?.querySelectorAll("[data-modal-route-key]")??[]].find(j=>j.dataset.modalRouteKey===N);if(!r)return;const a=R.current.get(N);(a?.isConnected&&r.contains(a)&&!a.matches(":disabled")&&!a.closest("[inert], [hidden]")?a:r).focus({preventScroll:!0})},[N]),t.useEffect(()=>{let r=!1;for(const[u,j]of C.current)j.owner!=="global"&&j.owner!==N&&(C.current.delete(u),r=!0);r&&L();const a=new Set(m.map(u=>u.key));for(const u of R.current.keys())a.has(u)||R.current.delete(u)},[N,m,L]),t.useEffect(()=>{if($.current?.key!==N){if($.current){const r={from:$.current,to:w,stack:m};V("onBlur",{route:$.current,...r}),V("onNavigate",r),V("onRouteChange",r)}V("onFocus",{route:w,stack:m}),$.current=w}},[w,N,m,V]),t.useEffect(()=>()=>{C.current.clear(),R.current.clear()},[]),t.useEffect(()=>{T.current||(T.current=!0,h?.({route:w,stack:m}))},[]),d.jsx(be.Provider,{value:i,children:d.jsx(ye.Provider,{value:Q,children:d.jsxs(qe,{dialogRef:O,options:o,requestClose:X,exiting:g,children:[d.jsx(De,{options:o,screen:x[w.name],route:w,navigation:i,requestClose:X,translate:c}),d.jsx("main",{className:"pmn-main",children:m.map(r=>d.jsx(Ie,{route:r,screen:x[r.name],navigation:i,focused:r.key===N,resultEvent:b[r.key]??null,bodyClassName:o.bodyClassName,setFooter:le,loadingApi:Q,notifyError:v,registerDirtyGuard:k},r.key))}),d.jsx(Ae,{screen:x[w.name],options:o,override:B[N],route:w,navigation:i,requestClose:X,translate:c,onError:v},N),d.jsx(Oe,{loading:Y,translate:c}),f&&d.jsxs("div",{className:"pmn-error",role:"alert",children:[d.jsx("span",{children:f.message||String(f)}),d.jsx("button",{type:"button",onClick:S,"aria-label":"Dismiss error",children:"×"})]})]})})})}const He=".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}}@keyframes pmn-fade-in{0%{opacity:0}to{opacity:1}}@keyframes pmn-fade-out{0%{opacity:1}to{opacity:0}}@keyframes pmn-scale-in{0%{opacity:0;transform:translateY(10px) scale(.97)}to{opacity:1;transform:none}}@keyframes pmn-scale-out{0%{opacity:1;transform:none}to{opacity:0;transform:translateY(10px) scale(.97)}}@keyframes pmn-right-in{0%{transform:translate(105%)}to{transform:none}}@keyframes pmn-right-out{0%{transform:none}to{transform:translate(105%)}}@keyframes pmn-left-in{0%{transform:translate(-105%)}to{transform:none}}@keyframes pmn-left-out{0%{transform:none}to{transform:translate(-105%)}}@keyframes pmn-top-in{0%{transform:translateY(-105%)}to{transform:none}}@keyframes pmn-top-out{0%{transform:none}to{transform:translateY(-105%)}}@keyframes pmn-bottom-in{0%{transform:translateY(105%)}to{transform:none}}@keyframes pmn-bottom-out{0%{transform:none}to{transform:translateY(105%)}}.pmn-entering{animation:pmn-fade-in var(--pmn-animation-duration) ease-out both}.pmn-exiting{animation:pmn-fade-out var(--pmn-animation-duration) ease-in both;pointer-events:none}.pmn-entering .pmn-dialog{animation:pmn-scale-in var(--pmn-animation-duration) cubic-bezier(.2,.8,.2,1) both}.pmn-exiting .pmn-dialog{animation:pmn-scale-out var(--pmn-animation-duration) ease-in both}.pmn-entering.pmn-place-right .pmn-dialog{animation-name:pmn-right-in}.pmn-exiting.pmn-place-right .pmn-dialog{animation-name:pmn-right-out}.pmn-entering.pmn-place-left .pmn-dialog{animation-name:pmn-left-in}.pmn-exiting.pmn-place-left .pmn-dialog{animation-name:pmn-left-out}.pmn-entering.pmn-place-top .pmn-dialog{animation-name:pmn-top-in}.pmn-exiting.pmn-place-top .pmn-dialog{animation-name:pmn-top-out}.pmn-entering.pmn-place-bottom .pmn-dialog{animation-name:pmn-bottom-in}.pmn-exiting.pmn-place-bottom .pmn-dialog{animation-name:pmn-bottom-out}.pmn-no-animation,.pmn-no-animation .pmn-dialog{animation:none!important}@media(prefers-reduced-motion:reduce){.pmn-entering,.pmn-exiting,.pmn-entering .pmn-dialog,.pmn-exiting .pmn-dialog{animation:none!important}}",Ce="react-modal-navigation-styles",he=new WeakMap;function Ge(){t.useInsertionEffect(()=>{if(typeof document>"u")return;const e=document;let n=he.get(e);if(!n){let o=e.getElementById(Ce);const c=!o;o||(o=e.createElement("style"),o.id=Ce,o.setAttribute("data-react-modal-navigation",""),o.textContent=He,e.head.appendChild(o)),n={element:o,owned:c,count:0},he.set(e,n)}return n.count+=1,()=>{n.count-=1,n.count===0&&(n.owned&&n.element.remove(),he.delete(e))}},[])}function ue(e,n,o){if(typeof e=="string"){if(!e.trim())throw new TypeError("[react-modal-navigation] modal name must not be empty");return{name:e,params:n??{},options:o??{}}}if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("[react-modal-navigation] open expects a modal name or a configuration object");const{name:c,params:l={},options:h={},...y}=e;if(typeof c!="string"||!c.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:c,params:l,options:{...y,...h}}}const ze={placement:"right",showHeader:!0,showBackButton:!0,showCloseButton:!0,viewportGap:5,borderRadius:12,closeOnOverlay:!1,closeOnEsc:!0},Ke=e=>({"modal.loading":"加载中...","modal.processing":"处理中...","modal.back":"返回","modal.close":"关闭","modal.cancel":"取消","modal.done":"完成"})[e]??e;function Ue({registry:e,children:n,defaultOptions:o={},backgroundColor:c,theme:l,translate:h=Ke,onError:y,confirmDiscard:v}){Ge();const[f,S]=t.useState(null),[k,g]=t.useState(null),[m,p]=t.useState(0),b=t.useRef(null),q=t.useRef(new Map),B=t.useRef([]),P=t.useRef(null),F=t.useRef(null),C=t.useRef(0),A=t.useRef(null),R=t.useRef(!1),O=t.useRef(0),$=t.useRef(null),H=t.useRef(new Map),[T,G]=t.useState(!1),w=t.useRef(v);w.current=v;const N=t.useCallback((s,i)=>(H.current.set(s,i),()=>{H.current.get(s)===i&&H.current.delete(s)}),[]),E=t.useCallback(async s=>{for(const i of H.current.values()){if(!i.dirty)continue;if((i.onBeforeDiscard?await i.onBeforeDiscard(s):w.current?await w.current(s):typeof window<"u"&&typeof window.confirm=="function"?window.confirm(i.message||"有未保存的修改,确定放弃吗?"):!1)===!1)return!1}return!0},[]),x=t.useRef(!0),L=t.useRef(null),I=t.useRef(y);I.current=y;const M=t.useCallback((s,i)=>{x.current&&g(s);try{I.current?I.current(s,i):console.error("[react-modal-navigation]",s)}catch(r){console.error("[react-modal-navigation] onError failed",r)}},[]),z=t.useCallback((s,i)=>{const r=q.current.get(s);q.current.delete(s),r?.(i)},[]),K=t.useCallback(s=>({...ze,...o,...l!==void 0?{theme:l}:{},...c!==void 0?{backgroundColor:c}:{},...s.config.modalOptions,...s.overrides}),[o,l,c]),_=f?K(f):null,Y=t.useRef(null);Y.current=_,L.current=_;const U=t.useCallback(async(s="api",i,r={})=>{const a=b.current;if(!a||A.current||R.current)return!1;A.current=a.id,R.current=!0;const u=L.current??K(a),j={...r,reason:s,result:i,name:a.name};try{if(!await E(j)||await u.onBeforeClose?.(j)===!1||b.current?.id!==a.id||!x.current||(G(!0),await new Promise(D=>{const ee=u.animation===!1||typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?0:Math.max(0,Number(u.animationDuration??220)||0);setTimeout(D,Math.min(ee,1e3))}),!x.current||b.current?.id!==a.id))return!1;b.current=null,$.current=null,S(null),G(!1),H.current.clear(),z(a.id,r.confirmed||i!==void 0?{status:"confirmed",value:i,reason:s}:{status:"dismissed",reason:s});try{await u.onClose?.(j)}catch(D){M(D,{phase:"onClose",name:a.name})}return!0}catch(D){return M(D,{phase:"onBeforeClose",name:a.name}),!1}finally{A.current===a.id&&(A.current=null),R.current=!1,!b.current&&x.current&&queueMicrotask(()=>F.current?.())}},[K,M,z,E]),Q=t.useCallback(async(s,i={},r={},a)=>{const u=e?.[s];if(!u)throw new Error(`[react-modal-navigation] Unknown modal: ${s}`);if(!u.screens?.[u.initialRoute])throw new Error(`[react-modal-navigation] Missing initial screen '${u.initialRoute}' in '${s}'`);if(!x.current||R.current||A.current)return null;R.current=!0;const j=O.current;try{const D=b.current;if(D){const ve=L.current??K(D),me={reason:"replace",name:D.name,nextName:s};try{if(!await E(me)||await ve.onBeforeClose?.(me)===!1)return null}catch(fe){return M(fe,{phase:"onBeforeClose",name:D.name}),null}if(!x.current||j!==O.current||b.current?.id!==D.id)return null;b.current=null,$.current=null,S(null),H.current.clear(),z(D.id,{status:"replaced",reason:"replace"});try{await ve.onClose?.(me)}catch(fe){M(fe,{phase:"onClose",name:D.name})}if(!x.current||j!==O.current)return null}const ee={id:++C.current,name:s,params:i,config:u,overrides:r};return b.current=ee,$.current=null,a&&q.current.set(ee.id,a),g(null),S(ee),ee.id}finally{R.current=!1}},[e,K,M,z,E]);P.current=Q;const te=t.useCallback(async()=>{if(!x.current||b.current||R.current||A.current)return;const s=B.current.shift();if(s){p(B.current.length);try{const i=await P.current(s.args.name,s.args.params,s.args.options,s.resolveResult);i===null?(s.resolveResult?.({status:"dismissed",reason:"blocked"}),s.resolveId?.(null),queueMicrotask(()=>F.current?.())):s.resolveId?.(i)}catch(i){s.reject?.(i),queueMicrotask(()=>F.current?.())}}},[]);F.current=te;const le=t.useCallback((s,i,r)=>{const a=ue(s,i,r);return e?.[a.name]?new Promise((u,j)=>{B.current.push({args:a,resolveId:u,reject:j}),p(B.current.length),queueMicrotask(()=>F.current?.())}):Promise.reject(new Error(`[react-modal-navigation] Unknown modal: ${a.name}`))},[e]),J=t.useCallback((s,i,r)=>{const a=ue(s,i,r);return e?.[a.name]?new Promise((u,j)=>{B.current.push({args:a,resolveResult:u,reject:j}),p(B.current.length),queueMicrotask(()=>F.current?.())}):Promise.reject(new Error(`[react-modal-navigation] Unknown modal: ${a.name}`))},[e]),ne=t.useCallback(s=>{if(!s||typeof s!="object"||Array.isArray(s))throw new TypeError("[react-modal-navigation] update expects an options object");const i=b.current;if(!i||R.current)return!1;const r={...i,overrides:{...i.overrides,...s}};return b.current=r,S(r),L.current=K(r),!0},[K]),V=t.useCallback((s="queue-cleared")=>{const i=B.current.splice(0);p(0);for(const r of i)r.resolveId?.(null),r.resolveResult?.({status:"dismissed",reason:s});return i.length},[]),W=t.useCallback((s,i,r)=>{const a=ue(s,i,r);return Q(a.name,a.params,a.options)},[Q]),re=t.useCallback((s,i,r)=>{const a=ue(s,i,r);return new Promise((u,j)=>{Q(a.name,a.params,a.options,u).then(D=>{D===null&&u({status:"dismissed",reason:"blocked"})},j)})},[Q]),oe=t.useCallback(s=>U("api",s),[U]),ae=t.useCallback((s="api")=>U(s),[U]),se=t.useCallback(s=>U("confirm",s,{confirmed:!0}),[U]),ce=t.useCallback((s,i)=>$.current?.setLoading(s,i),[]),X=t.useMemo(()=>({open:W,openAsync:re,enqueue:le,enqueueAsync:J,update:ne,clearQueue:V,close:oe,dismiss:ae,confirm:se,setLoading:ce,queueSize:m,isOpen:!!f,activeName:f?.name??null,error:k,clearError:()=>g(null)}),[W,re,le,J,ne,V,oe,ae,se,ce,f,k,m]);return t.useEffect(()=>(x.current=!0,()=>{x.current=!1,O.current+=1,b.current=null;for(const i of q.current.values())i({status:"dismissed",reason:"unmount"});q.current.clear(),H.current.clear();const s=B.current.splice(0);for(const i of s)i.resolveId?.(null),i.resolveResult?.({status:"dismissed",reason:"unmount"})}),[]),d.jsxs(Re.Provider,{value:X,children:[n,f&&d.jsx(je,{config:f.config,params:f.params,options:_,translate:h,notifyError:M,error:k,clearError:()=>g(null),registerLoading:s=>{$.current=s},registerDirtyGuard:N,exiting:T,onRequestClose:U,onOpened:s=>{try{const i=Y.current?.onOpen?.(s);Promise.resolve(i).catch(r=>M(r,{phase:"onOpen"}))}catch(i){M(i,{phase:"onOpen"})}}},f.id)]})}function We(){const e=t.useContext(Re),n=t.useContext(be);if(!e)throw new Error("[react-modal-navigation] useModal requires <ModalProvider>");return t.useMemo(()=>{const o=()=>{if(!n)throw new Error("[react-modal-navigation] navigation requires an active modal screen; use modal.open() outside a modal");return n};return{...e,modal:e,navigation:{navigate:(...l)=>o().navigate(...l),replace:(...l)=>o().replace(...l),reset:(...l)=>o().reset(...l),setParams:(...l)=>o().setParams(...l),goBack:(...l)=>o().goBack(...l),close:(...l)=>o().close(...l),get canGoBack(){return n?.canGoBack??!1},get stack(){return n?.stack??[]},get currentRoute(){return n?.currentRoute??null}}}},[e,n])}function Ye(){const e=t.useContext(be);if(!e)throw new Error("useModalNavigation requires an active modal screen");return e}function xe(){const e=t.useContext(de);if(!e)throw new Error("useIsFocused must be called inside a modal screen");return e.isFocused}function Qe(e){const n=xe();t.useEffect(()=>{if(n)return e()},[n,e])}function Ve(e){const n=t.useContext(de);if(!n)throw new Error("useNavigationResult requires an active modal screen");const o=t.useRef(e),c=t.useRef(null);t.useEffect(()=>{o.current=e},[e]),t.useEffect(()=>{!n.isFocused||!n.resultEvent||c.current!==n.resultEvent.id&&(c.current=n.resultEvent.id,o.current(n.resultEvent.data))},[n.isFocused,n.resultEvent])}function _e(e={}){const n=t.useContext(de);if(!n)throw new Error("[react-modal-navigation] useModalFooter requires an active modal screen");const{setFooter:o,routeKey:c}=n,l=t.useRef(e);l.current=e;const h=t.useMemo(()=>(...C)=>l.current.done?.(...C),[]),y=t.useMemo(()=>(...C)=>(l.current.cancel??l.current.cancle)?.(...C),[]),v=t.useMemo(()=>(...C)=>l.current.renderFooter?.(...C),[]),f=typeof e.done=="function",S=typeof(e.cancel??e.cancle)=="function",k=typeof e.renderFooter=="function",{showFooter:g,showFooterBorder:m,doneDisabled:p,doneText:b,cancelText:q,loadingText:B,footerClassName:P}=e,F=t.useMemo(()=>({showFooter:g,showFooterBorder:m,doneDisabled:p,doneText:b,cancelText:q,loadingText:B,footerClassName:P,...f?{done:h}:{},...S?{cancel:y}:{},...k?{renderFooter:v}:{}}),[g,m,p,b,q,B,P,f,S,k,h,y,v]);t.useEffect(()=>{o(c,F)},[c,o,F]),t.useEffect(()=>()=>o(c,null),[c,o])}function Se(){const e=t.useContext(ye);if(!e)throw new Error("[react-modal-navigation] useModalLoading requires an active modal screen");return e}function Je(){const e=Se(),n=xe(),o=t.useRef(!0),c=t.useRef(!1),[l,h]=t.useState(!1),[y,v]=t.useState(null),f=t.useRef(e);return f.current=e,t.useEffect(()=>(o.current=!0,()=>{o.current=!1}),[]),{run:t.useCallback(async(k,g={})=>{if(c.current)return{status:"busy"};if(typeof k!="function")throw new TypeError("[react-modal-navigation] run requires a function");c.current=!0,o.current&&(h(!0),v(null));const m=f.current.showLoading(g.loadingText);try{const p=await k();return o.current&&await g.onSuccess?.(p),{status:"success",value:p}}catch(p){if(o.current){v(p);try{await g.onError?.(p)}catch(b){console.error("[react-modal-navigation] onError failed",b)}}if(g.throwOnError)throw p;return{status:"error",error:p}}finally{m!=null&&f.current.hideLoading(m),c.current=!1,o.current&&h(!1)}},[]),pending:l,error:y,clearError:()=>v(null),isFocused:n}}function Xe(e,n={}){const o=t.useContext(Ee);if(!o)throw new Error("[react-modal-navigation] useModalUnsavedChanges must be used inside a modal screen");const c=t.useRef({dirty:e,...n});c.current={dirty:e,...n};const{routeKey:l,registerDirtyGuard:h}=o;t.useEffect(()=>h(l,{get dirty(){return!!c.current.dirty},get message(){return c.current.message},get onBeforeDiscard(){return c.current.onBeforeDiscard}}),[l,h])}exports.ModalNavigator=je;exports.ModalProvider=Ue;exports.useFocusEffect=Qe;exports.useIsFocused=xe;exports.useModal=We;exports.useModalFooter=_e;exports.useModalLoading=Se;exports.useModalNavigation=Ye;exports.useModalTask=Je;exports.useModalUnsavedChanges=Xe;exports.useNavigationResult=Ve;
package/dist/index.d.ts CHANGED
@@ -29,6 +29,10 @@ export interface ModalOptions {
29
29
  maxHeight?: number | string;
30
30
  /** Display as fullscreen on viewports up to 640px. */
31
31
  mobileFullscreen?: boolean;
32
+ /** Enable placement-aware entrance/exit animations (default true). */
33
+ animation?: boolean;
34
+ /** Animation duration in ms (default 220, maximum effective 1000). */
35
+ animationDuration?: number;
32
36
  /** Position: centered modal, side drawer, or top/bottom sheet. Default: right. */
33
37
  placement?: 'left' | 'right' | 'center' | 'top' | 'bottom';
34
38
  theme?: ModalTheme;
@@ -85,12 +89,15 @@ export interface ModalProviderProps {
85
89
  backgroundColor?: ModalBackground;
86
90
  theme?: ModalTheme;
87
91
  translate?: (key: string) => string;
92
+ /** Custom unsaved-changes confirmation. Return false to prevent closing/replacement. */
93
+ confirmDiscard?: (context: ModalEventContext) => boolean | Promise<boolean>;
88
94
  onError?: (error: unknown, context: { phase: string; [key: string]: unknown }) => void;
89
95
  }
90
96
  /** Named-object form for opening a modal without positional placeholders. */
91
- export interface ModalOpenConfig<P = unknown> {
97
+ export interface ModalOpenConfig<P = unknown> extends ModalOptions {
92
98
  name: string;
93
99
  params?: P;
100
+ /** Nested options override same-named top-level options. */
94
101
  options?: ModalOptions;
95
102
  }
96
103
  export interface ModalActions {
@@ -100,7 +107,22 @@ export interface ModalActions {
100
107
  open(config: ModalOpenConfig): Promise<number | null>;
101
108
  openAsync<T = unknown>(name: string, params?: unknown, overrides?: ModalOptions): Promise<ModalResult<T>>;
102
109
  openAsync<T = unknown>(config: ModalOpenConfig): Promise<ModalResult<T>>;
110
+ /** Queue a modal without replacing the current one; resolves to its ID when displayed. */
111
+ enqueue(name: string, params?: unknown, overrides?: ModalOptions): Promise<number | null>;
112
+ enqueue(config: ModalOpenConfig): Promise<number | null>;
113
+ /** Queue and await the result of a modal; other modals remain active until closed. */
114
+ enqueueAsync<T = unknown>(name: string, params?: unknown, overrides?: ModalOptions): Promise<ModalResult<T>>;
115
+ enqueueAsync<T = unknown>(config: ModalOpenConfig): Promise<ModalResult<T>>;
116
+ /** Merge runtime options into the currently visible modal without resetting navigation. */
117
+ update(patch: ModalOptions): boolean;
118
+ /** Cancel queued (not active) modals. Returns number cancelled. */
119
+ clearQueue(reason?: string): number;
120
+ readonly queueSize: number;
103
121
  close(result?: unknown): Promise<boolean>;
122
+ /** Dismiss without a confirmation value, using an optional reason. */
123
+ dismiss(reason?: string): Promise<boolean>;
124
+ /** Confirm even if the value is undefined. */
125
+ confirm(value?: unknown): Promise<boolean>;
104
126
  setLoading(value: boolean, text?: string): void;
105
127
  readonly isOpen: boolean;
106
128
  readonly activeName: string | null;
@@ -139,3 +161,9 @@ export interface ModalTaskActions {
139
161
  readonly isFocused: boolean;
140
162
  }
141
163
  export function useModalTask(): ModalTaskActions;
164
+
165
+ /** Protect a modal screen with unsaved form data; KeepAlive screens remain protected. */
166
+ export function useModalUnsavedChanges(dirty: boolean, options?: {
167
+ message?: string;
168
+ onBeforeDiscard?: (context: ModalEventContext) => boolean | Promise<boolean>;
169
+ }): void;