react-modal-navigation 1.1.5 → 1.1.7

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,35 @@
1
+ ## 1.1.6 — Architecture maintenance
2
+
3
+ - Extracted Loading and Toast controllers from ModalNavigator.
4
+ - Replaced Footer action JSON serialization with property comparison and latest callback dispatch.
5
+ - Added commands-only Loading Hook and state Hook, preserving existing API.
6
+ - Added typed navigation helper and regression tests.
7
+ - Guarded document access for non-browser rendering.
8
+
9
+ ## 1.1.6 — 使用体验扩展
10
+
11
+ - 新增 `useModalRoute` / `useModalParams`。
12
+ - 新增 `navigation.navigateAsync`,支持页面返回、移除、关闭等终止状态。
13
+ - 新增 Footer 声明式 `actions`,每个按钮独立提交状态。
14
+ - 新增 `toast.promise`,保留任务返回值和错误传播。
15
+ - 同步更新类型声明、文档与测试。
16
+
17
+ ## 1.1.6
18
+
19
+ - 修复 ModalNavigator 缺少 useState 导入的运行时问题。
20
+ - 稳定页面 Guard Context 和当前页面配置的引用。
21
+ - Toast 消息溢出时清理对应定时器。
22
+ - Footer 异步提交使用同步重入锁,避免快速双击重复提交。
23
+ - 更新性能说明与回归测试。
24
+
25
+ ## 1.0.0 — State isolation and concurrency hardening
26
+
27
+ - Stabilize loading command references independently of loading text changes.
28
+ - Protect asynchronous navigation against stale route identity and unmount.
29
+ - Synchronize route snapshots before dispatch to avoid stale reads within a single tick.
30
+ - Prevent post-unmount Toast and loading updates.
31
+ - Add regression tests for navigation state and lifecycle guards.
32
+
1
33
  - Footer 异步 Done/Cancel 操作自动触发覆盖整个弹窗的 Loading,支持 loadingText 国际化。
2
34
  # Changelog
3
35
 
@@ -23,3 +55,26 @@
23
55
  - 支持 `navigation.setOptions()` 动态更新当前页面标题、Header 和 Footer 配置,并完善路由参数文档。
24
56
 
25
57
  - Added modal-scoped `useToast()` notifications (success, error, warning, info).
58
+
59
+ ### 稳定性增强(第一阶段)
60
+ - 异步路由离开保护:返回、替换、重置、跳转至已有页面时检查将丢弃的脏页面,并防止并发导航。
61
+ - 页面缓存配置:`keepAlive` 与 `maxCachedScreens`,限制非活动页面的挂载数量。
62
+ - `ScreenLayer` 使用 `React.memo`,降低与页面无关的父组件更新带来的渲染开销。
63
+ - 导航操作返回 `Promise<boolean>`,方便判断异步拦截结果。
64
+
65
+
66
+ ### Context subscription isolation
67
+ - Added navigation command/state split and a `useSyncExternalStore` route snapshot store.
68
+ - Added `useModalNavigationCommands()` and `useModalNavigationState()` while retaining compatibility hooks.
69
+ - Stable navigation facade prevents screen props changing solely due to route snapshot updates.
70
+
71
+ ### Context 订阅隔离
72
+ - Loading、Footer、Toast 改用独立 external store,避免各自状态更新引发整个 Navigator 的状态重渲染。
73
+ - 保持现有 hooks 和 UI 行为兼容;增加订阅隔离回归测试和可选 React Profiler 测试。
74
+
75
+ ### React Profiler integration test harness (1.1.6)
76
+ - Added a real React 19 `ModalProvider` / `ModalNavigator` profiler integration suite.
77
+ - Added `npm run test:react` and explicit React testing dependencies.
78
+ - No Context API redesign in this change; performance refactors await measured results.
79
+
80
+ - Fix: Default Header back button now follows the current render stack depth; per-screen `showBackButton` is respected.
package/README.md CHANGED
@@ -557,3 +557,160 @@ toast.clear(); // 清空当前弹窗消息
557
557
  ```
558
558
 
559
559
  `duration` 单位毫秒;设为 `0` 则不自动消失。`dismissible: false` 隐藏关闭按钮。消息区域始终限制在弹窗内,弹窗关闭时通知自动销毁。国际化文案由业务侧调用 `t()` 后传入。
560
+
561
+ ### 导航保护与页面缓存
562
+
563
+ 使用 `useModalUnsavedChanges(dirty, { message, onBeforeDiscard })` 注册当前页面的未保存数据保护。现在内部 `navigate`、`goBack`、`replace`、`reset` 以及弹窗关闭/替换都检查将被移除的脏页面。`navigate` 进入新页面不会丢弃当前 KeepAlive 页面,因此不触发丢弃确认;返回或重置时会检查。异步确认期间拒绝重复导航。
564
+
565
+ 导航方法 `navigate`、`goBack`、`replace`、`reset` 现在返回 `Promise<boolean>`,可通过 `await` 判断是否被拦截:
566
+
567
+ ```jsx
568
+ const { navigation } = useModal();
569
+ const moved = await navigation.goBack({ saved: true });
570
+ if (!moved) console.log('用户取消了离开操作');
571
+ ```
572
+
573
+ 缓存可按页面与弹窗共同控制:
574
+
575
+ ```jsx
576
+ const registry = {
577
+ userModal: {
578
+ initialRoute: 'List',
579
+ modalOptions: { maxCachedScreens: 2 },
580
+ screens: {
581
+ List: { component: List, keepAlive: true },
582
+ Edit: { component: Edit, keepAlive: false },
583
+ Detail: { component: Detail, keepAlive: true },
584
+ },
585
+ },
586
+ };
587
+ ```
588
+
589
+ `keepAlive` 默认 `true`,`maxCachedScreens` 默认无限制;设置为 `0` 仅挂载当前页面。未缓存页面重新进入时会重新挂载、重新初始化局部状态;导航栈和路由参数仍然保留。缓存限制按当前导航栈中靠近栈顶的页面计算,并非 LRU。
590
+
591
+
592
+ ### 并发安全与状态隔离
593
+
594
+ 导航操作 `navigate`、`goBack`、`replace`、`reset` 返回 `Promise<boolean>`,应使用 `await` 获取实际结果。组件在异步离开确认期间拒绝重复导航,并在确认返回后检查页面身份;关闭或卸载的实例不会继续提交导航。Loading 的命令引用保持稳定,文案更新不会重新创建命令对象。
595
+
596
+ ```jsx
597
+ const { navigation } = useModal();
598
+ const handleBack = async () => {
599
+ const didNavigate = await navigation.goBack({ updated: true });
600
+ if (!didNavigate) return;
601
+ };
602
+ ```
603
+
604
+ 导航、Toast 和 Loading 均由弹窗实例管理,弹窗关闭时清理未完成的通知定时器和任务。
605
+
606
+
607
+ ## Context 订阅拆分(性能)
608
+
609
+ 需要导航操作但不读取当前路由的页面,优先使用 `useModalNavigationCommands()`;该 Hook 不订阅导航栈变化。
610
+
611
+ ```jsx
612
+ import { useModalNavigationCommands, useModalNavigationState } from 'react-modal-navigation';
613
+
614
+ function NextButton() {
615
+ const { navigate } = useModalNavigationCommands();
616
+ return <button onClick={() => navigate('UserDetail', { id: 1 })}>详情</button>;
617
+ }
618
+
619
+ function Breadcrumb() {
620
+ const { currentRoute, canGoBack, stack } = useModalNavigationState();
621
+ return <span>{currentRoute?.name} · {stack.length} · {canGoBack ? '可返回' : '首页'}</span>;
622
+ }
623
+ ```
624
+
625
+ `useModal()` 和 `useModalNavigation()` 保持兼容,会订阅导航状态;仅需要操作方法时推荐使用拆分后的 Hook。弹窗级 Toast/Loading 仍有独立的状态更新路径,后续可通过 React Profiler 继续验证渲染次数。
626
+
627
+ ## 独立状态订阅(性能优化)
628
+
629
+ Loading、Footer 和 Toast 分别使用独立的 external store(`useSyncExternalStore`)。
630
+ 通知 Toast 不会更新 Footer/Loading 的状态订阅;更新 Footer 配置不会通知 Toast/Loading;Loading 文案变化只通知 Loading 订阅者。
631
+ `useToast()` 返回稳定的命令接口;`useModalFooter()` 注册页面配置;`useModalLoading()` 仍兼容原 API,并订阅 `isLoading`。
632
+ 导航命令与导航状态继续通过 `useModalNavigationCommands()`、`useModalNavigationState()` 分离。
633
+
634
+ `tests/react-profiler.test.mjs` 提供 React Profiler 的更新次数回归测试;需在测试环境额外安装与 React 19 匹配的 `react-test-renderer`,否则测试明确标记为跳过。此测试验证独立 store 的消费者隔离,不等同于完整浏览器页面性能基准。
635
+
636
+ ## 1.1.6 性能与稳定性优化
637
+
638
+ - 修复 `ModalNavigator` 缺少 `useState` 导入导致的运行时异常。
639
+ - 稳定页面级导航保护 Context 值,减少缓存页面无关重渲染。
640
+ - 缓存当前页面的合并配置,减少 Header / Footer 不必要的属性引用变化。
641
+ - Toast 超过 5 条时主动清理被淘汰消息的计时器,避免多余回调。
642
+ - Footer 使用同步锁阻止连续点击触发并行提交。
643
+ - 保留原有 API;建议在实际业务中使用 React Profiler 验证缓存页面的提交次数。
644
+
645
+ ### React 19 实际组件渲染性能回归测试
646
+
647
+ 本项目提供 `tests/react-profiler.integration.test.jsx`,测试会挂载真实的 `ModalProvider`、`ModalNavigator`、KeepAlive 页面及 Toast/Loading Hook,并用 React Profiler 统计提交次数,而不是只测试模拟 Store。
648
+
649
+ ```bash
650
+ npm install
651
+ npm run test:react
652
+ ```
653
+
654
+ 测试覆盖 Toast 更新时当前页面的提交次数、缓存页面在 Toast 与 Loading 更新时的提交次数。**此测试需要完整安装 React 19、Vitest、jsdom 等依赖。** 如果依赖安装失败或测试没有执行,不能据此宣称通过,也不能将“0 次重渲染”视为已验证结论。运行结果应作为是否进一步拆分 Context 的依据。
655
+
656
+
657
+ ## 1.1.6 使用体验扩展
658
+
659
+ ```jsx
660
+ import { useModal, useModalRoute, useModalParams, useModalFooter, useToast } from 'react-modal-navigation';
661
+
662
+ function EditDevice() {
663
+ const { navigation } = useModal();
664
+ const { name, key } = useModalRoute();
665
+ const { deviceId } = useModalParams();
666
+ const toast = useToast();
667
+ useModalFooter({
668
+ actions: [
669
+ { key: 'cancel', label: '取消', variant: 'secondary', onClick: () => navigation.goBack() },
670
+ { key: 'save', label: '保存', variant: 'primary', loadingText: '保存中...',
671
+ onClick: () => toast.promise(() => saveDevice(deviceId), { loading: '正在保存', success: '保存成功', error: '保存失败' }) },
672
+ ],
673
+ });
674
+ const pickDevice = async () => {
675
+ const result = await navigation.navigateAsync('DevicePicker');
676
+ if (result.status === 'returned') console.log(result.value);
677
+ };
678
+ return <button onClick={pickDevice}>选择设备</button>;
679
+ }
680
+ // DevicePicker: navigation.goBack(selectedDevice)
681
+ ```
682
+
683
+ `navigateAsync()` 返回 `{status:'returned',value}`、`{status:'removed'}`、`{status:'cancelled'}` 或 `{status:'dismissed'}`,不会因页面被替换或弹窗关闭而无限等待。`toast.promise()` 保留原始 Promise 的返回值和异常。`actions` 与旧版 `done/cancel` 二选一;各按钮有独立 pending 状态。
684
+
685
+
686
+ ## v1.1.6 架构与性能优化
687
+
688
+ Loading 与 Toast 控制逻辑已从 `ModalNavigator` 提取为独立控制器,原有 `useModalLoading()`、`useToast()`、Footer 与导航 API 保持不变。
689
+
690
+ 只需控制 Loading、无需读取状态时,建议使用:
691
+
692
+ ```jsx
693
+ import { useModalLoadingCommands, useModalLoadingState } from 'react-modal-navigation';
694
+
695
+ function SaveButton() {
696
+ const { showLoading, hideLoading } = useModalLoadingCommands();
697
+ const save = async () => {
698
+ const token = showLoading('保存中...');
699
+ try { await saveData(); } finally { hideLoading(token); }
700
+ };
701
+ return <button onClick={save}>保存</button>;
702
+ }
703
+
704
+ function LoadingIndicator() {
705
+ const { visible } = useModalLoadingState();
706
+ return visible ? <span>正在处理</span> : null;
707
+ }
708
+ ```
709
+
710
+ 声明式 Footer 的按钮配置现在使用逐属性比较,避免 JSON 序列化丢失函数属性或遗漏新增配置字段。异步操作仍需要在业务层使用 `try/finally` 管理自身资源。
711
+
712
+ 类型增强:可通过 `TypedModalNavigation<Routes>` 为项目提供路由名及参数的静态检查。
713
+
714
+ ### 返回按钮显示规则(1.1.6 修复)
715
+
716
+ 默认 Header 在导航栈超过一页时自动显示返回按钮。使用 `navigation.navigate('Detail')` 推入页面;`replace` / `reset` 不增加可返回的历史。可通过 `showBackButton: false` 隐藏,页面 `setOptions({ showBackButton: true })` 可覆盖默认设置。如果使用 `renderHeader` 自定义整个 Header,需要自行渲染返回按钮。
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),e=require("react"),De=require("react-dom"),Ne=e.createContext(null),Ce=e.createContext(null),xe=e.createContext(null),Ee=e.createContext(null),Le=e.createContext(null),Pe=e.createContext(null);let Ae=0;const ke=(t,n)=>({key:`modal-route-${++Ae}`,name:t,params:n??{}}),Be=(t,n)=>[ke(t,n)];function $e(t,n){switch(n.type){case"RESET":return Be(n.name,n.params);case"NAVIGATE":{const o=t.findIndex(a=>a.name===n.name);return o<0?[...t,ke(n.name,n.params)]:t.slice(0,o+1).map((a,c)=>c===o?{...a,params:n.params??{}}:a)}case"SET_OPTIONS":return t.map((o,a)=>a===t.length-1?{...o,options:{...o.options??{},...n.options??{}}}:o);case"SET_PARAMS":return t.map((o,a)=>a===t.length-1?{...o,params:{...o.params??{},...n.params??{}}}:o);case"BACK":return t.length>1?t.slice(0,-1):t;case"REPLACE":return t.length?[...t.slice(0,-1),ke(n.name,n.params)]:t;default:return t}}const Me=()=>{if(typeof document>"u")return"light";const t=document.documentElement,n=document.body;return t.classList.contains("dark")||n.classList.contains("dark")||t.dataset.theme==="dark"||n.dataset.theme==="dark"?"dark":t.classList.contains("light")||n.classList.contains("light")||t.dataset.theme==="light"||n.dataset.theme==="light"?"light":window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"};let fe=0;const se=[];let ve=null;function Ie(){if(fe++,fe===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),b=parseFloat(getComputedStyle(o).paddingRight)||0;c&&(o.style.paddingRight=`${b+c}px`),o.style.setProperty("--modal-scrollbar-width",`${c}px`),n.style.overflow="hidden",o.style.overflow="hidden",ve=()=>{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 t=!1;return()=>{t||(t=!0,fe=Math.max(0,fe-1),fe||(ve?.(),ve=null))}}const ze='a[href],button:not([disabled]),input:not([disabled]),textarea:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])',He=t=>!t.closest('[inert], [hidden], [aria-hidden="true"]')&&t.getClientRects().length>0&&getComputedStyle(t).visibility!=="hidden"&&getComputedStyle(t).display!=="none";function Ge({dialogRef:t,options:n,requestClose:o,children:a,exiting:c=!1}){const b=e.useRef(null),g=e.useRef(null),E=e.useRef(o);E.current=o;const p=e.useRef(n.closeOnEsc);p.current=n.closeOnEsc;const[w,M]=e.useState(Me),x=n.theme==="light"||n.theme==="dark"?n.theme:w;e.useEffect(()=>{if(n.theme==="light"||n.theme==="dark")return;const P=()=>M(Me()),U=new MutationObserver(P);for(const Z of[document.documentElement,document.body])U.observe(Z,{attributes:!0,attributeFilter:["class","data-theme"]});const N=window.matchMedia?.("(prefers-color-scheme: dark)");return N?.addEventListener?.("change",P),P(),()=>{U.disconnect(),N?.removeEventListener?.("change",P)}},[n.theme]),e.useEffect(()=>{g.current=document.activeElement;const P=Ie(),U=b.current;se.push(U),t.current?.focus({preventScroll:!0});const N=k=>{const C=t.current;if(!C||se.at(-1)!==U)return;if(k.key==="Escape"&&p.current!==!1){k.preventDefault(),E.current("escape");return}if(k.key!=="Tab")return;const L=[...C.querySelectorAll(ze)].filter(He);if(!L.length){k.preventDefault(),C.focus();return}const V=L[0],D=L.at(-1);C.contains(document.activeElement)?k.shiftKey&&(document.activeElement===V||document.activeElement===C)?(k.preventDefault(),D.focus()):!k.shiftKey&&(document.activeElement===D||document.activeElement===C)&&(k.preventDefault(),V.focus()):(k.preventDefault(),(k.shiftKey?D:V).focus())},Z=k=>{se.at(-1)===U&&t.current&&!t.current.contains(k.target)&&t.current.focus({preventScroll:!0})};return document.addEventListener("keydown",N),document.addEventListener("focusin",Z),()=>{document.removeEventListener("keydown",N),document.removeEventListener("focusin",Z);const k=se.at(-1)===U,C=se.indexOf(U);if(C!==-1&&se.splice(C,1),P(),k){const L=g.current;L?.isConnected&&!L.closest("[inert], [hidden]")?L.focus?.({preventScroll:!0}):se.at(-1)?.querySelector("[role=dialog]")?.focus?.({preventScroll:!0})}}},[t]);const v=n.backgroundColor??n.backgroudColor,d=typeof v=="string"?v:v?.[x],h=typeof d=="string"&&/^(#|rgb\(|rgba\(|hsl\(|hsla\(|oklch\(|color\(|var\()/.test(d.trim())?d:null,F={sm:400,md:560,lg:720,xl:960,full:"100%"},S=["center","left","right","top","bottom"].includes(n.placement)?n.placement:"right",I=P=>typeof P=="number"?`${P}px`:P,j=I(n.width??F[n.size]??460),T=I(n.height),q=I(n.maxHeight),O=I(n.maxWidth),z=Number(n.viewportGap??5),G=Number.isFinite(z)?Math.max(0,z):5,K=typeof n.borderRadius=="number"?`${n.borderRadius}px`:n.borderRadius??"12px";return De.createPortal(u.jsx("div",{ref:b,className:`pmn-overlay ${c?"pmn-exiting":"pmn-entering"} ${n.animation===!1?"pmn-no-animation":""} pmn-place-${S} ${n.mobileFullscreen?"pmn-mobile-fullscreen":""}`,style:{padding:G,"--pmn-animation-duration":`${Math.min(1e3,Math.max(0,Number(n.animationDuration??220)||0))}ms`},onMouseDown:P=>{P.target===P.currentTarget&&n.closeOnOverlay===!0&&E.current("overlay")},children:u.jsx("section",{ref:t,tabIndex:-1,role:"dialog","aria-modal":"true","aria-label":n.ariaLabel??"Dialog","data-modal-theme":x,className:`pmn-dialog ${x==="dark"?"dark":""} ${!h&&d?d:""} ${n.className??""}`,style:{"--pmn-width":j,"--pmn-gap":`${G}px`,...T!==void 0?{"--pmn-height":T}:{},...q!==void 0?{"--pmn-max-height":q}:{},...O!==void 0?{"--pmn-max-width":O}:{},borderRadius:K,...h?{backgroundColor:h}:{}},children:a})}),document.body)}function Se({back:t}){return u.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"currentColor",strokeWidth:"2",children:t?u.jsx("path",{d:"m15 18-6-6 6-6"}):u.jsx("path",{d:"M18 6 6 18M6 6l12 12"})})}function Ke({options:t,screen:n,route:o,navigation:a,requestClose:c,translate:b}){if(t.showHeader===!1)return null;const g=b??(v=>v),E=n.showTitle??t.showTitle??!0,p=typeof n.title=="function"?n.title({t:g,route:o,navigation:a}):n.title??o.name,w={route:o,navigation:a,close:c,canGoBack:a.canGoBack,title:p,t:g},M=n.renderHeader??t.renderHeader;if(M)return M(w);const x=n.renderHeaderRight??t.renderHeaderRight;return u.jsxs("header",{className:`pmn-header ${n.showHeaderBorder??t.showHeaderBorder?"pmn-border-bottom":""} ${t.headerClassName??""}`,children:[t.showBackButton!==!1&&a.canGoBack&&u.jsx("button",{type:"button",className:"pmn-icon-button","aria-label":g("modal.back"),onClick:()=>a.goBack(),children:u.jsx(Se,{back:!0})}),E?u.jsx("h2",{children:p}):u.jsx("div",{className:"pmn-header-spacer"}),x?.(w),t.showCloseButton!==!1&&u.jsx("button",{type:"button",className:"pmn-icon-button","aria-label":g("modal.close"),onClick:()=>c("header"),children:u.jsx(Se,{})})]})}function Ue({screen:t,options:n,override:o,route:a,navigation:c,requestClose:b,translate:g,onError:E,loadingApi:p}){const[w,M]=e.useState(!1),x=g??(z=>z),v={...n,...t,...o},{showFooter:d,renderFooter:h,done:F,cancel:S,cancle:I}=v,j=S??I,T={route:a,navigation:c,close:b,t:x};if(d===!1)return null;const q=`pmn-footer ${v.showFooterBorder?"pmn-border-top":""} ${v.footerClassName??""}`;if(typeof h=="function")return u.jsx("footer",{className:q,children:h({...T,pending:w})});if(typeof F!="function"&&typeof j!="function")return null;const O=async z=>{if(w||typeof z!="function")return;M(!0);const G=p?.begin(a.key,v.loadingText??x("modal.processing"));try{await z(T)}catch(K){E?.(K,{phase:"footer",route:a})}finally{p?.end(a.key,G),M(!1)}};return u.jsxs("footer",{className:q,children:[typeof j=="function"&&u.jsx("button",{type:"button",disabled:w,onClick:()=>O(j),className:"pmn-button pmn-button-secondary",children:v.cancelText??x("modal.cancel")}),typeof F=="function"&&u.jsx("button",{type:"button",disabled:w||v.doneDisabled===!0,onClick:()=>O(F),className:"pmn-button pmn-button-primary",children:w?v.loadingText??x("modal.processing"):v.doneText??x("modal.done")})]})}function We({loading:t,translate:n}){if(!t.visible)return null;const a=(n??(b=>b))("modal.loading"),c=t.text??(a==="modal.loading"?"加载中...":a);return u.jsx("div",{className:"pmn-loading-overlay",role:"status","aria-live":"polite","aria-busy":"true",children:u.jsxs("div",{className:"pmn-loading-content",children:[u.jsx("span",{className:"pmn-spinner","aria-hidden":"true"}),c&&u.jsx("span",{className:"pmn-loading-text",children:c})]})})}class Ye extends e.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?u.jsxs("div",{role:"alert",className:"pmn-error-screen",children:[u.jsx("strong",{children:"页面加载失败"}),u.jsx("p",{children:this.state.error.message}),u.jsx("button",{type:"button",className:"pmn-button pmn-button-secondary",onClick:()=>this.setState({error:null}),children:"重试"})]}):this.props.children}}const _e={success:"✓",error:"×",warning:"!",info:"i"};function Qe({items:t,dismiss:n}){return t.length?u.jsx("div",{className:"pmn-toast-region","aria-label":"Notifications",children:t.map(o=>u.jsxs("div",{className:`pmn-toast pmn-toast-${o.type}`,role:o.type==="error"||o.type==="warning"?"alert":"status",children:[u.jsx("span",{className:"pmn-toast-symbol","aria-hidden":"true",children:_e[o.type]}),u.jsx("span",{className:"pmn-toast-message",children:o.message}),o.dismissible&&u.jsx("button",{type:"button",className:"pmn-toast-close","aria-label":"Dismiss notification",onClick:()=>n(o.id),children:"×"})]},o.id))}):null}function Ve({route:t,screen:n,navigation:o,focused:a,resultEvent:c,setFooter:b,loadingApi:g,bodyClassName:E,notifyError:p,registerDirtyGuard:w}){const M=n.component,x=e.useMemo(()=>({isFocused:a,resultEvent:c,routeKey:t.key,setFooter:b}),[a,c,t.key,b]),v=e.useMemo(()=>({isLoading:a&&g.isLoading,setLoading:(d,h)=>g.setScreenLoading(t.key,d,h),showLoading:d=>g.begin(t.key,d),hideLoading:d=>g.end(t.key,d)}),[a,g,t.key]);return u.jsx(Le.Provider,{value:{routeKey:t.key,registerDirtyGuard:w},children:u.jsx(xe.Provider,{value:x,children:u.jsx(Ee.Provider,{value:v,children:u.jsx("div",{hidden:!a,inert:!a,"data-modal-route-key":t.key,tabIndex:-1,className:`pmn-body ${E??""}`,children:u.jsx(Ye,{route:t,onError:p,children:u.jsx(M,{route:t,navigation:o})})})})})})}function Fe({config:t,initialScreen:n,params:o,options:a,translate:c,onRequestClose:b,onOpened:g,registerLoading:E,notifyError:p,error:w,clearError:M,registerDirtyGuard:x,exiting:v=!1}){const[d,h]=e.useReducer($e,null,()=>Be(n??t.initialRoute,o)),[F,S]=e.useState([]),I=e.useRef(0),j=e.useRef(new Map),T=e.useCallback(r=>{clearTimeout(j.current.get(r)),j.current.delete(r),S(i=>i.filter(m=>m.id!==r))},[]),q=e.useCallback((r,i={})=>{if(typeof r!="string"||!r.trim())throw new TypeError("[react-modal-navigation] toast message must be a non-empty string");const m=typeof i=="string"?{type:i}:i??{},_=["success","error","warning","info"].includes(m.type)?m.type:"info",be=++I.current,je=Number.isFinite(m.duration)?Math.max(0,m.duration):3e3;return S(Oe=>[...Oe,{id:be,message:r,type:_,dismissible:m.dismissible!==!1}].slice(-5)),je>0&&j.current.set(be,setTimeout(()=>T(be),je)),be},[T]),O=e.useMemo(()=>{const r=(i,m)=>q(i,m);for(const i of["success","error","warning","info"])r[i]=(m,_={})=>q(m,{..._,type:i});return r.dismiss=T,r.clear=()=>{for(const i of j.current.values())clearTimeout(i);j.current.clear(),S([])},r},[q,T]);e.useEffect(()=>()=>{for(const r of j.current.values())clearTimeout(r);j.current.clear()},[]);const[z,G]=e.useState({}),[K,P]=e.useState({}),[,U]=e.useState(0),N=e.useRef(new Map),Z=e.useRef(0),k=e.useRef(new Map),C=e.useRef(null),L=e.useRef(null),V=e.useRef(!1),D=e.useRef(!1),ce=e.useRef(0),R=d.at(-1),A=R.key,de=e.useRef(A);de.current=A;const W=t.screens,Q=e.useCallback(()=>U(r=>r+1),[]),ee=e.useCallback((r,i)=>{if(r!=="global"&&de.current!==r)return null;const m=++Z.current;return N.current.set(m,{owner:r,text:i}),Q(),m},[Q]),J=e.useCallback((r,i)=>{if(i!=null)N.current.get(i)?.owner===r&&N.current.delete(i);else for(const[m,_]of N.current)_.owner===r&&N.current.delete(m);Q()},[Q]),X=e.useCallback((r,i)=>{r?(J("global"),ee("global",i)):J("global")},[ee,J]),me=e.useCallback((r,i,m)=>{i?(J(r),ee(r,m)):J(r)},[ee,J]),ie=[...N.current.values()],te={visible:ie.length>0,text:ie.at(-1)?.text??null,count:ie.length},pe=e.useRef(te);pe.current=te;const le=e.useMemo(()=>({isLoading:te.visible,setLoading:X,setScreenLoading:me,begin:ee,end:J}),[te.visible,X,me,ee,J]),ue=e.useRef(E);ue.current=E,e.useEffect(()=>(ue.current?.({setLoading:X}),()=>ue.current?.(null)),[X]);const he=e.useCallback((r,i)=>P(m=>{if(i===null){if(!(r in m))return m;const _={...m};return delete _[r],_}return m[r]===i?m:{...m,[r]:i}}),[]),ne=e.useCallback(()=>{const r=document.activeElement;if(!(r instanceof HTMLElement)||!C.current?.contains(r))return;const i=r.closest("[data-modal-route-key]");i&&k.current.set(i.dataset.modalRouteKey,r),C.current.focus({preventScroll:!0})},[]),ge=e.useCallback(r=>{if(!Object.prototype.hasOwnProperty.call(W,r))throw new Error(`[react-modal-navigation] Unknown modal screen: ${r}`)},[W]),s=e.useCallback((r,i)=>{try{Promise.resolve(a[r]?.(i)).catch(m=>p(m,{phase:r}))}catch(m){p(m,{phase:r})}},[a,p]),l=e.useCallback((r,i,m)=>{ge(i),ne(),h({type:r,name:i,params:m})},[ge,ne]),y=e.useCallback((r,i)=>l("NAVIGATE",r,i),[l]),f=e.useCallback((r,i)=>l("REPLACE",r,i),[l]),$=e.useCallback((r,i)=>{G({}),l("RESET",r,i)},[l]),B=e.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})},[]),H=e.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})},[]),re=e.useCallback(r=>{if(d.length<=1||V.current)return!1;if(V.current=!0,r!==void 0){const i=d.at(-2);G(m=>({...m,[i.key]:{id:++ce.current,data:r}}))}return ne(),h({type:"BACK"}),!0},[d,ne]),Y=e.useCallback((r,i)=>pe.current.visible&&a.lockCloseWhileLoading!==!1?Promise.resolve(!1):b(r,i,{route:R,stack:d}),[a.lockCloseWhileLoading,b,R,d]),oe=e.useCallback(r=>Y("api",r),[Y]),ae=e.useMemo(()=>({navigate:y,replace:f,reset:$,setParams:B,setOptions:H,goBack:re,close:oe,setLoading:X,canGoBack:d.length>1,stack:d,currentRoute:R}),[y,f,$,B,H,re,oe,X,d,R]);return e.useLayoutEffect(()=>{V.current=!1;const r=[...C.current?.querySelectorAll("[data-modal-route-key]")??[]].find(_=>_.dataset.modalRouteKey===A);if(!r)return;const i=k.current.get(A);(i?.isConnected&&r.contains(i)&&!i.matches(":disabled")&&!i.closest("[inert], [hidden]")?i:r).focus({preventScroll:!0})},[A]),e.useEffect(()=>{let r=!1;for(const[m,_]of N.current)_.owner!=="global"&&_.owner!==A&&(N.current.delete(m),r=!0);r&&Q();const i=new Set(d.map(m=>m.key));for(const m of k.current.keys())i.has(m)||k.current.delete(m)},[A,d,Q]),e.useEffect(()=>{if(L.current?.key!==A){if(L.current){const r={from:L.current,to:R,stack:d};s("onBlur",{route:L.current,...r}),s("onNavigate",r),s("onRouteChange",r)}s("onFocus",{route:R,stack:d}),L.current=R}},[R,A,d,s]),e.useEffect(()=>()=>{N.current.clear(),k.current.clear()},[]),e.useEffect(()=>{D.current||(D.current=!0,g?.({route:R,stack:d}))},[]),u.jsx(Pe.Provider,{value:O,children:u.jsx(Ce.Provider,{value:ae,children:u.jsx(Ee.Provider,{value:le,children:u.jsxs(Ge,{dialogRef:C,options:a,requestClose:Y,exiting:v,children:[u.jsx(Ke,{options:a,screen:{...W[R.name],...R.options??{}},route:R,navigation:ae,requestClose:Y,translate:c}),u.jsx("main",{className:"pmn-main",children:d.map(r=>u.jsx(Ve,{route:r,screen:W[r.name],navigation:ae,focused:r.key===A,resultEvent:z[r.key]??null,bodyClassName:a.bodyClassName,setFooter:he,loadingApi:le,notifyError:p,registerDirtyGuard:x},r.key))}),u.jsx(Ue,{screen:{...W[R.name],...R.options??{}},options:a,override:K[A],route:R,navigation:ae,requestClose:Y,translate:c,onError:p,loadingApi:le},A),u.jsx(We,{loading:te,translate:c}),u.jsx(Qe,{items:F,dismiss:T}),w&&u.jsxs("div",{className:"pmn-error",role:"alert",children:[u.jsx("span",{children:w.message||String(w)}),u.jsx("button",{type:"button",onClick:M,"aria-label":"Dismiss error",children:"×"})]})]})})})})}const Je=".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}}.pmn-toast-region{position:absolute;top:56px;left:12px;right:12px;z-index:80;display:flex;flex-direction:column;align-items:center;gap:8px;pointer-events:none;max-height:calc(100% - 72px);overflow:hidden}.pmn-toast{pointer-events:auto;display:flex;align-items:flex-start;gap:10px;width:max-content;max-width:100%;min-width:min(260px,100%);padding:11px 13px;border:1px solid var(--pmn-border);border-radius:9px;background:var(--pmn-surface);color:var(--pmn-text);box-shadow:0 5px 18px #0000001a;font-size:13px;line-height:1.5;overflow-wrap:anywhere}.pmn-toast-symbol{flex:0 0 20px;display:grid;place-items:center;width:20px;height:20px;border-radius:50%;font-size:13px;font-weight:700;background:var(--pmn-hover);color:var(--pmn-muted)}.pmn-toast-success .pmn-toast-symbol{background:#dcfce7;color:#15803d}.pmn-toast-error .pmn-toast-symbol{background:#fee2e2;color:#b91c1c}.pmn-toast-warning .pmn-toast-symbol{background:#fef3c7;color:#b45309}.pmn-toast-info .pmn-toast-symbol{background:#dbeafe;color:#1d4ed8}.pmn-toast-message{flex:1;min-width:0;white-space:pre-wrap}.pmn-toast-close{border:0;background:transparent;color:var(--pmn-muted);cursor:pointer;font-size:19px;line-height:18px;padding:0 1px}.pmn-toast-close:hover{color:var(--pmn-text)}",Te="react-modal-navigation-styles",we=new WeakMap;function Xe(){e.useInsertionEffect(()=>{if(typeof document>"u")return;const t=document;let n=we.get(t);if(!n){let o=t.getElementById(Te);const a=!o;o||(o=t.createElement("style"),o.id=Te,o.setAttribute("data-react-modal-navigation",""),o.textContent=Je,t.head.appendChild(o)),n={element:o,owned:a,count:0},we.set(t,n)}return n.count+=1,()=>{n.count-=1,n.count===0&&(n.owned&&n.element.remove(),we.delete(t))}},[])}function ye(t,n,o){if(typeof t=="string"){if(!t.trim())throw new TypeError("[react-modal-navigation] modal name must not be empty");return{name:t,params:n??{},options:o??{}}}if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("[react-modal-navigation] open expects a modal name or a configuration object");const{name:a,screen:c,params:b={},options:g={},...E}=t;if(typeof a!="string"||!a.trim())throw new TypeError("[react-modal-navigation] open config requires a non-empty string name");if(g===null||typeof g!="object"||Array.isArray(g))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:b,options:{...E,...g}}}const Ze={placement:"right",showHeader:!0,showBackButton:!0,showCloseButton:!0,viewportGap:5,borderRadius:12,closeOnOverlay:!1,closeOnEsc:!0},et=t=>({"modal.loading":"加载中...","modal.processing":"处理中...","modal.back":"返回","modal.close":"关闭","modal.cancel":"取消","modal.done":"完成"})[t]??t;function tt({registry:t,children:n,defaultOptions:o={},backgroundColor:a,theme:c,translate:b=et,onError:g,confirmDiscard:E}){Xe();const[p,w]=e.useState(null),[M,x]=e.useState(null),[v,d]=e.useState(0),h=e.useRef(null),F=e.useRef(new Map),S=e.useRef([]),I=e.useRef(null),j=e.useRef(null),T=e.useRef(0),q=e.useRef(null),O=e.useRef(!1),z=e.useRef(0),G=e.useRef(null),K=e.useRef(new Map),[P,U]=e.useState(!1),N=e.useRef(E);N.current=E;const Z=e.useCallback((s,l)=>(K.current.set(s,l),()=>{K.current.get(s)===l&&K.current.delete(s)}),[]),k=e.useCallback(async s=>{for(const l of K.current.values()){if(!l.dirty)continue;if((l.onBeforeDiscard?await l.onBeforeDiscard(s):N.current?await N.current(s):typeof window<"u"&&typeof window.confirm=="function"?window.confirm(l.message||"有未保存的修改,确定放弃吗?"):!1)===!1)return!1}return!0},[]),C=e.useRef(!0),L=e.useRef(null),V=e.useRef(g);V.current=g;const D=e.useCallback((s,l)=>{C.current&&x(s);try{V.current?V.current(s,l):console.error("[react-modal-navigation]",s)}catch(y){console.error("[react-modal-navigation] onError failed",y)}},[]),ce=e.useCallback((s,l)=>{const y=F.current.get(s);F.current.delete(s),y?.(l)},[]),R=e.useCallback(s=>({...Ze,...o,...c!==void 0?{theme:c}:{},...a!==void 0?{backgroundColor:a}:{},...s.config.modalOptions,...s.overrides}),[o,c,a]),A=p?R(p):null,de=e.useRef(null);de.current=A,L.current=A;const W=e.useCallback(async(s="api",l,y={})=>{const f=h.current;if(!f||q.current||O.current)return!1;q.current=f.id,O.current=!0;const $=L.current??R(f),B={...y,reason:s,result:l,name:f.name};try{if(!await k(B)||await $.onBeforeClose?.(B)===!1||h.current?.id!==f.id||!C.current||(U(!0),await new Promise(H=>{const re=$.animation===!1||typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?0:Math.max(0,Number($.animationDuration??220)||0);setTimeout(H,Math.min(re,1e3))}),!C.current||h.current?.id!==f.id))return!1;h.current=null,G.current=null,w(null),U(!1),K.current.clear(),ce(f.id,y.confirmed||l!==void 0?{status:"confirmed",value:l,reason:s}:{status:"dismissed",reason:s});try{await $.onClose?.(B)}catch(H){D(H,{phase:"onClose",name:f.name})}return!0}catch(H){return D(H,{phase:"onBeforeClose",name:f.name}),!1}finally{q.current===f.id&&(q.current=null),O.current=!1,!h.current&&C.current&&queueMicrotask(()=>j.current?.())}},[R,D,ce,k]),Q=e.useCallback(async(s,l={},y={},f,$)=>{const B=t?.[s];if(!B)throw new Error(`[react-modal-navigation] Unknown modal: ${s}`);const H=$??B.initialRoute;if(!B.screens?.[H])throw new Error(`[react-modal-navigation] Unknown initial screen '${H}' in modal '${s}'`);if(!C.current||O.current||q.current)return null;O.current=!0;const re=z.current;try{const Y=h.current;if(Y){const ae=L.current??R(Y),r={reason:"replace",name:Y.name,nextName:s};try{if(!await k(r)||await ae.onBeforeClose?.(r)===!1)return null}catch(i){return D(i,{phase:"onBeforeClose",name:Y.name}),null}if(!C.current||re!==z.current||h.current?.id!==Y.id)return null;h.current=null,G.current=null,w(null),K.current.clear(),ce(Y.id,{status:"replaced",reason:"replace"});try{await ae.onClose?.(r)}catch(i){D(i,{phase:"onClose",name:Y.name})}if(!C.current||re!==z.current)return null}const oe={id:++T.current,name:s,screen:H,params:l,config:B,overrides:y};return h.current=oe,G.current=null,f&&F.current.set(oe.id,f),x(null),w(oe),oe.id}finally{O.current=!1}},[t,R,D,ce,k]);I.current=Q;const ee=e.useCallback(async()=>{if(!C.current||h.current||O.current||q.current)return;const s=S.current.shift();if(s){d(S.current.length);try{const l=await I.current(s.args.name,s.args.params,s.args.options,s.resolveResult,s.args.screen);l===null?(s.resolveResult?.({status:"dismissed",reason:"blocked"}),s.resolveId?.(null),queueMicrotask(()=>j.current?.())):s.resolveId?.(l)}catch(l){s.reject?.(l),queueMicrotask(()=>j.current?.())}}},[]);j.current=ee;const J=e.useCallback((s,l,y)=>{const f=ye(s,l,y);return t?.[f.name]?new Promise(($,B)=>{S.current.push({args:f,resolveId:$,reject:B}),d(S.current.length),queueMicrotask(()=>j.current?.())}):Promise.reject(new Error(`[react-modal-navigation] Unknown modal: ${f.name}`))},[t]),X=e.useCallback((s,l,y)=>{const f=ye(s,l,y);return t?.[f.name]?new Promise(($,B)=>{S.current.push({args:f,resolveResult:$,reject:B}),d(S.current.length),queueMicrotask(()=>j.current?.())}):Promise.reject(new Error(`[react-modal-navigation] Unknown modal: ${f.name}`))},[t]),me=e.useCallback(s=>{if(!s||typeof s!="object"||Array.isArray(s))throw new TypeError("[react-modal-navigation] update expects an options object");const l=h.current;if(!l||O.current)return!1;const y={...l,overrides:{...l.overrides,...s}};return h.current=y,w(y),L.current=R(y),!0},[R]),ie=e.useCallback((s="queue-cleared")=>{const l=S.current.splice(0);d(0);for(const y of l)y.resolveId?.(null),y.resolveResult?.({status:"dismissed",reason:s});return l.length},[]),te=e.useCallback((s,l,y)=>{const f=ye(s,l,y);return Q(f.name,f.params,f.options,void 0,f.screen)},[Q]),pe=e.useCallback((s,l,y)=>{const f=ye(s,l,y);return new Promise(($,B)=>{Q(f.name,f.params,f.options,$,f.screen).then(H=>{H===null&&$({status:"dismissed",reason:"blocked"})},B)})},[Q]),le=e.useCallback(s=>W("api",s),[W]),ue=e.useCallback((s="api")=>W(s),[W]),he=e.useCallback(s=>W("confirm",s,{confirmed:!0}),[W]),ne=e.useCallback((s,l)=>G.current?.setLoading(s,l),[]),ge=e.useMemo(()=>({open:te,openAsync:pe,enqueue:J,enqueueAsync:X,update:me,clearQueue:ie,close:le,dismiss:ue,confirm:he,setLoading:ne,queueSize:v,isOpen:!!p,activeName:p?.name??null,error:M,clearError:()=>x(null)}),[te,pe,J,X,me,ie,le,ue,he,ne,p,M,v]);return e.useEffect(()=>(C.current=!0,()=>{C.current=!1,z.current+=1,h.current=null;for(const l of F.current.values())l({status:"dismissed",reason:"unmount"});F.current.clear(),K.current.clear();const s=S.current.splice(0);for(const l of s)l.resolveId?.(null),l.resolveResult?.({status:"dismissed",reason:"unmount"})}),[]),u.jsxs(Ne.Provider,{value:ge,children:[n,p&&u.jsx(Fe,{config:p.config,initialScreen:p.screen,params:p.params,options:A,translate:b,notifyError:D,error:M,clearError:()=>x(null),registerLoading:s=>{G.current=s},registerDirtyGuard:Z,exiting:P,onRequestClose:W,onOpened:s=>{try{const l=de.current?.onOpen?.(s);Promise.resolve(l).catch(y=>D(y,{phase:"onOpen"}))}catch(l){D(l,{phase:"onOpen"})}}},p.id)]})}function nt(){const t=e.useContext(Ne),n=e.useContext(Ce);if(!t)throw new Error("[react-modal-navigation] useModal requires <ModalProvider>");return e.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{...t,modal:t,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}}}},[t,n])}function rt(){const t=e.useContext(Ce);if(!t)throw new Error("useModalNavigation requires an active modal screen");return t}function Re(){const t=e.useContext(xe);if(!t)throw new Error("useIsFocused must be called inside a modal screen");return t.isFocused}function ot(t){const n=Re();e.useEffect(()=>{if(n)return t()},[n,t])}function at(t){const n=e.useContext(xe);if(!n)throw new Error("useNavigationResult requires an active modal screen");const o=e.useRef(t),a=e.useRef(null);e.useEffect(()=>{o.current=t},[t]),e.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 st(t={}){const n=e.useContext(xe);if(!n)throw new Error("[react-modal-navigation] useModalFooter requires an active modal screen");const{setFooter:o,routeKey:a}=n,c=e.useRef(t);c.current=t;const b=e.useMemo(()=>(...T)=>c.current.done?.(...T),[]),g=e.useMemo(()=>(...T)=>(c.current.cancel??c.current.cancle)?.(...T),[]),E=e.useMemo(()=>(...T)=>c.current.renderFooter?.(...T),[]),p=typeof t.done=="function",w=typeof(t.cancel??t.cancle)=="function",M=typeof t.renderFooter=="function",{showFooter:x,showFooterBorder:v,doneDisabled:d,doneText:h,cancelText:F,loadingText:S,footerClassName:I}=t,j=e.useMemo(()=>({showFooter:x,showFooterBorder:v,doneDisabled:d,doneText:h,cancelText:F,loadingText:S,footerClassName:I,...p?{done:b}:{},...w?{cancel:g}:{},...M?{renderFooter:E}:{}}),[x,v,d,h,F,S,I,p,w,M,b,g,E]);e.useEffect(()=>{o(a,j)},[a,o,j]),e.useEffect(()=>()=>o(a,null),[a,o])}function qe(){const t=e.useContext(Ee);if(!t)throw new Error("[react-modal-navigation] useModalLoading requires an active modal screen");return t}function ct(){const t=qe(),n=Re(),o=e.useRef(!0),a=e.useRef(!1),[c,b]=e.useState(!1),[g,E]=e.useState(null),p=e.useRef(t);return p.current=t,e.useEffect(()=>(o.current=!0,()=>{o.current=!1}),[]),{run:e.useCallback(async(M,x={})=>{if(a.current)return{status:"busy"};if(typeof M!="function")throw new TypeError("[react-modal-navigation] run requires a function");a.current=!0,o.current&&(b(!0),E(null));const v=p.current.showLoading(x.loadingText);try{const d=await M();return o.current&&await x.onSuccess?.(d),{status:"success",value:d}}catch(d){if(o.current){E(d);try{await x.onError?.(d)}catch(h){console.error("[react-modal-navigation] onError failed",h)}}if(x.throwOnError)throw d;return{status:"error",error:d}}finally{v!=null&&p.current.hideLoading(v),a.current=!1,o.current&&b(!1)}},[]),pending:c,error:g,clearError:()=>E(null),isFocused:n}}function it(t,n={}){const o=e.useContext(Le);if(!o)throw new Error("[react-modal-navigation] useModalUnsavedChanges must be used inside a modal screen");const a=e.useRef({dirty:t,...n});a.current={dirty:t,...n};const{routeKey:c,registerDirtyGuard:b}=o;e.useEffect(()=>b(c,{get dirty(){return!!a.current.dirty},get message(){return a.current.message},get onBeforeDiscard(){return a.current.onBeforeDiscard}}),[c,b])}const lt=()=>{const t=e.useContext(Pe);if(!t)throw new Error("[react-modal-navigation] useToast requires an active modal");return t};exports.ModalNavigator=Fe;exports.ModalProvider=tt;exports.useFocusEffect=ot;exports.useIsFocused=Re;exports.useModal=nt;exports.useModalFooter=st;exports.useModalLoading=qe;exports.useModalNavigation=rt;exports.useModalTask=ct;exports.useModalUnsavedChanges=it;exports.useNavigationResult=at;exports.useToast=lt;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),e=require("react"),rt=require("react-dom"),We=e.createContext(null),ot=e.createContext(null),Me=e.createContext(null),je=e.createContext(null),Ye=e.createContext(null),_e=e.createContext(null),Fe=e.createContext(null),Oe=e.createContext(null),De=e.createContext(null),at=e.createContext(null),st=e.createContext(null),Ve=e.createContext(null);function ct(t){let n=t;const o=new Set;return{getSnapshot:()=>n,subscribe:r=>(o.add(r),()=>o.delete(r)),publish(r){if(n!==r){n=r;for(const i of[...o])i()}},listenerCount:()=>o.size}}function Pe(t){let n=t;const o=new Set;return{getSnapshot:()=>n,subscribe:r=>(o.add(r),()=>o.delete(r)),publish(r){if(!Object.is(n,r)){n=r;for(const i of[...o])i()}},listenerCount:()=>o.size}}let it=0;const qe=(t,n)=>({key:`modal-route-${++it}`,name:t,params:n??{}}),Qe=(t,n)=>[qe(t,n)];function Ee(t,n){switch(n.type){case"RESET":return Qe(n.name,n.params);case"NAVIGATE":{const o=t.findIndex(r=>r.name===n.name);return o<0?[...t,qe(n.name,n.params)]:t.slice(0,o+1).map((r,i)=>i===o?{...r,params:n.params??{}}:r)}case"SET_OPTIONS":return t.map((o,r)=>r===t.length-1?{...o,options:{...o.options??{},...n.options??{}}}:o);case"SET_PARAMS":return t.map((o,r)=>r===t.length-1?{...o,params:{...o.params??{},...n.params??{}}}:o);case"BACK":return t.length>1?t.slice(0,-1):t;case"REPLACE":return t.length?[...t.slice(0,-1),qe(n.name,n.params)]:t;default:return t}}function ut(t,n,o=1/0){const r=o===1/0?1/0:Math.max(0,Math.floor(Number(o)||0)),i=t.slice(0,-1).filter(d=>n[d.name]?.keepAlive!==!1),g=new Set((r===0?[]:i.slice(-r)).map(d=>d.key));return t.filter((d,m)=>m===t.length-1||g.has(d.key))}const Ke=()=>{if(typeof document>"u")return"light";const t=document.documentElement,n=document.body;return t.classList.contains("dark")||n.classList.contains("dark")||t.dataset.theme==="dark"||n.dataset.theme==="dark"?"dark":t.classList.contains("light")||n.classList.contains("light")||t.dataset.theme==="light"||n.dataset.theme==="light"?"light":window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"};let ve=0;const ue=[];let Be=null;function lt(){if(ve++,ve===1){const n=document.documentElement,o=document.body,r={html:n.style.overflow,body:o.style.overflow,padding:o.style.paddingRight,width:o.style.getPropertyValue("--modal-scrollbar-width")},i=Math.max(0,window.innerWidth-n.clientWidth),g=parseFloat(getComputedStyle(o).paddingRight)||0;i&&(o.style.paddingRight=`${g+i}px`),o.style.setProperty("--modal-scrollbar-width",`${i}px`),n.style.overflow="hidden",o.style.overflow="hidden",Be=()=>{n.style.overflow=r.html,o.style.overflow=r.body,o.style.paddingRight=r.padding,r.width?o.style.setProperty("--modal-scrollbar-width",r.width):o.style.removeProperty("--modal-scrollbar-width")}}let t=!1;return()=>{t||(t=!0,ve=Math.max(0,ve-1),ve||(Be?.(),Be=null))}}const dt='a[href],button:not([disabled]),input:not([disabled]),textarea:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])',mt=t=>!t.closest('[inert], [hidden], [aria-hidden="true"]')&&t.getClientRects().length>0&&getComputedStyle(t).visibility!=="hidden"&&getComputedStyle(t).display!=="none";function ft({dialogRef:t,options:n,requestClose:o,children:r,exiting:i=!1}){const g=e.useRef(null),d=e.useRef(null),m=e.useRef(o);m.current=o;const f=e.useRef(n.closeOnEsc);f.current=n.closeOnEsc;const[x,R]=e.useState(Ke),y=n.theme==="light"||n.theme==="dark"?n.theme:x;e.useEffect(()=>{if(n.theme==="light"||n.theme==="dark")return;const b=()=>R(Ke()),M=new MutationObserver(b);for(const F of[document.documentElement,document.body])M.observe(F,{attributes:!0,attributeFilter:["class","data-theme"]});const q=window.matchMedia?.("(prefers-color-scheme: dark)");return q?.addEventListener?.("change",b),b(),()=>{M.disconnect(),q?.removeEventListener?.("change",b)}},[n.theme]),e.useEffect(()=>{d.current=document.activeElement;const b=lt(),M=g.current;ue.push(M),t.current?.focus({preventScroll:!0});const q=j=>{const W=t.current;if(!W||ue.at(-1)!==M)return;if(j.key==="Escape"&&f.current!==!1){j.preventDefault(),m.current("escape");return}if(j.key!=="Tab")return;const N=[...W.querySelectorAll(dt)].filter(mt);if(!N.length){j.preventDefault(),W.focus();return}const Q=N[0],J=N.at(-1);W.contains(document.activeElement)?j.shiftKey&&(document.activeElement===Q||document.activeElement===W)?(j.preventDefault(),J.focus()):!j.shiftKey&&(document.activeElement===J||document.activeElement===W)&&(j.preventDefault(),Q.focus()):(j.preventDefault(),(j.shiftKey?J:Q).focus())},F=j=>{ue.at(-1)===M&&t.current&&!t.current.contains(j.target)&&t.current.focus({preventScroll:!0})};return document.addEventListener("keydown",q),document.addEventListener("focusin",F),()=>{document.removeEventListener("keydown",q),document.removeEventListener("focusin",F);const j=ue.at(-1)===M,W=ue.indexOf(M);if(W!==-1&&ue.splice(W,1),b(),j){const N=d.current;N?.isConnected&&!N.closest("[inert], [hidden]")?N.focus?.({preventScroll:!0}):ue.at(-1)?.querySelector("[role=dialog]")?.focus?.({preventScroll:!0})}}},[t]);const h=n.backgroundColor??n.backgroudColor,l=typeof h=="string"?h:h?.[y],c=typeof l=="string"&&/^(#|rgb\(|rgba\(|hsl\(|hsla\(|oklch\(|color\(|var\()/.test(l.trim())?l:null,L={sm:400,md:560,lg:720,xl:960,full:"100%"},E=["center","left","right","top","bottom"].includes(n.placement)?n.placement:"right",P=b=>typeof b=="number"?`${b}px`:b,B=P(n.width??L[n.size]??460),I=P(n.height),k=P(n.maxHeight),$=P(n.maxWidth),K=Number(n.viewportGap??5),G=Number.isFinite(K)?Math.max(0,K):5,S=typeof n.borderRadius=="number"?`${n.borderRadius}px`:n.borderRadius??"12px";return rt.createPortal(u.jsx("div",{ref:g,className:`pmn-overlay ${i?"pmn-exiting":"pmn-entering"} ${n.animation===!1?"pmn-no-animation":""} pmn-place-${E} ${n.mobileFullscreen?"pmn-mobile-fullscreen":""}`,style:{padding:G,"--pmn-animation-duration":`${Math.min(1e3,Math.max(0,Number(n.animationDuration??220)||0))}ms`},onMouseDown:b=>{b.target===b.currentTarget&&n.closeOnOverlay===!0&&m.current("overlay")},children:u.jsx("section",{ref:t,tabIndex:-1,role:"dialog","aria-modal":"true","aria-label":n.ariaLabel??"Dialog","data-modal-theme":y,className:`pmn-dialog ${y==="dark"?"dark":""} ${!c&&l?l:""} ${n.className??""}`,style:{"--pmn-width":B,"--pmn-gap":`${G}px`,...I!==void 0?{"--pmn-height":I}:{},...k!==void 0?{"--pmn-max-height":k}:{},...$!==void 0?{"--pmn-max-width":$}:{},borderRadius:S,...c?{backgroundColor:c}:{}},children:r})}),document.body)}function Ge({back:t}){return u.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"currentColor",strokeWidth:"2",children:t?u.jsx("path",{d:"m15 18-6-6 6-6"}):u.jsx("path",{d:"M18 6 6 18M6 6l12 12"})})}function pt({options:t,screen:n,route:o,navigation:r,requestClose:i,translate:g,canGoBack:d}){if(t.showHeader===!1)return null;const m=g??(l=>l),f=n.showTitle??t.showTitle??!0,x=typeof n.title=="function"?n.title({t:m,route:o,navigation:r}):n.title??o.name,R={route:o,navigation:r,close:i,canGoBack:d,title:x,t:m},y=n.renderHeader??t.renderHeader;if(y)return y(R);const h=n.renderHeaderRight??t.renderHeaderRight;return u.jsxs("header",{className:`pmn-header ${n.showHeaderBorder??t.showHeaderBorder?"pmn-border-bottom":""} ${t.headerClassName??""}`,children:[(n.showBackButton??t.showBackButton)!==!1&&d&&u.jsx("button",{type:"button",className:"pmn-icon-button","aria-label":m("modal.back"),onClick:()=>r.goBack(),children:u.jsx(Ge,{back:!0})}),f?u.jsx("h2",{children:x}):u.jsx("div",{className:"pmn-header-spacer"}),h?.(R),t.showCloseButton!==!1&&u.jsx("button",{type:"button",className:"pmn-icon-button","aria-label":m("modal.close"),onClick:()=>i("header"),children:u.jsx(Ge,{})})]})}function gt({screen:t,options:n,override:o,route:r,navigation:i,requestClose:g,translate:d,onError:m,loadingApi:f}){const[x,R]=e.useState(null),y=e.useRef(new Set),h=e.useRef(!0);e.useEffect(()=>(h.current=!0,()=>{h.current=!1}),[]);const l=d??(b=>b),c={...n,...t,...o},{showFooter:L,renderFooter:E,done:P,cancel:B,cancle:I}=c,k=B??I,$={route:r,navigation:i,close:g,t:l};if(L===!1)return null;const K=`pmn-footer ${c.showFooterBorder?"pmn-border-top":""} ${c.footerClassName??""}`;if(typeof E=="function")return u.jsx("footer",{className:K,children:E({...$,pending:y.current.size>0})});const G=Array.isArray(c.actions)?c.actions:null;if(!G&&typeof P!="function"&&typeof k!="function")return null;const S=async(b,M,q)=>{if(y.current.has(b)||typeof M!="function")return;y.current.add(b),R(b);const F=f?.begin(r.key,q??c.loadingText??l("modal.processing"));try{await M($)}catch(j){m?.(j,{phase:"footer",action:b,route:r})}finally{f?.end(r.key,F),y.current.delete(b),h.current&&R(j=>j===b?null:j)}};return G?u.jsx("footer",{className:K,children:G.filter(b=>!b.hidden).map(b=>{const M=y.current.has(b.key)||b.loading===!0;return u.jsx("button",{type:"button",disabled:b.disabled===!0||M,className:`pmn-button ${b.variant==="primary"||b.variant==="danger"?"pmn-button-primary":"pmn-button-secondary"} ${b.variant==="danger"?"pmn-button-danger":""}`,onClick:()=>S(b.key,b.onClick,b.loadingText),children:M?b.loadingText??c.loadingText??l("modal.processing"):b.label},b.key)})}):u.jsxs("footer",{className:K,children:[typeof k=="function"&&u.jsx("button",{type:"button",disabled:x!==null,onClick:()=>S("cancel",k),className:"pmn-button pmn-button-secondary",children:c.cancelText??l("modal.cancel")}),typeof P=="function"&&u.jsx("button",{type:"button",disabled:x!==null||c.doneDisabled===!0,onClick:()=>S("done",P),className:"pmn-button pmn-button-primary",children:x==="done"?c.loadingText??l("modal.processing"):c.doneText??l("modal.done")})]})}function ht({loading:t,translate:n}){if(!t.visible)return null;const r=(n??(g=>g))("modal.loading"),i=t.text??(r==="modal.loading"?"加载中...":r);return u.jsx("div",{className:"pmn-loading-overlay",role:"status","aria-live":"polite","aria-busy":"true",children:u.jsxs("div",{className:"pmn-loading-content",children:[u.jsx("span",{className:"pmn-spinner","aria-hidden":"true"}),i&&u.jsx("span",{className:"pmn-loading-text",children:i})]})})}class bt extends e.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?u.jsxs("div",{role:"alert",className:"pmn-error-screen",children:[u.jsx("strong",{children:"页面加载失败"}),u.jsx("p",{children:this.state.error.message}),u.jsx("button",{type:"button",className:"pmn-button pmn-button-secondary",onClick:()=>this.setState({error:null}),children:"重试"})]}):this.props.children}}const xt={success:"✓",error:"×",warning:"!",info:"i"};function yt({items:t,dismiss:n}){return t.length?u.jsx("div",{className:"pmn-toast-region","aria-label":"Notifications",children:t.map(o=>u.jsxs("div",{className:`pmn-toast pmn-toast-${o.type}`,role:o.type==="error"||o.type==="warning"?"alert":"status",children:[u.jsx("span",{className:"pmn-toast-symbol","aria-hidden":"true",children:xt[o.type]}),u.jsx("span",{className:"pmn-toast-message",children:o.message}),o.dismissible&&u.jsx("button",{type:"button",className:"pmn-toast-close","aria-label":"Dismiss notification",onClick:()=>n(o.id),children:"×"})]},o.id))}):null}function vt(t,n){const o=e.useRef(0),r=e.useRef(new Map),i=e.useCallback(m=>{clearTimeout(r.current.get(m)),r.current.delete(m),n.current&&t.current.publish(t.current.getSnapshot().filter(f=>f.id!==m))},[]),g=e.useCallback((m,f={})=>{if(typeof m!="string"||!m.trim())throw new TypeError("[react-modal-navigation] toast message must be a non-empty string");const x=typeof f=="string"?{type:f}:f??{},R=["success","error","warning","info"].includes(x.type)?x.type:"info",y=++o.current,h=Number.isFinite(x.duration)?Math.max(0,x.duration):3e3;if(!n.current)return null;const l=t.current.getSnapshot(),c=l.slice(0,Math.max(0,l.length-4));for(const L of c)clearTimeout(r.current.get(L.id)),r.current.delete(L.id);return t.current.publish([...l.slice(-4),{id:y,message:m,type:R,dismissible:x.dismissible!==!1}]),h>0&&r.current.set(y,setTimeout(()=>i(y),h)),y},[i]),d=e.useMemo(()=>{const m=(f,x)=>g(f,x);for(const f of["success","error","warning","info"])m[f]=(x,R={})=>g(x,{...R,type:f});return m.promise=async(f,x,R={})=>{const y=g(x.loading,{...R,type:"info",duration:0});try{const h=await(typeof f=="function"?f():f);y!=null&&i(y);const l=typeof x.success=="function"?x.success(h):x.success;return l&&g(l,{...R,type:"success"}),h}catch(h){y!=null&&i(y);const l=typeof x.error=="function"?x.error(h):x.error;throw l&&g(l,{...R,type:"error"}),h}},m.dismiss=i,m.clear=()=>{for(const f of r.current.values())clearTimeout(f);r.current.clear(),t.current.publish([])},m},[g,i]);return e.useEffect(()=>()=>{for(const m of r.current.values())clearTimeout(m);r.current.clear()},[]),{toast:d,dismissToast:i}}function wt(t,n,o){const r=e.useRef(new Map),i=e.useRef(0),g=e.useCallback(()=>{if(!n.current)return;const h=[...r.current.values()],l={visible:h.length>0,text:h.at(-1)?.text??null,count:h.length},c=t.current.getSnapshot();(c.visible!==l.visible||c.text!==l.text||c.count!==l.count)&&t.current.publish(l)},[]),d=e.useCallback((h,l)=>{if(!n.current||h!=="global"&&o.current!==h)return null;const c=++i.current;return r.current.set(c,{owner:h,text:l}),g(),c},[g]),m=e.useCallback((h,l)=>{if(l!=null)r.current.get(l)?.owner===h&&r.current.delete(l);else for(const[c,L]of r.current)L.owner===h&&r.current.delete(c);g()},[g]),f=e.useCallback((h,l)=>{h?(m("global"),d("global",l)):m("global")},[d,m]),x=e.useCallback((h,l,c)=>{l?(m(h),d(h,c)):m(h)},[d,m]);return{loadingApi:e.useMemo(()=>({setLoading:f,setScreenLoading:x,begin:d,end:m}),[f,x,d,m]),refreshLoading:g,loadingTasks:r,setLoading:f}}const kt=e.memo(function({store:n,translate:o}){const r=e.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot);return u.jsx(ht,{loading:r,translate:o})}),Ct=e.memo(function({store:n,dismiss:o}){const r=e.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot);return u.jsx(yt,{items:r,dismiss:o})}),Rt=e.memo(function({store:n,routeKey:o,...r}){const i=e.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot);return u.jsx(gt,{...r,override:i[o]})}),Et=e.memo(function({route:n,screen:o,navigation:r,focused:i,resultEvent:g,setFooter:d,loadingApi:m,loadingStore:f,bodyClassName:x,notifyError:R,registerDirtyGuard:y}){const h=o.component,l=e.useMemo(()=>({isFocused:i,resultEvent:g,routeKey:n.key,setFooter:d}),[i,g,n.key,d]),c=e.useMemo(()=>({setLoading:(E,P)=>m.setScreenLoading(n.key,E,P),showLoading:E=>m.begin(n.key,E),hideLoading:E=>m.end(n.key,E)}),[m,n.key]),L=e.useMemo(()=>({routeKey:n.key,registerDirtyGuard:y}),[n.key,y]);return u.jsx(Ve.Provider,{value:n,children:u.jsx(Ye.Provider,{value:L,children:u.jsx(Me.Provider,{value:l,children:u.jsx(je.Provider,{value:c,children:u.jsx(De.Provider,{value:f,children:u.jsx("div",{hidden:!i,inert:!i,"data-modal-route-key":n.key,tabIndex:-1,className:`pmn-body ${x??""}`,children:u.jsx(bt,{route:n,onError:R,children:u.jsx(h,{route:n,navigation:r})})})})})})})})});function Je({config:t,initialScreen:n,params:o,options:r,translate:i,onRequestClose:g,onOpened:d,registerLoading:m,notifyError:f,error:x,clearError:R,registerDirtyGuard:y,canNavigate:h,exiting:l=!1}){const[c,L]=e.useReducer(Ee,null,()=>Qe(n??t.initialRoute,o)),E=e.useRef(null);E.current||(E.current=ct({canGoBack:c.length>1,stack:c,currentRoute:c.at(-1)}));const P=e.useRef(null),B=e.useRef(null),I=e.useRef(null);P.current||(P.current=Pe({visible:!1,text:null,count:0})),B.current||(B.current=Pe({})),I.current||(I.current=Pe([]));const k=e.useRef(!0),$=e.useRef(0),{toast:K,dismissToast:G}=vt(I,k);e.useEffect(()=>(k.current=!0,()=>{k.current=!1,$.current++}),[]);const[S,b]=e.useState({}),M=e.useRef(new Map),q=e.useRef(null),F=e.useRef(null),j=e.useRef(!1),W=e.useRef(!1),N=e.useRef(new Map),Q=e.useRef(0),J=e.useCallback((a,v,T)=>{for(const[D,ne]of N.current)a.includes(ne.key)&&(N.current.delete(D),ne.resolve({status:v,...v==="returned"?{value:T}:{}}))},[]),A=e.useRef(c);A.current=c;const re=e.useRef(h);re.current=h;const X=e.useRef(!1),ge=e.useRef(0),z=c.at(-1),O=z.key,oe=e.useRef(O);oe.current=O;const{loadingApi:he,refreshLoading:be,loadingTasks:le,setLoading:se}=wt(P,k,oe),Z=t.screens,we=P,de=e.useRef(m);de.current=m,e.useEffect(()=>(de.current?.({setLoading:se}),()=>de.current?.(null)),[se]);const ke=e.useCallback((a,v)=>{if(!k.current)return;const T=B.current.getSnapshot();if(v===null){if(!(a in T))return;const D={...T};delete D[a],B.current.publish(D);return}T[a]!==v&&B.current.publish({...T,[a]:v})},[]),xe=e.useCallback(()=>{if(typeof document>"u")return;const a=document.activeElement;if(!(a instanceof HTMLElement)||!q.current?.contains(a))return;const v=a.closest("[data-modal-route-key]");v&&M.current.set(v.dataset.modalRouteKey,a),q.current.focus({preventScroll:!0})},[]),ye=e.useCallback(a=>{if(!Object.prototype.hasOwnProperty.call(Z,a))throw new Error(`[react-modal-navigation] Unknown modal screen: ${a}`)},[Z]),ae=e.useCallback((a,v)=>{try{Promise.resolve(r[a]?.(v)).catch(T=>f(T,{phase:a}))}catch(T){f(T,{phase:a})}},[r,f]),V=e.useCallback(async(a,v,T,D)=>{if(!k.current||W.current)return!1;const ne=$.current,_=A.current,Te=_.at(-1);if(a!=="BACK"&&ye(v),a==="BACK"&&_.length<=1)return!1;const ze=a==="NAVIGATE"?_.findIndex(pe=>pe.name===v):-1,Ne=a==="RESET"?_:a==="BACK"||a==="REPLACE"?[Te]:ze>=0?_.slice(ze+1):[];W.current=!0;try{if(Ne.length&&re.current&&!await re.current(Ne.map(Le=>Le.key),{reason:"navigation",action:a,from:Te,to:a==="BACK"?_.at(-2)?.name:v})||!k.current||ne!==$.current||A.current.at(-1)?.key!==Te.key)return!1;if(a==="BACK"&&D!==void 0){const Re=_.at(-2);b(Le=>({...Le,[Re.key]:{id:++ge.current,data:D}}))}a==="RESET"&&b({}),J(Ne.map(Re=>Re.key),a==="BACK"?"returned":"removed",D),xe();const pe={type:a,name:v,params:T};return A.current=Ee(A.current,pe),L(pe),!0}catch(pe){return k.current&&f(pe,{phase:"navigationGuard",action:a}),!1}finally{W.current=!1}},[ye,xe,f,J]),s=e.useCallback((a,v)=>V("NAVIGATE",a,v),[V]),p=e.useCallback(async(a,v)=>{if(!k.current)return{status:"cancelled"};if(A.current,!await V("NAVIGATE",a,v)||!k.current)return{status:"cancelled"};const D=A.current.at(-1);return!D||D.name!==a?{status:"cancelled"}:new Promise(ne=>{const _=++Q.current;N.current.set(_,{key:D.key,resolve:ne})})},[V]),C=e.useCallback((a,v)=>V("REPLACE",a,v),[V]),w=e.useCallback((a,v)=>V("RESET",a,v),[V]),H=e.useCallback(a=>{if(!a||typeof a!="object"||Array.isArray(a))throw new TypeError("[react-modal-navigation] setParams expects an object");if(!k.current)return;const v={type:"SET_PARAMS",params:a};A.current=Ee(A.current,v),L(v)},[]),U=e.useCallback(a=>{if(!a||typeof a!="object"||Array.isArray(a))throw new TypeError("[react-modal-navigation] setOptions expects an object");if(!k.current)return;const v={type:"SET_OPTIONS",options:a};A.current=Ee(A.current,v),L(v)},[]),Y=e.useCallback(a=>V("BACK",null,void 0,a),[V]),ee=e.useCallback((a,v)=>!k.current||we.current.getSnapshot().visible&&r.lockCloseWhileLoading!==!1?Promise.resolve(!1):g(a,v,{route:z,stack:c}),[r.lockCloseWhileLoading,g,z,c]),te=e.useRef(ee);te.current=ee;const ce=e.useCallback(a=>te.current("api",a),[]),me=e.useMemo(()=>({navigate:s,navigateAsync:p,replace:C,reset:w,setParams:H,setOptions:U,goBack:Y,close:ce,setLoading:se}),[s,p,C,w,H,U,Y,ce,se]),fe=e.useMemo(()=>({canGoBack:c.length>1,stack:c,currentRoute:z}),[c]);e.useLayoutEffect(()=>E.current.publish(fe),[fe]);const ie=e.useRef(null);ie.current||(ie.current=Object.defineProperties({},{canGoBack:{enumerable:!0,get:()=>E.current.getSnapshot().canGoBack},stack:{enumerable:!0,get:()=>E.current.getSnapshot().stack},currentRoute:{enumerable:!0,get:()=>E.current.getSnapshot().currentRoute}}));const Ce=e.useMemo(()=>Object.assign(ie.current,me),[me]);e.useLayoutEffect(()=>{j.current=!1;const a=[...q.current?.querySelectorAll("[data-modal-route-key]")??[]].find(D=>D.dataset.modalRouteKey===O);if(!a)return;const v=M.current.get(O);(v?.isConnected&&a.contains(v)&&!v.matches(":disabled")&&!v.closest("[inert], [hidden]")?v:a).focus({preventScroll:!0})},[O]),e.useEffect(()=>{let a=!1;for(const[T,D]of le.current)D.owner!=="global"&&D.owner!==O&&(le.current.delete(T),a=!0);a&&be();const v=new Set(c.map(T=>T.key));b(T=>{const D=Object.keys(T).filter(_=>!v.has(_));if(!D.length)return T;const ne={...T};return D.forEach(_=>delete ne[_]),ne});for(const T of M.current.keys())v.has(T)||M.current.delete(T)},[O,c,be]),e.useEffect(()=>{if(F.current?.key!==O){if(F.current){const a={from:F.current,to:z,stack:c};ae("onBlur",{route:F.current,...a}),ae("onNavigate",a),ae("onRouteChange",a)}ae("onFocus",{route:z,stack:c}),F.current=z}},[z,O,c,ae]),e.useEffect(()=>()=>{le.current.clear(),M.current.clear();for(const a of N.current.values())a.resolve({status:"dismissed"});N.current.clear()},[]),e.useEffect(()=>{X.current||(X.current=!0,d?.({route:z,stack:c}))},[]);const nt=e.useMemo(()=>ut(c,Z,r.maxCachedScreens),[c,Z,r.maxCachedScreens]),$e=e.useMemo(()=>({...Z[z.name],...z.options??{}}),[Z,z.name,z.options]);return u.jsx(_e.Provider,{value:K,children:u.jsx(st.Provider,{value:I.current,children:u.jsx(at.Provider,{value:B.current,children:u.jsx(ot.Provider,{value:Ce,children:u.jsx(Fe.Provider,{value:me,children:u.jsx(Oe.Provider,{value:E.current,children:u.jsx(je.Provider,{value:he,children:u.jsxs(ft,{dialogRef:q,options:r,requestClose:ee,exiting:l,children:[u.jsx(pt,{options:r,screen:$e,route:z,navigation:Ce,requestClose:ee,translate:i,canGoBack:c.length>1}),u.jsx("main",{className:"pmn-main",children:nt.map(a=>u.jsx(Et,{route:a,screen:Z[a.name],navigation:Ce,focused:a.key===O,resultEvent:S[a.key]??null,bodyClassName:r.bodyClassName,setFooter:ke,loadingApi:he,loadingStore:P.current,notifyError:f,registerDirtyGuard:y},a.key))}),u.jsx(Rt,{store:B.current,routeKey:O,screen:$e,options:r,route:z,navigation:Ce,requestClose:ee,translate:i,onError:f,loadingApi:he},O),u.jsx(kt,{store:P.current,translate:i}),u.jsx(Ct,{store:I.current,dismiss:G}),x&&u.jsxs("div",{className:"pmn-error",role:"alert",children:[u.jsx("span",{children:x.message||String(x)}),u.jsx("button",{type:"button",onClick:R,"aria-label":"Dismiss error",children:"×"})]})]})})})})})})})})}const St=".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}}.pmn-toast-region{position:absolute;top:56px;left:12px;right:12px;z-index:80;display:flex;flex-direction:column;align-items:center;gap:8px;pointer-events:none;max-height:calc(100% - 72px);overflow:hidden}.pmn-toast{pointer-events:auto;display:flex;align-items:flex-start;gap:10px;width:max-content;max-width:100%;min-width:min(260px,100%);padding:11px 13px;border:1px solid var(--pmn-border);border-radius:9px;background:var(--pmn-surface);color:var(--pmn-text);box-shadow:0 5px 18px #0000001a;font-size:13px;line-height:1.5;overflow-wrap:anywhere}.pmn-toast-symbol{flex:0 0 20px;display:grid;place-items:center;width:20px;height:20px;border-radius:50%;font-size:13px;font-weight:700;background:var(--pmn-hover);color:var(--pmn-muted)}.pmn-toast-success .pmn-toast-symbol{background:#dcfce7;color:#15803d}.pmn-toast-error .pmn-toast-symbol{background:#fee2e2;color:#b91c1c}.pmn-toast-warning .pmn-toast-symbol{background:#fef3c7;color:#b45309}.pmn-toast-info .pmn-toast-symbol{background:#dbeafe;color:#1d4ed8}.pmn-toast-message{flex:1;min-width:0;white-space:pre-wrap}.pmn-toast-close{border:0;background:transparent;color:var(--pmn-muted);cursor:pointer;font-size:19px;line-height:18px;padding:0 1px}.pmn-toast-close:hover{color:var(--pmn-text)}.pmn-button-danger{background:#dc2626!important;color:#fff!important;border-color:#dc2626!important}",He="react-modal-navigation-styles",Ae=new WeakMap;function Mt(){e.useInsertionEffect(()=>{if(typeof document>"u")return;const t=document;let n=Ae.get(t);if(!n){let o=t.getElementById(He);const r=!o;o||(o=t.createElement("style"),o.id=He,o.setAttribute("data-react-modal-navigation",""),o.textContent=St,t.head.appendChild(o)),n={element:o,owned:r,count:0},Ae.set(t,n)}return n.count+=1,()=>{n.count-=1,n.count===0&&(n.owned&&n.element.remove(),Ae.delete(t))}},[])}function Se(t,n,o){if(typeof t=="string"){if(!t.trim())throw new TypeError("[react-modal-navigation] modal name must not be empty");return{name:t,params:n??{},options:o??{}}}if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("[react-modal-navigation] open expects a modal name or a configuration object");const{name:r,screen:i,params:g={},options:d={},...m}=t;if(typeof r!="string"||!r.trim())throw new TypeError("[react-modal-navigation] open config requires a non-empty string name");if(d===null||typeof d!="object"||Array.isArray(d))throw new TypeError("[react-modal-navigation] open config options must be an object");if(i!==void 0&&(typeof i!="string"||!i.trim()))throw new TypeError("[react-modal-navigation] screen must be a non-empty string");return{name:r,...i===void 0?{}:{screen:i},params:g,options:{...m,...d}}}const jt={placement:"right",showHeader:!0,showBackButton:!0,showCloseButton:!0,viewportGap:5,borderRadius:12,closeOnOverlay:!1,closeOnEsc:!0},Tt=t=>({"modal.loading":"加载中...","modal.processing":"处理中...","modal.back":"返回","modal.close":"关闭","modal.cancel":"取消","modal.done":"完成"})[t]??t;function Nt({registry:t,children:n,defaultOptions:o={},backgroundColor:r,theme:i,translate:g=Tt,onError:d,confirmDiscard:m}){Mt();const[f,x]=e.useState(null),[R,y]=e.useState(null),[h,l]=e.useState(0),c=e.useRef(null),L=e.useRef(new Map),E=e.useRef([]),P=e.useRef(null),B=e.useRef(null),I=e.useRef(0),k=e.useRef(null),$=e.useRef(!1),K=e.useRef(0),G=e.useRef(null),S=e.useRef(new Map),[b,M]=e.useState(!1),q=e.useRef(m);q.current=m;const F=e.useCallback((s,p)=>(S.current.set(s,p),()=>{S.current.get(s)===p&&S.current.delete(s)}),[]),j=e.useCallback(async s=>{for(const p of S.current.values()){if(!p.dirty)continue;if((p.onBeforeDiscard?await p.onBeforeDiscard(s):q.current?await q.current(s):typeof window<"u"&&typeof window.confirm=="function"?window.confirm(p.message||"有未保存的修改,确定放弃吗?"):!1)===!1)return!1}return!0},[]),W=e.useCallback(async(s,p)=>{for(const C of s){const w=S.current.get(C);if(!w?.dirty)continue;if((w.onBeforeDiscard?await w.onBeforeDiscard(p):q.current?await q.current(p):typeof window<"u"&&typeof window.confirm=="function"?window.confirm(w.message||"有未保存的修改,确定放弃吗?"):!1)===!1)return!1}return!0},[]),N=e.useRef(!0),Q=e.useRef(null),J=e.useRef(d);J.current=d;const A=e.useCallback((s,p)=>{N.current&&y(s);try{J.current?J.current(s,p):console.error("[react-modal-navigation]",s)}catch(C){console.error("[react-modal-navigation] onError failed",C)}},[]),re=e.useCallback((s,p)=>{const C=L.current.get(s);L.current.delete(s),C?.(p)},[]),X=e.useCallback(s=>({...jt,...o,...i!==void 0?{theme:i}:{},...r!==void 0?{backgroundColor:r}:{},...s.config.modalOptions,...s.overrides}),[o,i,r]),ge=f?X(f):null,z=e.useRef(null);z.current=ge,Q.current=ge;const O=e.useCallback(async(s="api",p,C={})=>{const w=c.current;if(!w||k.current||$.current)return!1;k.current=w.id,$.current=!0;const H=Q.current??X(w),U={...C,reason:s,result:p,name:w.name};try{if(!await j(U)||await H.onBeforeClose?.(U)===!1||c.current?.id!==w.id||!N.current||(M(!0),await new Promise(Y=>{const ee=H.animation===!1||typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?0:Math.max(0,Number(H.animationDuration??220)||0);setTimeout(Y,Math.min(ee,1e3))}),!N.current||c.current?.id!==w.id))return!1;c.current=null,G.current=null,x(null),M(!1),S.current.clear(),re(w.id,C.confirmed||p!==void 0?{status:"confirmed",value:p,reason:s}:{status:"dismissed",reason:s});try{await H.onClose?.(U)}catch(Y){A(Y,{phase:"onClose",name:w.name})}return!0}catch(Y){return A(Y,{phase:"onBeforeClose",name:w.name}),!1}finally{k.current===w.id&&(k.current=null),$.current=!1,!c.current&&N.current&&queueMicrotask(()=>B.current?.())}},[X,A,re,j]),oe=e.useCallback(async(s,p={},C={},w,H)=>{const U=t?.[s];if(!U)throw new Error(`[react-modal-navigation] Unknown modal: ${s}`);const Y=H??U.initialRoute;if(!U.screens?.[Y])throw new Error(`[react-modal-navigation] Unknown initial screen '${Y}' in modal '${s}'`);if(!N.current||$.current||k.current)return null;$.current=!0;const ee=K.current;try{const te=c.current;if(te){const me=Q.current??X(te),fe={reason:"replace",name:te.name,nextName:s};try{if(!await j(fe)||await me.onBeforeClose?.(fe)===!1)return null}catch(ie){return A(ie,{phase:"onBeforeClose",name:te.name}),null}if(!N.current||ee!==K.current||c.current?.id!==te.id)return null;c.current=null,G.current=null,x(null),S.current.clear(),re(te.id,{status:"replaced",reason:"replace"});try{await me.onClose?.(fe)}catch(ie){A(ie,{phase:"onClose",name:te.name})}if(!N.current||ee!==K.current)return null}const ce={id:++I.current,name:s,screen:Y,params:p,config:U,overrides:C};return c.current=ce,G.current=null,w&&L.current.set(ce.id,w),y(null),x(ce),ce.id}finally{$.current=!1}},[t,X,A,re,j]);P.current=oe;const he=e.useCallback(async()=>{if(!N.current||c.current||$.current||k.current)return;const s=E.current.shift();if(s){l(E.current.length);try{const p=await P.current(s.args.name,s.args.params,s.args.options,s.resolveResult,s.args.screen);p===null?(s.resolveResult?.({status:"dismissed",reason:"blocked"}),s.resolveId?.(null),queueMicrotask(()=>B.current?.())):s.resolveId?.(p)}catch(p){s.reject?.(p),queueMicrotask(()=>B.current?.())}}},[]);B.current=he;const be=e.useCallback((s,p,C)=>{const w=Se(s,p,C);return t?.[w.name]?new Promise((H,U)=>{E.current.push({args:w,resolveId:H,reject:U}),l(E.current.length),queueMicrotask(()=>B.current?.())}):Promise.reject(new Error(`[react-modal-navigation] Unknown modal: ${w.name}`))},[t]),le=e.useCallback((s,p,C)=>{const w=Se(s,p,C);return t?.[w.name]?new Promise((H,U)=>{E.current.push({args:w,resolveResult:H,reject:U}),l(E.current.length),queueMicrotask(()=>B.current?.())}):Promise.reject(new Error(`[react-modal-navigation] Unknown modal: ${w.name}`))},[t]),se=e.useCallback(s=>{if(!s||typeof s!="object"||Array.isArray(s))throw new TypeError("[react-modal-navigation] update expects an options object");const p=c.current;if(!p||$.current)return!1;const C={...p,overrides:{...p.overrides,...s}};return c.current=C,x(C),Q.current=X(C),!0},[X]),Z=e.useCallback((s="queue-cleared")=>{const p=E.current.splice(0);l(0);for(const C of p)C.resolveId?.(null),C.resolveResult?.({status:"dismissed",reason:s});return p.length},[]),we=e.useCallback((s,p,C)=>{const w=Se(s,p,C);return oe(w.name,w.params,w.options,void 0,w.screen)},[oe]),de=e.useCallback((s,p,C)=>{const w=Se(s,p,C);return new Promise((H,U)=>{oe(w.name,w.params,w.options,H,w.screen).then(Y=>{Y===null&&H({status:"dismissed",reason:"blocked"})},U)})},[oe]),ke=e.useCallback(s=>O("api",s),[O]),xe=e.useCallback((s="api")=>O(s),[O]),ye=e.useCallback(s=>O("confirm",s,{confirmed:!0}),[O]),ae=e.useCallback((s,p)=>G.current?.setLoading(s,p),[]),V=e.useMemo(()=>({open:we,openAsync:de,enqueue:be,enqueueAsync:le,update:se,clearQueue:Z,close:ke,dismiss:xe,confirm:ye,setLoading:ae,queueSize:h,isOpen:!!f,activeName:f?.name??null,error:R,clearError:()=>y(null)}),[we,de,be,le,se,Z,ke,xe,ye,ae,f,R,h]);return e.useEffect(()=>(N.current=!0,()=>{N.current=!1,K.current+=1,c.current=null;for(const p of L.current.values())p({status:"dismissed",reason:"unmount"});L.current.clear(),S.current.clear();const s=E.current.splice(0);for(const p of s)p.resolveId?.(null),p.resolveResult?.({status:"dismissed",reason:"unmount"})}),[]),u.jsxs(We.Provider,{value:V,children:[n,f&&u.jsx(Je,{config:f.config,initialScreen:f.screen,params:f.params,options:ge,translate:g,notifyError:A,error:R,clearError:()=>y(null),registerLoading:s=>{G.current=s},registerDirtyGuard:F,canNavigate:W,exiting:b,onRequestClose:O,onOpened:s=>{try{const p=z.current?.onOpen?.(s);Promise.resolve(p).catch(C=>A(C,{phase:"onOpen"}))}catch(p){A(p,{phase:"onOpen"})}}},f.id)]})}const Lt=Object.freeze({canGoBack:!1,stack:[],currentRoute:null}),Pt=()=>()=>{},Ue=()=>Lt;function Bt(){const t=e.useContext(We),n=e.useContext(Fe),o=e.useContext(Oe),r=e.useSyncExternalStore(o?.subscribe??Pt,o?.getSnapshot??Ue,o?.getSnapshot??Ue);if(!t)throw new Error("[react-modal-navigation] useModal requires <ModalProvider>");const i=e.useMemo(()=>{const g=()=>{if(!n)throw new Error("[react-modal-navigation] navigation requires an active modal screen; use modal.open() outside a modal");return n};return{navigate:(...d)=>g().navigate(...d),replace:(...d)=>g().replace(...d),reset:(...d)=>g().reset(...d),setParams:(...d)=>g().setParams(...d),setOptions:(...d)=>g().setOptions(...d),goBack:(...d)=>g().goBack(...d),close:(...d)=>g().close(...d),setLoading:(...d)=>g().setLoading(...d),canGoBack:r.canGoBack,stack:r.stack,currentRoute:r.currentRoute}},[n,r]);return e.useMemo(()=>({...t,modal:t,navigation:i}),[t,i])}function Xe(){const t=e.useContext(Fe);if(!t)throw new Error("useModalNavigationCommands requires an active modal screen");return t}function Ze(){const t=e.useContext(Oe);if(!t)throw new Error("useModalNavigationState requires an active modal screen");return e.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getSnapshot)}function At(){const t=Xe(),n=Ze();return e.useMemo(()=>({...t,...n}),[t,n])}function Ie(){const t=e.useContext(Me);if(!t)throw new Error("useIsFocused must be called inside a modal screen");return t.isFocused}function qt(t){const n=Ie();e.useEffect(()=>{if(n)return t()},[n,t])}function Ft(t){const n=e.useContext(Me);if(!n)throw new Error("useNavigationResult requires an active modal screen");const o=e.useRef(t),r=e.useRef(null);e.useEffect(()=>{o.current=t},[t]),e.useEffect(()=>{!n.isFocused||!n.resultEvent||r.current!==n.resultEvent.id&&(r.current=n.resultEvent.id,o.current(n.resultEvent.data))},[n.isFocused,n.resultEvent])}function Ot(t={}){const n=e.useContext(Me);if(!n)throw new Error("[react-modal-navigation] useModalFooter requires an active modal screen");const{setFooter:o,routeKey:r}=n,i=e.useRef(t);i.current=t;const g=e.useMemo(()=>(...S)=>i.current.done?.(...S),[]),d=e.useMemo(()=>(...S)=>(i.current.cancel??i.current.cancle)?.(...S),[]),m=e.useMemo(()=>(...S)=>i.current.renderFooter?.(...S),[]),f=typeof t.done=="function",x=typeof(t.cancel??t.cancle)=="function",R=typeof t.renderFooter=="function",{showFooter:y,showFooterBorder:h,doneDisabled:l,doneText:c,cancelText:L,loadingText:E,footerClassName:P}=t,B=e.useRef({source:null,normalized:void 0}),I=Array.isArray(t.actions)?t.actions:null,k=B.current.source;I===k||I&&k&&I.length===k.length&&I.every((S,b)=>{const M=k[b];return[...new Set([...Object.keys(S),...Object.keys(M)])].every(F=>F==="onClick"||Object.is(S[F],M[F]))})||(B.current={source:I?.map(S=>({...S}))??null,normalized:I?.map((S,b)=>({...S,onClick:(...M)=>(i.current.actions?.find(F=>F.key===S.key)??i.current.actions?.[b])?.onClick?.(...M)}))});const K=B.current.normalized,G=e.useMemo(()=>({showFooter:y,showFooterBorder:h,doneDisabled:l,doneText:c,cancelText:L,loadingText:E,footerClassName:P,...K!==void 0?{actions:K}:{},...f?{done:g}:{},...x?{cancel:d}:{},...R?{renderFooter:m}:{}}),[y,h,l,c,L,E,P,K,f,x,R,g,d,m]);e.useEffect(()=>{o(r,G)},[r,o,G]),e.useEffect(()=>()=>o(r,null),[r,o])}function et(){const t=e.useContext(je),n=e.useContext(De);if(!t||!n)throw new Error("[react-modal-navigation] useModalLoading requires an active modal screen");const o=e.useSyncExternalStore(n.subscribe,n.getSnapshot,n.getSnapshot);return e.useMemo(()=>({...t,isLoading:o.visible}),[t,o.visible])}function Dt(){const t=e.useContext(je);if(!t)throw new Error("[react-modal-navigation] useModalLoadingCommands requires an active modal screen");return t}function It(){const t=e.useContext(De);if(!t)throw new Error("[react-modal-navigation] useModalLoadingState requires an active modal screen");return e.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getSnapshot)}function $t(){const t=et(),n=Ie(),o=e.useRef(!0),r=e.useRef(!1),[i,g]=e.useState(!1),[d,m]=e.useState(null),f=e.useRef(t);return f.current=t,e.useEffect(()=>(o.current=!0,()=>{o.current=!1}),[]),{run:e.useCallback(async(R,y={})=>{if(r.current)return{status:"busy"};if(typeof R!="function")throw new TypeError("[react-modal-navigation] run requires a function");r.current=!0,o.current&&(g(!0),m(null));const h=f.current.showLoading(y.loadingText);try{const l=await R();return o.current&&await y.onSuccess?.(l),{status:"success",value:l}}catch(l){if(o.current){m(l);try{await y.onError?.(l)}catch(c){console.error("[react-modal-navigation] onError failed",c)}}if(y.throwOnError)throw l;return{status:"error",error:l}}finally{h!=null&&f.current.hideLoading(h),r.current=!1,o.current&&g(!1)}},[]),pending:i,error:d,clearError:()=>m(null),isFocused:n}}function zt(t,n={}){const o=e.useContext(Ye);if(!o)throw new Error("[react-modal-navigation] useModalUnsavedChanges must be used inside a modal screen");const r=e.useRef({dirty:t,...n});r.current={dirty:t,...n};const{routeKey:i,registerDirtyGuard:g}=o;e.useEffect(()=>g(i,{get dirty(){return!!r.current.dirty},get message(){return r.current.message},get onBeforeDiscard(){return r.current.onBeforeDiscard}}),[i,g])}const Kt=()=>{const t=e.useContext(_e);if(!t)throw new Error("[react-modal-navigation] useToast requires an active modal");return t};function tt(){const t=e.useContext(Ve);if(!t)throw new Error("[react-modal-navigation] useModalRoute requires a modal screen");return t}function Gt(){return tt().params}exports.ModalNavigator=Je;exports.ModalProvider=Nt;exports.useFocusEffect=qt;exports.useIsFocused=Ie;exports.useModal=Bt;exports.useModalFooter=Ot;exports.useModalLoading=et;exports.useModalLoadingCommands=Dt;exports.useModalLoadingState=It;exports.useModalNavigation=At;exports.useModalNavigationCommands=Xe;exports.useModalNavigationState=Ze;exports.useModalParams=Gt;exports.useModalRoute=tt;exports.useModalTask=$t;exports.useModalUnsavedChanges=zt;exports.useNavigationResult=Ft;exports.useToast=Kt;
package/dist/index.d.ts CHANGED
@@ -4,14 +4,37 @@ export type ModalBackground = string | { light?: string; dark?: string };
4
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
+ export type PageNavigationResult<T = unknown> =
8
+ | { status: 'returned'; value: T }
9
+ | { status: 'removed' | 'cancelled' | 'dismissed' };
10
+ export interface ModalFooterAction {
11
+ key: string;
12
+ label: string;
13
+ variant?: 'primary' | 'secondary' | 'danger';
14
+ disabled?: boolean;
15
+ hidden?: boolean;
16
+ loading?: boolean;
17
+ loadingText?: string;
18
+ onClick?: (context: ModalActionContext) => void | Promise<void>;
19
+ }
20
+ /** Define screen names and params for strongly typed navigation helpers. */
21
+ export type ModalRouteParams = Record<string, unknown>;
22
+ export type TypedModalNavigation<Routes extends Record<string, unknown>> = Omit<ModalNavigation, 'navigate' | 'navigateAsync' | 'replace' | 'reset'> & {
23
+ navigate<K extends keyof Routes & string>(name: K, params: Routes[K]): Promise<boolean>;
24
+ navigateAsync<T = unknown, K extends keyof Routes & string = keyof Routes & string>(name: K, params: Routes[K]): Promise<PageNavigationResult<T>>;
25
+ replace<K extends keyof Routes & string>(name: K, params: Routes[K]): Promise<boolean>;
26
+ reset<K extends keyof Routes & string>(name: K, params: Routes[K]): Promise<boolean>;
27
+ };
7
28
  export interface ModalNavigation {
8
- navigate(name: string, params?: unknown): void;
9
- replace(name: string, params?: unknown): void;
10
- reset(name: string, params?: unknown): void;
29
+ navigate(name: string, params?: unknown): Promise<boolean>;
30
+ /** Await a child route until it returns, is removed, or the modal closes. */
31
+ navigateAsync<T = unknown>(name: string, params?: unknown): Promise<PageNavigationResult<T>>;
32
+ replace(name: string, params?: unknown): Promise<boolean>;
33
+ reset(name: string, params?: unknown): Promise<boolean>;
11
34
  setParams(params: Record<string, unknown>): void;
12
35
  /** Update options of the active screen without navigating. Changes are scoped to this route instance. */
13
36
  setOptions(options: ModalScreenOptions): void;
14
- goBack(result?: unknown): boolean;
37
+ goBack(result?: unknown): Promise<boolean>;
15
38
  close(result?: unknown): Promise<boolean>;
16
39
  setLoading(value: boolean, text?: string): void;
17
40
  readonly canGoBack: boolean;
@@ -54,6 +77,8 @@ export interface ModalOptions {
54
77
  showFooterBorder?: boolean;
55
78
  showFooter?: boolean;
56
79
  lockCloseWhileLoading?: boolean;
80
+ /** Maximum number of inactive KeepAlive screen instances retained in memory (default unlimited). */
81
+ maxCachedScreens?: number;
57
82
  className?: string;
58
83
  bodyClassName?: string;
59
84
  headerClassName?: string;
@@ -66,6 +91,7 @@ export interface ModalOptions {
66
91
  onRouteChange?: (context: ModalEventContext) => void;
67
92
  onFocus?: (context: ModalEventContext) => void;
68
93
  onBlur?: (context: ModalEventContext) => void;
94
+ actions?: ModalFooterAction[];
69
95
  done?: (context: ModalActionContext) => void | Promise<void>;
70
96
  cancel?: (context: ModalActionContext) => void | Promise<void>;
71
97
  cancle?: (context: ModalActionContext) => void | Promise<void>;
@@ -82,6 +108,8 @@ export interface ModalScreenOptions extends Omit<Partial<ModalOptions>, 'title'>
82
108
  title?: string | ReactNode | ((context: { t: (key: string) => string; route: ModalRoute; navigation: ModalNavigation }) => ReactNode);
83
109
  }
84
110
  export interface ModalScreen extends ModalOptions {
111
+ /** Whether this screen remains mounted when inactive (default true). */
112
+ keepAlive?: boolean;
85
113
  component: ComponentType<any>;
86
114
  title?: string | ((context: { t: (key: string) => string; route: ModalRoute; navigation: ModalNavigation }) => ReactNode);
87
115
  }
@@ -146,6 +174,9 @@ export function useIsFocused(): boolean;
146
174
  export function useFocusEffect(callback: () => void | (() => void)): void;
147
175
  export function useNavigationResult(callback: (result: unknown) => void): void;
148
176
  export function useModalFooter(config: Partial<ModalOptions>): void;
177
+ /** Returns the route for this screen, including when kept alive in the background. */
178
+ export function useModalRoute<P = unknown>(): ModalRoute<P>;
179
+ export function useModalParams<P = Record<string, unknown>>(): P;
149
180
  export interface ModalLoadingActions {
150
181
  isLoading: boolean;
151
182
  setLoading(value: boolean, text?: string): void;
@@ -153,6 +184,8 @@ export interface ModalLoadingActions {
153
184
  hideLoading(token?: number | null): void;
154
185
  }
155
186
  export function useModalLoading(): ModalLoadingActions;
187
+ export function useModalLoadingCommands(): Omit<ModalLoadingActions, 'isLoading'>;
188
+ export function useModalLoadingState(): { visible: boolean; text: string | null; count: number };
156
189
 
157
190
  export type ModalTaskResult<T> = { status: 'success'; value: T } | { status: 'error'; error: unknown } | { status: 'busy' };
158
191
  export interface ModalTaskOptions<T> {
@@ -188,5 +221,16 @@ export interface ToastActions {
188
221
  info(message: string, options?: Omit<ToastOptions, 'type'>): number;
189
222
  dismiss(id: number): void;
190
223
  clear(): void;
224
+ /** Preserves the original promise result or rejection. */
225
+ promise<T>(task: Promise<T> | (() => Promise<T> | T), messages: {
226
+ loading: string;
227
+ success?: string | ((value: T) => string);
228
+ error?: string | ((error: unknown) => string);
229
+ }, options?: Omit<ToastOptions, 'type'>): Promise<T>;
191
230
  }
192
231
  export function useToast(): ToastActions;
232
+
233
+ /** Stable navigation commands without subscribing to route changes. */
234
+ export declare function useModalNavigationCommands(): Pick<ModalNavigation, "navigate" | "navigateAsync" | "replace" | "reset" | "setParams" | "setOptions" | "goBack" | "close" | "setLoading">;
235
+ /** Reactive navigation metadata. */
236
+ export declare function useModalNavigationState(): Pick<ModalNavigation, "canGoBack" | "stack" | "currentRoute">;