react-modal-navigation 1.1.2 → 1.1.4

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 CHANGED
@@ -1,3 +1,4 @@
1
+ - Footer 异步 Done/Cancel 操作自动触发覆盖整个弹窗的 Loading,支持 loadingText 国际化。
1
2
  # Changelog
2
3
 
3
4
  ## 1.0.0
@@ -16,3 +17,7 @@
16
17
  - `useModalUnsavedChanges` 提供未保存表单保护。
17
18
  - 根据弹窗位置匹配进入与退出动画,并支持减少动态效果设置。
18
19
  - 提供 TypeScript 类型声明和中文 API 参考文档。
20
+
21
+ - 支持通过 `modal.open({ name, screen, params })` 指定初始页面,兼容异步与队列调用。
22
+
23
+ - 支持 `navigation.setOptions()` 动态更新当前页面标题、Header 和 Footer 配置,并完善路由参数文档。
package/README.md CHANGED
@@ -229,6 +229,21 @@ function UserDetail() {
229
229
 
230
230
  `navigate` 进入路由,`goBack(result?)` 返回上一页,`replace` 替换当前页,`reset` 重置栈,`setParams` 合并当前页参数。隐藏页面 KeepAlive 保留状态;建议用 `useFocusEffect` 管理轮询和订阅。
231
231
 
232
+ ### 页面跳转方法速查
233
+
234
+ | 方法 | 使用示例 | 行为 |
235
+ |---|---|---|
236
+ | `navigate` | `navigation.navigate('UserDetail', { userId: 1 })` | 跳转;已有同名页面则复用并截断后续页面 |
237
+ | `goBack` | `navigation.goBack({ saved: true })` | 返回上一页并传回结果;根页面返回 `false` |
238
+ | `replace` | `navigation.replace('Success', { id: 1 })` | 替换当前页面 |
239
+ | `reset` | `navigation.reset('UserList')` | 重置为新的根页面 |
240
+ | `setParams` | `navigation.setParams({ tab: 'info' })` | 浅合并当前页面参数 |
241
+ | `close` | `await navigation.close({ id: 1 })` | 关闭整个弹窗,不是返回上一页 |
242
+
243
+ `navigation.canGoBack` 判断能否返回;`navigation.currentRoute` 获取当前页面 `{ key, name, params }`;`navigation.stack` 获取完整导航栈。上一页使用 `useNavigationResult(callback)` 接收 `goBack(result)` 的结果,KeepAlive 页面使用 `useIsFocused()` / `useFocusEffect()` 管理焦点副作用。
244
+
245
+ 完整的逐项说明、栈变化示例、返回值和注意事项请阅读 **[API 参考手册 · 第 5 章:页面导航](docs/API.md#5-页面导航-api完整指南)**。
246
+
232
247
  ## Promise 结果与关闭守卫
233
248
 
234
249
  ```jsx
@@ -405,3 +420,102 @@ modal.open({ name: 'quickInfo', placement: 'center', animation: false });
405
420
  ```
406
421
 
407
422
  `animationDuration` 单位毫秒;系统启用 `prefers-reduced-motion: reduce` 时自动关闭动画。退出动画结束后才触发 `onClose` 和队列中的下一个弹窗。
423
+
424
+ ## 打开时指定初始页面
425
+
426
+ 在同一个弹窗中注册多个页面,默认使用 `initialRoute`。通过 `screen` 可以在打开时覆盖初始页面,不需要先打开列表再导航。
427
+
428
+ ```jsx
429
+ const registry = {
430
+ userModal: {
431
+ initialRoute: 'UserList',
432
+ screens: {
433
+ UserList: { component: UserList, title: '用户列表' },
434
+ UserDetail: { component: UserDetail, title: '用户详情' },
435
+ UserEdit: { component: UserEdit, title: '编辑用户' },
436
+ },
437
+ },
438
+ };
439
+
440
+ modal.open({ name: 'userModal' }); // 打开 UserList
441
+ modal.open({
442
+ name: 'userModal',
443
+ screen: 'UserDetail',
444
+ params: { userId: 1001 },
445
+ placement: 'right',
446
+ width: 600,
447
+ });
448
+
449
+ // Promise 和队列 API 也支持 screen
450
+ const result = await modal.openAsync({
451
+ name: 'userModal',
452
+ screen: 'UserEdit',
453
+ params: { userId: 1001 },
454
+ });
455
+ ```
456
+
457
+ - `screen` 必须是 `registry[name].screens` 中注册的页面名称。
458
+ - 省略 `screen` 时使用 `initialRoute`;`params` 始终传给选中的初始页面。
459
+ - 未注册的页面会抛出错误,不会静默回退。
460
+ - 传统字符串调用 `modal.open('userModal', params, options)` 保持不变。
461
+ - `screen` 只在打开时生效,打开后切换页面请使用 `navigation.navigate()`。
462
+
463
+
464
+ ## 动态页面标题与路由参数
465
+
466
+ 每个弹窗页面均可通过 `useModal()` 取得 `navigation.currentRoute`,或者直接读取页面组件的 `route` 属性。`params` 是打开或跳转页面时传入的参数。
467
+
468
+ ```jsx
469
+ import { useEffect } from 'react';
470
+ import { useModal } from 'react-modal-navigation';
471
+
472
+ function UserDetail({ route }) {
473
+ const { navigation } = useModal();
474
+ const userId = route.params?.userId;
475
+
476
+ useEffect(() => {
477
+ navigation.setOptions({ title: `用户详情 #${userId}` });
478
+ }, [navigation.setOptions, userId]);
479
+
480
+ return <div>用户 ID:{userId}</div>;
481
+ }
482
+
483
+ // 打开时指定页面和参数
484
+ modal.open({ name: 'userModal', screen: 'UserDetail', params: { userId: 1001 } });
485
+
486
+ // 弹窗内导航时传参
487
+ navigation.navigate('UserDetail', { userId: 1002 });
488
+ ```
489
+
490
+ `navigation.setOptions(options)` 更新**当前路由实例**的页面配置(例如 `title`、`renderHeaderRight`、`showBackButton`),不会修改 Registry,也不会重置页面栈。`navigation.setParams({ userId: 1003 })` 则合并当前页面参数。详情见 [API 文档](docs/API.md)。
491
+
492
+
493
+ ### Footer 异步操作的整窗 Loading
494
+
495
+ 点击默认 Footer 的 Done/Cancel 按钮后,组件会在异步操作期间自动显示覆盖整个弹窗的 Loading 蒙层,完成或失败后自动移除。无需手动管理加载状态。`loadingText` 优先于 `translate('modal.processing')`,可按业务分别设置。
496
+
497
+ ```jsx
498
+ function EditUser() {
499
+ const { t } = useTranslation();
500
+ useModalFooter({
501
+ doneText: t('common.save'),
502
+ loadingText: t('common.saving'),
503
+ done: async () => { await saveUser(); },
504
+ });
505
+ return <UserForm />;
506
+ }
507
+ ```
508
+
509
+ 如果需要手动控制整个弹窗的加载,可继续使用 `useModalLoading()` 的 `setLoading(true, t('...'))` / `setLoading(false)`,或者 `modal.setLoading(...)`。
510
+
511
+
512
+ ### 整窗 Loading 蒙层
513
+
514
+ `useModalLoading()` / `modal.setLoading()` 触发的 Loading 覆盖整个弹窗(Header、页面内容和 Footer),居中展示无卡片、无阴影的旋转圆圈及可国际化文案。背景使用半透明蒙层,弹窗内的操作在加载期间被遮挡。
515
+
516
+ ```jsx
517
+ modal.setLoading(true, { text: t("common.loading") });
518
+ // 请求结束后
519
+ modal.setLoading(false);
520
+ ```
521
+
package/dist/index.cjs CHANGED
@@ -1 +1 @@
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;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),t=require("react"),Le=require("react-dom"),Me=t.createContext(null),ve=t.createContext(null),fe=t.createContext(null),xe=t.createContext(null),je=t.createContext(null);let Pe=0;const ye=(e,n)=>({key:`modal-route-${++Pe}`,name:e,params:n??{}}),Se=(e,n)=>[ye(e,n)];function Be(e,n){switch(n.type){case"RESET":return Se(n.name,n.params);case"NAVIGATE":{const o=e.findIndex(a=>a.name===n.name);return o<0?[...e,ye(n.name,n.params)]:e.slice(0,o+1).map((a,c)=>c===o?{...a,params:n.params??{}}:a)}case"SET_OPTIONS":return e.map((o,a)=>a===e.length-1?{...o,options:{...o.options??{},...n.options??{}}}:o);case"SET_PARAMS":return e.map((o,a)=>a===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),ye(n.name,n.params)]:e;default:return e}}const Ee=()=>{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 X=[];let ge=null;function Fe(){if(ie++,ie===1){const n=document.documentElement,o=document.body,a={html:n.style.overflow,body:o.style.overflow,padding:o.style.paddingRight,width:o.style.getPropertyValue("--modal-scrollbar-width")},c=Math.max(0,window.innerWidth-n.clientWidth),y=parseFloat(getComputedStyle(o).paddingRight)||0;c&&(o.style.paddingRight=`${y+c}px`),o.style.setProperty("--modal-scrollbar-width",`${c}px`),n.style.overflow="hidden",o.style.overflow="hidden",ge=()=>{n.style.overflow=a.html,o.style.overflow=a.body,o.style.paddingRight=a.padding,a.width?o.style.setProperty("--modal-scrollbar-width",a.width):o.style.removeProperty("--modal-scrollbar-width")}}let e=!1;return()=>{e||(e=!0,ie=Math.max(0,ie-1),ie||(ge?.(),ge=null))}}const qe='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";function Ae({dialogRef:e,options:n,requestClose:o,children:a,exiting:c=!1}){const y=t.useRef(null),b=t.useRef(null),E=t.useRef(o);E.current=o;const p=t.useRef(n.closeOnEsc);p.current=n.closeOnEsc;const[k,j]=t.useState(Ee),x=n.theme==="light"||n.theme==="dark"?n.theme:k;t.useEffect(()=>{if(n.theme==="light"||n.theme==="dark")return;const T=()=>j(Ee()),I=new MutationObserver(T);for(const C of[document.documentElement,document.body])I.observe(C,{attributes:!0,attributeFilter:["class","data-theme"]});const W=window.matchMedia?.("(prefers-color-scheme: dark)");return W?.addEventListener?.("change",T),T(),()=>{I.disconnect(),W?.removeEventListener?.("change",T)}},[n.theme]),t.useEffect(()=>{b.current=document.activeElement;const T=Fe(),I=y.current;X.push(I),e.current?.focus({preventScroll:!0});const W=g=>{const R=e.current;if(!R||X.at(-1)!==I)return;if(g.key==="Escape"&&p.current!==!1){g.preventDefault(),E.current("escape");return}if(g.key!=="Tab")return;const P=[...R.querySelectorAll(qe)].filter(Oe);if(!P.length){g.preventDefault(),R.focus();return}const H=P[0],S=P.at(-1);R.contains(document.activeElement)?g.shiftKey&&(document.activeElement===H||document.activeElement===R)?(g.preventDefault(),S.focus()):!g.shiftKey&&(document.activeElement===S||document.activeElement===R)&&(g.preventDefault(),H.focus()):(g.preventDefault(),(g.shiftKey?S:H).focus())},C=g=>{X.at(-1)===I&&e.current&&!e.current.contains(g.target)&&e.current.focus({preventScroll:!0})};return document.addEventListener("keydown",W),document.addEventListener("focusin",C),()=>{document.removeEventListener("keydown",W),document.removeEventListener("focusin",C);const g=X.at(-1)===I,R=X.indexOf(I);if(R!==-1&&X.splice(R,1),T(),g){const P=b.current;P?.isConnected&&!P.closest("[inert], [hidden]")?P.focus?.({preventScroll:!0}):X.at(-1)?.querySelector("[role=dialog]")?.focus?.({preventScroll:!0})}}},[e]);const w=n.backgroundColor??n.backgroudColor,u=typeof w=="string"?w:w?.[x],h=typeof u=="string"&&/^(#|rgb\(|rgba\(|hsl\(|hsla\(|oklch\(|color\(|var\()/.test(u.trim())?u:null,q={sm:400,md:560,lg:720,xl:960,full:"100%"},N=["center","left","right","top","bottom"].includes(n.placement)?n.placement:"right",$=T=>typeof T=="number"?`${T}px`:T,B=$(n.width??q[n.size]??460),A=$(n.height),M=$(n.maxHeight),O=$(n.maxWidth),L=Number(n.viewportGap??5),D=Number.isFinite(L)?Math.max(0,L):5,F=typeof n.borderRadius=="number"?`${n.borderRadius}px`:n.borderRadius??"12px";return Le.createPortal(d.jsx("div",{ref:y,className:`pmn-overlay ${c?"pmn-exiting":"pmn-entering"} ${n.animation===!1?"pmn-no-animation":""} pmn-place-${N} ${n.mobileFullscreen?"pmn-mobile-fullscreen":""}`,style:{padding:D,"--pmn-animation-duration":`${Math.min(1e3,Math.max(0,Number(n.animationDuration??220)||0))}ms`},onMouseDown:T=>{T.target===T.currentTarget&&n.closeOnOverlay===!0&&E.current("overlay")},children:d.jsx("section",{ref:e,tabIndex:-1,role:"dialog","aria-modal":"true","aria-label":n.ariaLabel??"Dialog","data-modal-theme":x,className:`pmn-dialog ${x==="dark"?"dark":""} ${!h&&u?u:""} ${n.className??""}`,style:{"--pmn-width":B,"--pmn-gap":`${D}px`,...A!==void 0?{"--pmn-height":A}:{},...M!==void 0?{"--pmn-max-height":M}:{},...O!==void 0?{"--pmn-max-width":O}:{},borderRadius:F,...h?{backgroundColor:h}:{}},children:a})}),document.body)}function Ce({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:a,requestClose:c,translate:y}){if(e.showHeader===!1)return null;const b=y??(w=>w),E=n.showTitle??e.showTitle??!0,p=typeof n.title=="function"?n.title({t:b,route:o,navigation:a}):n.title??o.name,k={route:o,navigation:a,close:c,canGoBack:a.canGoBack,title:p,t:b},j=n.renderHeader??e.renderHeader;if(j)return j(k);const x=n.renderHeaderRight??e.renderHeaderRight;return d.jsxs("header",{className:`pmn-header ${n.showHeaderBorder??e.showHeaderBorder?"pmn-border-bottom":""} ${e.headerClassName??""}`,children:[e.showBackButton!==!1&&a.canGoBack&&d.jsx("button",{type:"button",className:"pmn-icon-button","aria-label":b("modal.back"),onClick:()=>a.goBack(),children:d.jsx(Ce,{back:!0})}),E?d.jsx("h2",{children:p}):d.jsx("div",{className:"pmn-header-spacer"}),x?.(k),e.showCloseButton!==!1&&d.jsx("button",{type:"button",className:"pmn-icon-button","aria-label":b("modal.close"),onClick:()=>c("header"),children:d.jsx(Ce,{})})]})}function $e({screen:e,options:n,override:o,route:a,navigation:c,requestClose:y,translate:b,onError:E,loadingApi:p}){const[k,j]=t.useState(!1),x=b??(L=>L),w={...n,...e,...o},{showFooter:u,renderFooter:h,done:q,cancel:N,cancle:$}=w,B=N??$,A={route:a,navigation:c,close:y,t:x};if(u===!1)return null;const M=`pmn-footer ${w.showFooterBorder?"pmn-border-top":""} ${w.footerClassName??""}`;if(typeof h=="function")return d.jsx("footer",{className:M,children:h({...A,pending:k})});if(typeof q!="function"&&typeof B!="function")return null;const O=async L=>{if(k||typeof L!="function")return;j(!0);const D=p?.begin(a.key,w.loadingText??x("modal.processing"));try{await L(A)}catch(F){E?.(F,{phase:"footer",route:a})}finally{p?.end(a.key,D),j(!1)}};return d.jsxs("footer",{className:M,children:[typeof B=="function"&&d.jsx("button",{type:"button",disabled:k,onClick:()=>O(B),className:"pmn-button pmn-button-secondary",children:w.cancelText??x("modal.cancel")}),typeof q=="function"&&d.jsx("button",{type:"button",disabled:k||w.doneDisabled===!0,onClick:()=>O(q),className:"pmn-button pmn-button-primary",children:k?w.loadingText??x("modal.processing"):w.doneText??x("modal.done")})]})}function Ie({loading:e,translate:n}){if(!e.visible)return null;const a=(n??(y=>y))("modal.loading"),c=e.text??(a==="modal.loading"?"加载中...":a);return d.jsx("div",{className:"pmn-loading-overlay",role:"status","aria-live":"polite","aria-busy":"true",children:d.jsxs("div",{className:"pmn-loading-content",children:[d.jsx("span",{className:"pmn-spinner","aria-hidden":"true"}),c&&d.jsx("span",{className:"pmn-loading-text",children:c})]})})}class He 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 ze({route:e,screen:n,navigation:o,focused:a,resultEvent:c,setFooter:y,loadingApi:b,bodyClassName:E,notifyError:p,registerDirtyGuard:k}){const j=n.component,x=t.useMemo(()=>({isFocused:a,resultEvent:c,routeKey:e.key,setFooter:y}),[a,c,e.key,y]),w=t.useMemo(()=>({isLoading:a&&b.isLoading,setLoading:(u,h)=>b.setScreenLoading(e.key,u,h),showLoading:u=>b.begin(e.key,u),hideLoading:u=>b.end(e.key,u)}),[a,b,e.key]);return d.jsx(je.Provider,{value:{routeKey:e.key,registerDirtyGuard:k},children:d.jsx(fe.Provider,{value:x,children:d.jsx(xe.Provider,{value:w,children:d.jsx("div",{hidden:!a,inert:!a,"data-modal-route-key":e.key,tabIndex:-1,className:`pmn-body ${E??""}`,children:d.jsx(He,{route:e,onError:p,children:d.jsx(j,{route:e,navigation:o})})})})})})}function Te({config:e,initialScreen:n,params:o,options:a,translate:c,onRequestClose:y,onOpened:b,registerLoading:E,notifyError:p,error:k,clearError:j,registerDirtyGuard:x,exiting:w=!1}){const[u,h]=t.useReducer(Be,null,()=>Se(n??e.initialRoute,o)),[q,N]=t.useState({}),[$,B]=t.useState({}),[,A]=t.useState(0),M=t.useRef(new Map),O=t.useRef(0),L=t.useRef(new Map),D=t.useRef(null),F=t.useRef(null),T=t.useRef(!1),I=t.useRef(!1),W=t.useRef(0),C=u.at(-1),g=C.key,R=t.useRef(g);R.current=g;const P=e.screens,H=t.useCallback(()=>A(r=>r+1),[]),S=t.useCallback((r,l)=>{if(r!=="global"&&R.current!==r)return null;const m=++O.current;return M.current.set(m,{owner:r,text:l}),H(),m},[H]),K=t.useCallback((r,l)=>{if(l!=null)M.current.get(l)?.owner===r&&M.current.delete(l);else for(const[m,G]of M.current)G.owner===r&&M.current.delete(m);H()},[H]),z=t.useCallback((r,l)=>{r?(K("global"),S("global",l)):K("global")},[S,K]),Z=t.useCallback((r,l,m)=>{l?(K(r),S(r,m)):K(r)},[S,K]),ee=[...M.current.values()],U={visible:ee.length>0,text:ee.at(-1)?.text??null,count:ee.length},_=t.useRef(U);_.current=U;const ne=t.useMemo(()=>({isLoading:U.visible,setLoading:z,setScreenLoading:Z,begin:S,end:K}),[U.visible,z,Z,S,K]),te=t.useRef(E);te.current=E,t.useEffect(()=>(te.current?.({setLoading:z}),()=>te.current?.(null)),[z]);const le=t.useCallback((r,l)=>B(m=>{if(l===null){if(!(r in m))return m;const G={...m};return delete G[r],G}return m[r]===l?m:{...m,[r]:l}}),[]),V=t.useCallback(()=>{const r=document.activeElement;if(!(r instanceof HTMLElement)||!D.current?.contains(r))return;const l=r.closest("[data-modal-route-key]");l&&L.current.set(l.dataset.modalRouteKey,r),D.current.focus({preventScroll:!0})},[]),re=t.useCallback(r=>{if(!Object.prototype.hasOwnProperty.call(P,r))throw new Error(`[react-modal-navigation] Unknown modal screen: ${r}`)},[P]),Q=t.useCallback((r,l)=>{try{Promise.resolve(a[r]?.(l)).catch(m=>p(m,{phase:r}))}catch(m){p(m,{phase:r})}},[a,p]),Y=t.useCallback((r,l,m)=>{re(l),V(),h({type:r,name:l,params:m})},[re,V]),oe=t.useCallback((r,l)=>Y("NAVIGATE",r,l),[Y]),ae=t.useCallback((r,l)=>Y("REPLACE",r,l),[Y]),se=t.useCallback((r,l)=>{N({}),Y("RESET",r,l)},[Y]),ce=t.useCallback(r=>{if(!r||typeof r!="object"||Array.isArray(r))throw new TypeError("[react-modal-navigation] setParams expects an object");h({type:"SET_PARAMS",params:r})},[]),ue=t.useCallback(r=>{if(!r||typeof r!="object"||Array.isArray(r))throw new TypeError("[react-modal-navigation] setOptions expects an object");h({type:"SET_OPTIONS",options:r})},[]),s=t.useCallback(r=>{if(u.length<=1||T.current)return!1;if(T.current=!0,r!==void 0){const l=u.at(-2);N(m=>({...m,[l.key]:{id:++W.current,data:r}}))}return V(),h({type:"BACK"}),!0},[u,V]),i=t.useCallback((r,l)=>_.current.visible&&a.lockCloseWhileLoading!==!1?Promise.resolve(!1):y(r,l,{route:C,stack:u}),[a.lockCloseWhileLoading,y,C,u]),v=t.useCallback(r=>i("api",r),[i]),f=t.useMemo(()=>({navigate:oe,replace:ae,reset:se,setParams:ce,setOptions:ue,goBack:s,close:v,setLoading:z,canGoBack:u.length>1,stack:u,currentRoute:C}),[oe,ae,se,ce,ue,s,v,z,u,C]);return t.useLayoutEffect(()=>{T.current=!1;const r=[...D.current?.querySelectorAll("[data-modal-route-key]")??[]].find(G=>G.dataset.modalRouteKey===g);if(!r)return;const l=L.current.get(g);(l?.isConnected&&r.contains(l)&&!l.matches(":disabled")&&!l.closest("[inert], [hidden]")?l:r).focus({preventScroll:!0})},[g]),t.useEffect(()=>{let r=!1;for(const[m,G]of M.current)G.owner!=="global"&&G.owner!==g&&(M.current.delete(m),r=!0);r&&H();const l=new Set(u.map(m=>m.key));for(const m of L.current.keys())l.has(m)||L.current.delete(m)},[g,u,H]),t.useEffect(()=>{if(F.current?.key!==g){if(F.current){const r={from:F.current,to:C,stack:u};Q("onBlur",{route:F.current,...r}),Q("onNavigate",r),Q("onRouteChange",r)}Q("onFocus",{route:C,stack:u}),F.current=C}},[C,g,u,Q]),t.useEffect(()=>()=>{M.current.clear(),L.current.clear()},[]),t.useEffect(()=>{I.current||(I.current=!0,b?.({route:C,stack:u}))},[]),d.jsx(ve.Provider,{value:f,children:d.jsx(xe.Provider,{value:ne,children:d.jsxs(Ae,{dialogRef:D,options:a,requestClose:i,exiting:w,children:[d.jsx(De,{options:a,screen:{...P[C.name],...C.options??{}},route:C,navigation:f,requestClose:i,translate:c}),d.jsx("main",{className:"pmn-main",children:u.map(r=>d.jsx(ze,{route:r,screen:P[r.name],navigation:f,focused:r.key===g,resultEvent:q[r.key]??null,bodyClassName:a.bodyClassName,setFooter:le,loadingApi:ne,notifyError:p,registerDirtyGuard:x},r.key))}),d.jsx($e,{screen:{...P[C.name],...C.options??{}},options:a,override:$[g],route:C,navigation:f,requestClose:i,translate:c,onError:p,loadingApi:ne},g),d.jsx(Ie,{loading:U,translate:c}),k&&d.jsxs("div",{className:"pmn-error",role:"alert",children:[d.jsx("span",{children:k.message||String(k)}),d.jsx("button",{type:"button",onClick:j,"aria-label":"Dismiss error",children:"×"})]})]})})})}const Ge=".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:#ffffffb8;backdrop-filter:blur(2px);-webkit-backdrop-filter:blur(2px);cursor:progress}.pmn-dialog[data-modal-theme=dark] .pmn-loading-overlay{background:#0f172ab8}.pmn-loading-content{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;max-width:85%;text-align:center;color:var(--pmn-text);pointer-events:none}.pmn-loading-text{font-size:14px;font-weight:500;line-height:1.5;overflow-wrap:anywhere}.pmn-spinner{width:38px;height:38px;border:3px solid rgba(37,99,235,.2);border-top-color:#2563eb;border-radius:50%;animation:pmn-spin .8s linear infinite}@keyframes pmn-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.pmn-spinner{animation-duration:1.8s}}.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}}",Re="react-modal-navigation-styles",be=new WeakMap;function Ke(){t.useInsertionEffect(()=>{if(typeof document>"u")return;const e=document;let n=be.get(e);if(!n){let o=e.getElementById(Re);const a=!o;o||(o=e.createElement("style"),o.id=Re,o.setAttribute("data-react-modal-navigation",""),o.textContent=Ge,e.head.appendChild(o)),n={element:o,owned:a,count:0},be.set(e,n)}return n.count+=1,()=>{n.count-=1,n.count===0&&(n.owned&&n.element.remove(),be.delete(e))}},[])}function me(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:a,screen:c,params:y={},options:b={},...E}=e;if(typeof a!="string"||!a.trim())throw new TypeError("[react-modal-navigation] open config requires a non-empty string name");if(b===null||typeof b!="object"||Array.isArray(b))throw new TypeError("[react-modal-navigation] open config options must be an object");if(c!==void 0&&(typeof c!="string"||!c.trim()))throw new TypeError("[react-modal-navigation] screen must be a non-empty string");return{name:a,...c===void 0?{}:{screen:c},params:y,options:{...E,...b}}}const Ue={placement:"right",showHeader:!0,showBackButton:!0,showCloseButton:!0,viewportGap:5,borderRadius:12,closeOnOverlay:!1,closeOnEsc:!0},We=e=>({"modal.loading":"加载中...","modal.processing":"处理中...","modal.back":"返回","modal.close":"关闭","modal.cancel":"取消","modal.done":"完成"})[e]??e;function Ye({registry:e,children:n,defaultOptions:o={},backgroundColor:a,theme:c,translate:y=We,onError:b,confirmDiscard:E}){Ke();const[p,k]=t.useState(null),[j,x]=t.useState(null),[w,u]=t.useState(0),h=t.useRef(null),q=t.useRef(new Map),N=t.useRef([]),$=t.useRef(null),B=t.useRef(null),A=t.useRef(0),M=t.useRef(null),O=t.useRef(!1),L=t.useRef(0),D=t.useRef(null),F=t.useRef(new Map),[T,I]=t.useState(!1),W=t.useRef(E);W.current=E;const C=t.useCallback((s,i)=>(F.current.set(s,i),()=>{F.current.get(s)===i&&F.current.delete(s)}),[]),g=t.useCallback(async s=>{for(const i of F.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},[]),R=t.useRef(!0),P=t.useRef(null),H=t.useRef(b);H.current=b;const S=t.useCallback((s,i)=>{R.current&&x(s);try{H.current?H.current(s,i):console.error("[react-modal-navigation]",s)}catch(v){console.error("[react-modal-navigation] onError failed",v)}},[]),K=t.useCallback((s,i)=>{const v=q.current.get(s);q.current.delete(s),v?.(i)},[]),z=t.useCallback(s=>({...Ue,...o,...c!==void 0?{theme:c}:{},...a!==void 0?{backgroundColor:a}:{},...s.config.modalOptions,...s.overrides}),[o,c,a]),Z=p?z(p):null,ee=t.useRef(null);ee.current=Z,P.current=Z;const U=t.useCallback(async(s="api",i,v={})=>{const f=h.current;if(!f||M.current||O.current)return!1;M.current=f.id,O.current=!0;const r=P.current??z(f),l={...v,reason:s,result:i,name:f.name};try{if(!await g(l)||await r.onBeforeClose?.(l)===!1||h.current?.id!==f.id||!R.current||(I(!0),await new Promise(m=>{const G=r.animation===!1||typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?0:Math.max(0,Number(r.animationDuration??220)||0);setTimeout(m,Math.min(G,1e3))}),!R.current||h.current?.id!==f.id))return!1;h.current=null,D.current=null,k(null),I(!1),F.current.clear(),K(f.id,v.confirmed||i!==void 0?{status:"confirmed",value:i,reason:s}:{status:"dismissed",reason:s});try{await r.onClose?.(l)}catch(m){S(m,{phase:"onClose",name:f.name})}return!0}catch(m){return S(m,{phase:"onBeforeClose",name:f.name}),!1}finally{M.current===f.id&&(M.current=null),O.current=!1,!h.current&&R.current&&queueMicrotask(()=>B.current?.())}},[z,S,K,g]),_=t.useCallback(async(s,i={},v={},f,r)=>{const l=e?.[s];if(!l)throw new Error(`[react-modal-navigation] Unknown modal: ${s}`);const m=r??l.initialRoute;if(!l.screens?.[m])throw new Error(`[react-modal-navigation] Unknown initial screen '${m}' in modal '${s}'`);if(!R.current||O.current||M.current)return null;O.current=!0;const G=L.current;try{const J=h.current;if(J){const ke=P.current??z(J),pe={reason:"replace",name:J.name,nextName:s};try{if(!await g(pe)||await ke.onBeforeClose?.(pe)===!1)return null}catch(he){return S(he,{phase:"onBeforeClose",name:J.name}),null}if(!R.current||G!==L.current||h.current?.id!==J.id)return null;h.current=null,D.current=null,k(null),F.current.clear(),K(J.id,{status:"replaced",reason:"replace"});try{await ke.onClose?.(pe)}catch(he){S(he,{phase:"onClose",name:J.name})}if(!R.current||G!==L.current)return null}const de={id:++A.current,name:s,screen:m,params:i,config:l,overrides:v};return h.current=de,D.current=null,f&&q.current.set(de.id,f),x(null),k(de),de.id}finally{O.current=!1}},[e,z,S,K,g]);$.current=_;const ne=t.useCallback(async()=>{if(!R.current||h.current||O.current||M.current)return;const s=N.current.shift();if(s){u(N.current.length);try{const i=await $.current(s.args.name,s.args.params,s.args.options,s.resolveResult,s.args.screen);i===null?(s.resolveResult?.({status:"dismissed",reason:"blocked"}),s.resolveId?.(null),queueMicrotask(()=>B.current?.())):s.resolveId?.(i)}catch(i){s.reject?.(i),queueMicrotask(()=>B.current?.())}}},[]);B.current=ne;const te=t.useCallback((s,i,v)=>{const f=me(s,i,v);return e?.[f.name]?new Promise((r,l)=>{N.current.push({args:f,resolveId:r,reject:l}),u(N.current.length),queueMicrotask(()=>B.current?.())}):Promise.reject(new Error(`[react-modal-navigation] Unknown modal: ${f.name}`))},[e]),le=t.useCallback((s,i,v)=>{const f=me(s,i,v);return e?.[f.name]?new Promise((r,l)=>{N.current.push({args:f,resolveResult:r,reject:l}),u(N.current.length),queueMicrotask(()=>B.current?.())}):Promise.reject(new Error(`[react-modal-navigation] Unknown modal: ${f.name}`))},[e]),V=t.useCallback(s=>{if(!s||typeof s!="object"||Array.isArray(s))throw new TypeError("[react-modal-navigation] update expects an options object");const i=h.current;if(!i||O.current)return!1;const v={...i,overrides:{...i.overrides,...s}};return h.current=v,k(v),P.current=z(v),!0},[z]),re=t.useCallback((s="queue-cleared")=>{const i=N.current.splice(0);u(0);for(const v of i)v.resolveId?.(null),v.resolveResult?.({status:"dismissed",reason:s});return i.length},[]),Q=t.useCallback((s,i,v)=>{const f=me(s,i,v);return _(f.name,f.params,f.options,void 0,f.screen)},[_]),Y=t.useCallback((s,i,v)=>{const f=me(s,i,v);return new Promise((r,l)=>{_(f.name,f.params,f.options,r,f.screen).then(m=>{m===null&&r({status:"dismissed",reason:"blocked"})},l)})},[_]),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)=>D.current?.setLoading(s,i),[]),ue=t.useMemo(()=>({open:Q,openAsync:Y,enqueue:te,enqueueAsync:le,update:V,clearQueue:re,close:oe,dismiss:ae,confirm:se,setLoading:ce,queueSize:w,isOpen:!!p,activeName:p?.name??null,error:j,clearError:()=>x(null)}),[Q,Y,te,le,V,re,oe,ae,se,ce,p,j,w]);return t.useEffect(()=>(R.current=!0,()=>{R.current=!1,L.current+=1,h.current=null;for(const i of q.current.values())i({status:"dismissed",reason:"unmount"});q.current.clear(),F.current.clear();const s=N.current.splice(0);for(const i of s)i.resolveId?.(null),i.resolveResult?.({status:"dismissed",reason:"unmount"})}),[]),d.jsxs(Me.Provider,{value:ue,children:[n,p&&d.jsx(Te,{config:p.config,initialScreen:p.screen,params:p.params,options:Z,translate:y,notifyError:S,error:j,clearError:()=>x(null),registerLoading:s=>{D.current=s},registerDirtyGuard:C,exiting:T,onRequestClose:U,onOpened:s=>{try{const i=ee.current?.onOpen?.(s);Promise.resolve(i).catch(v=>S(v,{phase:"onOpen"}))}catch(i){S(i,{phase:"onOpen"})}}},p.id)]})}function _e(){const e=t.useContext(Me),n=t.useContext(ve);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:(...c)=>o().navigate(...c),replace:(...c)=>o().replace(...c),reset:(...c)=>o().reset(...c),setParams:(...c)=>o().setParams(...c),setOptions:(...c)=>o().setOptions(...c),goBack:(...c)=>o().goBack(...c),close:(...c)=>o().close(...c),get canGoBack(){return n?.canGoBack??!1},get stack(){return n?.stack??[]},get currentRoute(){return n?.currentRoute??null}}}},[e,n])}function Qe(){const e=t.useContext(ve);if(!e)throw new Error("useModalNavigation requires an active modal screen");return e}function we(){const e=t.useContext(fe);if(!e)throw new Error("useIsFocused must be called inside a modal screen");return e.isFocused}function Ve(e){const n=we();t.useEffect(()=>{if(n)return e()},[n,e])}function Je(e){const n=t.useContext(fe);if(!n)throw new Error("useNavigationResult requires an active modal screen");const o=t.useRef(e),a=t.useRef(null);t.useEffect(()=>{o.current=e},[e]),t.useEffect(()=>{!n.isFocused||!n.resultEvent||a.current!==n.resultEvent.id&&(a.current=n.resultEvent.id,o.current(n.resultEvent.data))},[n.isFocused,n.resultEvent])}function Xe(e={}){const n=t.useContext(fe);if(!n)throw new Error("[react-modal-navigation] useModalFooter requires an active modal screen");const{setFooter:o,routeKey:a}=n,c=t.useRef(e);c.current=e;const y=t.useMemo(()=>(...A)=>c.current.done?.(...A),[]),b=t.useMemo(()=>(...A)=>(c.current.cancel??c.current.cancle)?.(...A),[]),E=t.useMemo(()=>(...A)=>c.current.renderFooter?.(...A),[]),p=typeof e.done=="function",k=typeof(e.cancel??e.cancle)=="function",j=typeof e.renderFooter=="function",{showFooter:x,showFooterBorder:w,doneDisabled:u,doneText:h,cancelText:q,loadingText:N,footerClassName:$}=e,B=t.useMemo(()=>({showFooter:x,showFooterBorder:w,doneDisabled:u,doneText:h,cancelText:q,loadingText:N,footerClassName:$,...p?{done:y}:{},...k?{cancel:b}:{},...j?{renderFooter:E}:{}}),[x,w,u,h,q,N,$,p,k,j,y,b,E]);t.useEffect(()=>{o(a,B)},[a,o,B]),t.useEffect(()=>()=>o(a,null),[a,o])}function Ne(){const e=t.useContext(xe);if(!e)throw new Error("[react-modal-navigation] useModalLoading requires an active modal screen");return e}function Ze(){const e=Ne(),n=we(),o=t.useRef(!0),a=t.useRef(!1),[c,y]=t.useState(!1),[b,E]=t.useState(null),p=t.useRef(e);return p.current=e,t.useEffect(()=>(o.current=!0,()=>{o.current=!1}),[]),{run:t.useCallback(async(j,x={})=>{if(a.current)return{status:"busy"};if(typeof j!="function")throw new TypeError("[react-modal-navigation] run requires a function");a.current=!0,o.current&&(y(!0),E(null));const w=p.current.showLoading(x.loadingText);try{const u=await j();return o.current&&await x.onSuccess?.(u),{status:"success",value:u}}catch(u){if(o.current){E(u);try{await x.onError?.(u)}catch(h){console.error("[react-modal-navigation] onError failed",h)}}if(x.throwOnError)throw u;return{status:"error",error:u}}finally{w!=null&&p.current.hideLoading(w),a.current=!1,o.current&&y(!1)}},[]),pending:c,error:b,clearError:()=>E(null),isFocused:n}}function et(e,n={}){const o=t.useContext(je);if(!o)throw new Error("[react-modal-navigation] useModalUnsavedChanges must be used inside a modal screen");const a=t.useRef({dirty:e,...n});a.current={dirty:e,...n};const{routeKey:c,registerDirtyGuard:y}=o;t.useEffect(()=>y(c,{get dirty(){return!!a.current.dirty},get message(){return a.current.message},get onBeforeDiscard(){return a.current.onBeforeDiscard}}),[c,y])}exports.ModalNavigator=Te;exports.ModalProvider=Ye;exports.useFocusEffect=Ve;exports.useIsFocused=we;exports.useModal=_e;exports.useModalFooter=Xe;exports.useModalLoading=Ne;exports.useModalNavigation=Qe;exports.useModalTask=Ze;exports.useModalUnsavedChanges=et;exports.useNavigationResult=Je;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { ComponentType, ReactNode } from 'react';
2
2
  export type ModalTheme = 'auto' | 'light' | 'dark';
3
3
  export type ModalBackground = string | { light?: string; dark?: string };
4
- export interface ModalRoute<P = unknown> { key: string; name: string; params: P }
4
+ export interface ModalRoute<P = unknown> { key: string; name: string; params: P; options?: ModalScreenOptions }
5
5
  export type ModalResult<T = unknown> = { status: 'confirmed'; value: T; reason: string } | { status: 'dismissed' | 'replaced'; reason: string };
6
6
  export interface ModalEventContext<T = unknown> { route?: ModalRoute; stack?: ModalRoute[]; from?: ModalRoute; to?: ModalRoute; reason?: string; result?: T; name?: string }
7
7
  export interface ModalNavigation {
@@ -9,6 +9,8 @@ export interface ModalNavigation {
9
9
  replace(name: string, params?: unknown): void;
10
10
  reset(name: string, params?: unknown): void;
11
11
  setParams(params: Record<string, unknown>): void;
12
+ /** Update options of the active screen without navigating. Changes are scoped to this route instance. */
13
+ setOptions(options: ModalScreenOptions): void;
12
14
  goBack(result?: unknown): boolean;
13
15
  close(result?: unknown): Promise<boolean>;
14
16
  setLoading(value: boolean, text?: string): void;
@@ -76,6 +78,9 @@ export interface ModalOptions {
76
78
  renderHeaderRight?: (context: ModalActionContext) => ReactNode;
77
79
  }
78
80
  export interface ModalActionContext { route: ModalRoute; navigation: ModalNavigation; close: (reason?: string, result?: unknown) => Promise<boolean>; t: (key: string) => string }
81
+ export interface ModalScreenOptions extends Omit<Partial<ModalOptions>, 'title'> {
82
+ title?: string | ReactNode | ((context: { t: (key: string) => string; route: ModalRoute; navigation: ModalNavigation }) => ReactNode);
83
+ }
79
84
  export interface ModalScreen extends ModalOptions {
80
85
  component: ComponentType<any>;
81
86
  title?: string | ((context: { t: (key: string) => string; route: ModalRoute; navigation: ModalNavigation }) => ReactNode);
@@ -96,6 +101,9 @@ export interface ModalProviderProps {
96
101
  /** Named-object form for opening a modal without positional placeholders. */
97
102
  export interface ModalOpenConfig<P = unknown> extends ModalOptions {
98
103
  name: string;
104
+ /** Initial screen within registry[name].screens; defaults to initialRoute. */
105
+ screen?: string;
106
+ /** Params passed to the selected initial screen. */
99
107
  params?: P;
100
108
  /** Nested options override same-named top-level options. */
101
109
  options?: ModalOptions;