@remit/web-client-dist 0.0.217 → 0.0.219
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/assets/{ComposeBody-DzoUP5mO.js → ComposeBody-B7A7M4j3.js} +1 -1
- package/assets/{ConfirmDialog-C4hlsYS7.js → ConfirmDialog-D5nahg6y.js} +1 -1
- package/assets/{ErrorState-bMJzrGDP.js → ErrorState-Bv7-HYh6.js} +1 -1
- package/assets/{OnboardingWizard--R3_ucAT.js → OnboardingWizard-C1JuUnOV.js} +1 -1
- package/assets/{account-form-helpers-DIq5DB07.js → account-form-helpers-hmeH-7ez.js} +1 -1
- package/assets/{accounts-BdGf-o7a.js → accounts-B6PggVhQ.js} +1 -1
- package/assets/{advanced-CxzJM3CX.js → advanced-7RKTr71d.js} +1 -1
- package/assets/{appearance-BJHsNeyk.js → appearance-DEd7WWvJ.js} +1 -1
- package/assets/{avatar-CTRk22EW.js → avatar-DfVX_XsZ.js} +1 -1
- package/assets/{browser-ponyfill-CKYUPXg9.js → browser-ponyfill-DhaqVnl2.js} +1 -1
- package/assets/{circle-check-C5io36vF.js → circle-check-D_eO0Xzn.js} +1 -1
- package/assets/{download-Ds-LfNwD.js → download--oH9ivRy.js} +1 -1
- package/assets/{filters-DzDviygv.js → filters-lxDLSn8k.js} +1 -1
- package/assets/{flagged-DOoGjSlu.js → flagged-uGND5ArV.js} +1 -1
- package/assets/{folder-BcWbB7Pz.js → folder-CZVXBM8D.js} +1 -1
- package/assets/{folders-lVRpW3Oi.js → folders-BX4mv0sG.js} +1 -1
- package/assets/{index-BBwvcb2-.js → index-C4rK5MC7.js} +1 -1
- package/assets/index-CRro5tRr.js +1 -0
- package/assets/{index-DM4BOCSe.js → index-DQafamIy.js} +9 -9
- package/assets/{kbd-BL9ARcol.js → kbd-CCL5EYSt.js} +1 -1
- package/assets/{labels-BG9ozrln.js → labels-LKfQjQM9.js} +1 -1
- package/assets/{mail-D4MAGaS5.js → mail-IFtY2S37.js} +3 -3
- package/assets/{move-targets-DEb7vdFQ.js → move-targets-_q9cp5GP.js} +1 -1
- package/assets/{onboarding-DQXz37tB.js → onboarding-B6iPevA1.js} +1 -1
- package/assets/{senders-c1CiIVwb.js → senders-BeDv1NAL.js} +1 -1
- package/assets/settings-W1jup8qD.js +1 -0
- package/assets/{settings-screen-CQJ3_bkq.js → settings-screen-CCxtRgGg.js} +1 -1
- package/assets/{shield-check-BNa6R6v-.js → shield-check-zKNWKLzR.js} +1 -1
- package/assets/{suggested-vips-DJ5f1zxE.js → suggested-vips-s7PqaoHr.js} +1 -1
- package/assets/{useDebouncedValue-DAb50Lnx.js → useDebouncedValue-B--1mDhF.js} +1 -1
- package/assets/{useLabels-DxZzFiir.js → useLabels-CFxnGM7k.js} +1 -1
- package/assets/{useRulePreview-DsPeqv-v.js → useRulePreview-7fdjaacZ.js} +1 -1
- package/assets/{useSignature-D28r0EJP.js → useSignature-DzGECw2G.js} +1 -1
- package/index.html +1 -1
- package/package.json +1 -1
- package/assets/index-Cr79p8kD.js +0 -1
- package/assets/settings-CcNrR8So.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-
|
|
2
|
-
import{R as K,c as tf,r as c,a as je,j as r,C as Kt,X as St,b as V,B as ae,d as yt,S as qt,e as Tt,f as os,L as Ms,g as Ia,h as sf,i as nf,k as nn,A as Ta,T as Rt,F as Ra,P as rf,l as rn,u as Xn,m as Ma,n as af,I as El,p as Il,o as Aa,q as of,D as lf,s as an,t as Jn,O as cf,M as uf,v as df,w as Tl,x as ff,y as mf,z as hf,E as pf,G as gf,H as Rl,J as Oa,K as xf,N as Ml,Q as bf,U as vf,V as Da,W as Pa,_ as $t,Y as Al,Z as yf,$ as La,a0 as wf,a1 as Sf,a2 as kf,a3 as ia,a4 as Cf,a5 as jf,a6 as Re,a7 as Nf,a8 as Ef,a9 as If,aa as Tf,ab as Rf,ac as Mf,ad as Bo,ae as Af,af as Of,ag as Df,ah as Fa,ai as Ol,aj as Dl,ak as Ht,al as He,am as it,an as on,ao as $e,ap as $a,aq as _a,ar as za,as as Ba,at as Zn,au as Es,av as Me,aw as ln,ax as ve,ay as Pl,az as Pf,aA as Oe,aB as Ll,aC as Lf,aD as er,aE as tr,aF as Fl,aG as $l,aH as Ff,aI as Mt,aJ as lt,aK as $f,aL as ht,aM as _l,aN as ts,aO as sr,aP as _f,aQ as nr,aR as Ka,aS as Ua,aT as is,aU as rr,aV as ls,aW as zf,aX as Bf,aY as zn,aZ as Kf,a_ as zl,a$ as Is,b0 as Uf,b1 as ar,b2 as qf,b3 as Hf,b4 as Wf,b5 as Bl,b6 as qa,b7 as Vf,b8 as Ko,b9 as Qf,ba as Gf,bb as As,bc as Yf,bd as Et,be as Kl,bf as Xf,bg as Jf,bh as Zf,bi as Ul,bj as em,bk as tm,bl as sm,bm as nm,bn as Uo,bo as rm,bp as am,bq as om,br as im,bs as Ha,bt as la,bu as ca,bv as lm,bw as cm,bx as ql,by as um,bz as Wa,bA as dm,bB as fm,bC as mm,bD as hm,bE as pm,bF as gm,bG as xm,bH as bm,bI as vm,bJ as ym,bK as Pt,bL as Nt,bM as wm}from"./index-DM4BOCSe.js";import{A as wt,M as Va,C as Sm}from"./avatar-CTRk22EW.js";import{K as ks}from"./kbd-BL9ARcol.js";import{S as cn,C as Qa,R as km}from"./shield-check-BNa6R6v-.js";import{M as Hl,a as Cm}from"./account-form-helpers-DIq5DB07.js";import{R as jm,u as Nm}from"./useSignature-D28r0EJP.js";import{u as or}from"./useDebouncedValue-DAb50Lnx.js";import{B as Em,u as Wt,a as qo,b as Ho,c as Im,d as Tm,e as Rm,n as Mm,o as Am,f as Om,g as Dm,S as Pm}from"./useRulePreview-DsPeqv-v.js";import{E as Vt,f as Wl}from"./ErrorState-bMJzrGDP.js";import{f as Vl,a as pt,b as Ql,c as ss,d as Bn,t as Lm}from"./format-CKZmh-Ru.js";import{P as Wo,u as Gl,b as Ga,M as ot}from"./move-targets-DEb7vdFQ.js";import{u as Ya}from"./useLabels-DxZzFiir.js";import{C as Xa}from"./ConfirmDialog-C4hlsYS7.js";import{C as Fm}from"./circle-check-C5io36vF.js";import{F as $m}from"./folder-BcWbB7Pz.js";function Xs(e){if(_m())e.focus({preventScroll:!0});else{let t=zm(e);e.focus(),Bm(t)}}let Sn=null;function _m(){if(Sn==null){Sn=!1;try{document.createElement("div").focus({get preventScroll(){return Sn=!0,!0}})}catch{}}return Sn}function zm(e){let t=e.parentNode,s=[],n=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==n;)(t.offsetHeight<t.scrollHeight||t.offsetWidth<t.scrollWidth)&&s.push({element:t,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft}),t=t.parentNode;return n instanceof HTMLElement&&s.push({element:n,scrollTop:n.scrollTop,scrollLeft:n.scrollLeft}),s}function Bm(e){for(let{element:t,scrollTop:s,scrollLeft:n}of e)t.scrollTop=s,t.scrollLeft=n}const zt=e=>e?.ownerDocument??document,Ut=e=>e&&"window"in e&&e.window===e?e:zt(e).defaultView||window;function Km(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function Um(e){return Km(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let qm=!1;function Yl(){return qm}function vt(e,t){if(!Yl())return t&&e?e.contains(t):!1;if(!e||!t)return!1;let s=t;for(;s!==null;){if(s===e)return!0;s.tagName==="SLOT"&&s.assignedSlot?s=s.assignedSlot.parentNode:Um(s)?s=s.host:s=s.parentNode}return!1}function Be(e){if(Yl()&&e.target instanceof Element&&e.target.shadowRoot){if("composedPath"in e)return e.composedPath()[0]??null;if("composedPath"in e.nativeEvent)return e.nativeEvent.composedPath()[0]??null}return e.target}const Hm=typeof Element<"u"&&"checkVisibility"in Element.prototype;function Wm(e){const t=Ut(e);if(!(e instanceof t.HTMLElement)&&!(e instanceof t.SVGElement))return!1;let{display:s,visibility:n}=e.style,a=s!=="none"&&n!=="hidden"&&n!=="collapse";if(a){const{getComputedStyle:o}=Ut(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function Vm(e,t){return!e.hasAttribute("hidden")&&!e.hasAttribute("data-react-aria-prevent-focus")&&(e.nodeName==="DETAILS"&&t&&t.nodeName!=="SUMMARY"?e.hasAttribute("open"):!0)}function Xl(e,t){return Hm?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&Wm(e)&&Vm(e,t)&&(!e.parentElement||Xl(e.parentElement,e))}const Jl=["input:not([disabled]):not([type=hidden])","select:not([disabled])","textarea:not([disabled])","button:not([disabled])","a[href]","area[href]","summary","iframe","object","embed","audio[controls]","video[controls]",'[contenteditable]:not([contenteditable^="false"])',"permission"],Qm=Jl.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";Jl.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function Gm(e,t){return e.matches(Qm)&&!Ym(e)&&(t?.skipVisibilityCheck||Xl(e))}function Ym(e){let t=e;for(;t!=null;){if(t instanceof Ut(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const Ja=typeof document<"u"?K.useLayoutEffect:()=>{};function Xm(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function Jm(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function Zm(e){for(;e&&!Gm(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Ut(e),s=t.document.activeElement;if(!s||s===e)return;let n=!1,a=d=>{(Be(d)===s||n)&&d.stopImmediatePropagation()},o=d=>{(Be(d)===s||n)&&(d.stopImmediatePropagation(),!e&&!n&&(n=!0,Xs(s),u()))},i=d=>{(Be(d)===e||n)&&d.stopImmediatePropagation()},l=d=>{(Be(d)===e||n)&&(d.stopImmediatePropagation(),n||(n=!0,Xs(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",l,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(m),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",l,!0),t.removeEventListener("focus",i,!0),n=!1},m=requestAnimationFrame(u);return u}function ir(e){if(typeof window>"u"||window.navigator==null)return!1;let t=window.navigator.userAgentData?.brands;return Array.isArray(t)&&t.some(s=>e.test(s.brand))||e.test(window.navigator.userAgent)}function Za(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function Qt(e){let t=null;return()=>(t==null&&(t=e()),t)}const Kn=Qt(function(){return Za(/^Mac/i)}),eh=Qt(function(){return Za(/^iPhone/i)}),Zl=Qt(function(){return Za(/^iPad/i)||Kn()&&navigator.maxTouchPoints>1}),ec=Qt(function(){return eh()||Zl()}),th=Qt(function(){return ir(/AppleWebKit/i)&&!sh()}),sh=Qt(function(){return ir(/Chrome/i)}),tc=Qt(function(){return ir(/Android/i)}),nh=Qt(function(){return ir(/Firefox/i)});function rh(e){return e.pointerType===""&&e.isTrusted?!0:tc()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function ah(e){return!tc()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function Js(e,t,s=!0){let{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}=t;nh()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Kn()?n=!0:a=!0);let l=th()&&Kn()&&!Zl()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});Js.isOpening=s,Xs(e),e.dispatchEvent(l),Js.isOpening=!1}Js.isOpening=!1;let _t=new Map,ua=new Set;function Vo(){if(typeof window>"u")return;function e(n){return"propertyName"in n}let t=n=>{let a=Be(n);if(!e(n)||!a)return;let o=_t.get(a);o||(o=new Set,_t.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(n.propertyName)},s=n=>{let a=Be(n);if(!e(n)||!a)return;let o=_t.get(a);if(o&&(o.delete(n.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),_t.delete(a)),_t.size===0)){for(let i of ua)i();ua.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?Vo():document.addEventListener("DOMContentLoaded",Vo));function oh(){for(const[e]of _t)"isConnected"in e&&!e.isConnected&&_t.delete(e)}function ih(e){requestAnimationFrame(()=>{oh(),_t.size===0?e():ua.add(e)})}function sc(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let da=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{da.delete(e)});function lh(e,t){if(e===t)return e;let s=da.get(e);if(s)return s.forEach(a=>a.current=t),t;let n=da.get(t);return n?(n.forEach(a=>a.current=e),e):t}function ch(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const n=e.map(a=>{const o=Qo(a,t);return s||=typeof o=="function",o});if(s)return()=>{n.forEach((a,o)=>{typeof a=="function"?a():Qo(e[o],null)})}}}function Qo(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Os(...e){let t={...e[0]};for(let s=1;s<e.length;s++){let n=e[s];for(let a in n){let o=t[a],i=n[a];typeof o=="function"&&typeof i=="function"&&a[0]==="o"&&a[1]==="n"&&a.charCodeAt(2)>=65&&a.charCodeAt(2)<=90?t[a]=sc(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=tf(o,i):a==="id"&&o&&i?t.id=lh(o,i):a==="ref"&&o&&i?t.ref=ch(o,i):t[a]=i!==void 0?i:o}}return t}function uh(e,t){Ja(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const dh=K.useInsertionEffect??Ja;function Lr(e){const t=c.useRef(null);return dh(()=>{t.current=e},[e]),c.useCallback((...s)=>{const n=t.current;return n?.(...s)},[])}let ws="default",fa="",Pn=new WeakMap;function fh(e){if(ec()){if(ws==="default"){const t=zt(e);fa=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}ws="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Pn.set(e,e.style[t]),e.style[t]="none"}}function Go(e){if(ec()){if(ws!=="disabled")return;ws="restoring",setTimeout(()=>{ih(()=>{if(ws==="restoring"){const t=zt(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=fa||""),fa="",ws="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Pn.has(e)){let t=Pn.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Pn.delete(e)}}function Yo(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let Fr=new WeakMap;function mh(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return Yo(t);if(Fr.has(t))return Fr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),n=s&&s instanceof Ut(s).HTMLMetaElement&&(s.nonce||s.content)||Yo(t)||void 0;return n!==void 0&&Fr.set(t,n),n}const nc=K.createContext({register:()=>{}});nc.displayName="PressResponderContext";function rc(){let e=c.useRef(new Map),t=c.useCallback((a,o,i,l)=>{let u=l?.once?(...m)=>{e.current.delete(i),i(...m)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:l}),a.addEventListener(o,u,l)},[]),s=c.useCallback((a,o,i,l)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,l),e.current.delete(i)},[]),n=c.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return c.useEffect(()=>n,[n]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:n}}function hh(e){let t=c.useContext(nc);if(t){let{register:s,ref:n,...a}=t;e=Os(a,e),s()}return uh(t,e.ref),e}class kn{#s;constructor(t,s,n,a){this.#s=!0;const i=(a?.target??n.currentTarget)?.getBoundingClientRect();let l,u=0,m,d=null;n.clientX!=null&&n.clientY!=null&&(m=n.clientX,d=n.clientY),i&&(m!=null&&d!=null?(l=m-i.left,u=d-i.top):(l=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=n.currentTarget,this.shiftKey=n.shiftKey,this.metaKey=n.metaKey,this.ctrlKey=n.ctrlKey,this.altKey=n.altKey,this.x=l,this.y=u,this.key=n.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const Xo=Symbol("linkClicked"),Jo="react-aria-pressable-style",Zo="data-react-aria-pressable";function ph(e){let{onPress:t,onPressChange:s,onPressStart:n,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:l,isPressed:u,preventFocusOnPress:m,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:f,ref:h,...g}=hh(e),[x,p]=c.useState(!1),v=c.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:b,removeAllGlobalListeners:S}=rc(),w=c.useCallback((k,P)=>{let F=v.current;if(l||F.didFirePressStart)return!1;let C=!0;if(F.isTriggeringEvent=!0,n){let T=new kn("pressstart",P,k);n(T),C=T.shouldStopPropagation}return s&&s(!0),F.isTriggeringEvent=!1,F.didFirePressStart=!0,p(!0),C},[l,n,s]),y=c.useCallback((k,P,F=!0)=>{let C=v.current;if(!C.didFirePressStart)return!1;C.didFirePressStart=!1,C.isTriggeringEvent=!0;let T=!0;if(a){let I=new kn("pressend",P,k);a(I),T=I.shouldStopPropagation}if(s&&s(!1),p(!1),t&&F&&!l){let I=new kn("press",P,k);t(I),T&&=I.shouldStopPropagation}return C.isTriggeringEvent=!1,T},[l,a,s,t]),j=Lr(y),E=c.useCallback((k,P)=>{let F=v.current;if(l)return!1;if(o){F.isTriggeringEvent=!0;let C=new kn("pressup",P,k);return o(C),F.isTriggeringEvent=!1,C.shouldStopPropagation}return!0},[l,o]),M=Lr(E),N=c.useCallback(k=>{let P=v.current;if(P.isPressed&&P.target){P.didFirePressStart&&P.pointerType!=null&&y(Xt(P.target,k),P.pointerType,!1),P.isPressed=!1,P.isOverTarget=!1,P.activePointerId=null,P.pointerType=null,S(),f||Go(P.target);for(let F of P.disposables)F();P.disposables=[]}},[f,S,y]),A=Lr(N);c.useEffect(()=>{l&&v.current.isPressed&&A({currentTarget:v.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let L=c.useCallback(k=>{d&&N(k)},[d,N]),O=c.useCallback(k=>{l||i?.(k)},[l,i]),D=c.useCallback((k,P)=>{if(!l&&i){let F=new MouseEvent("click",k);Jm(F,P),i(Xm(F))}},[l,i]),R=c.useMemo(()=>{let k=v.current,P={onKeyDown(C){if($r(C.nativeEvent,C.currentTarget)&&vt(C.currentTarget,Be(C))){ei(Be(C),C.key)&&C.preventDefault();let T=!0;!k.isPressed&&!C.repeat&&(k.target=C.currentTarget,k.isPressed=!0,k.pointerType="keyboard",T=w(C,"keyboard"));let I=C.currentTarget,q=se=>{$r(se,I)&&!se.repeat&&vt(I,Be(se))&&k.target&&M(Xt(k.target,se),"keyboard")};b(zt(C.currentTarget),"keyup",sc(q,F),!0),T&&C.stopPropagation(),C.metaKey&&Kn()&&k.metaKeyEvents?.set(C.key,C.nativeEvent)}else C.key==="Meta"&&(k.metaKeyEvents=new Map)},onClick(C){if(!(C&&!vt(C.currentTarget,Be(C)))&&C&&C.button===0&&!k.isTriggeringEvent&&!Js.isOpening){let T=!0;if(l&&C.preventDefault(),!k.ignoreEmulatedMouseEvents&&!k.isPressed&&(k.pointerType==="virtual"||rh(C.nativeEvent))){let I=w(C,"virtual"),q=M(C,"virtual"),se=j(C,"virtual");O(C),T=I&&q&&se}else if(k.isPressed&&k.pointerType!=="keyboard"){let I=k.pointerType||C.nativeEvent.pointerType||"virtual",q=M(Xt(C.currentTarget,C),I),se=j(Xt(C.currentTarget,C),I,!0);T=q&&se,k.isOverTarget=!1,O(C),A(C)}k.ignoreEmulatedMouseEvents=!1,T&&C.stopPropagation()}}},F=C=>{if(k.isPressed&&k.target&&$r(C,k.target)){ei(Be(C),C.key)&&C.preventDefault();let T=Be(C),I=vt(k.target,T);j(Xt(k.target,C),"keyboard",I),I&&D(C,k.target),S(),C.key!=="Enter"&&eo(k.target)&&vt(k.target,T)&&!C[Xo]&&(C[Xo]=!0,Js(k.target,C,!1)),k.isPressed=!1,k.metaKeyEvents?.delete(C.key)}else if(C.key==="Meta"&&k.metaKeyEvents?.size){let T=k.metaKeyEvents;k.metaKeyEvents=void 0;for(let I of T.values())k.target?.dispatchEvent(new KeyboardEvent("keyup",I))}};if(typeof PointerEvent<"u"){P.onPointerDown=I=>{if(I.button!==0||!vt(I.currentTarget,Be(I)))return;if(ah(I.nativeEvent)){k.pointerType="virtual";return}k.pointerType=I.pointerType;let q=!0;if(!k.isPressed){k.isPressed=!0,k.isOverTarget=!0,k.activePointerId=I.pointerId,k.target=I.currentTarget,f||fh(k.target),q=w(I,k.pointerType);let se=Be(I);"releasePointerCapture"in se&&("hasPointerCapture"in se?se.hasPointerCapture(I.pointerId)&&se.releasePointerCapture(I.pointerId):se.releasePointerCapture(I.pointerId)),b(zt(I.currentTarget),"pointerup",C,!1),b(zt(I.currentTarget),"pointercancel",T,!1)}q&&I.stopPropagation()},P.onMouseDown=I=>{if(vt(I.currentTarget,Be(I))&&I.button===0){if(m){let q=Zm(I.target);q&&k.disposables.push(q)}I.stopPropagation()}},P.onPointerUp=I=>{!vt(I.currentTarget,Be(I))||k.pointerType==="virtual"||I.button===0&&!k.isPressed&&M(I,k.pointerType||I.pointerType)},P.onPointerEnter=I=>{I.pointerId===k.activePointerId&&k.target&&!k.isOverTarget&&k.pointerType!=null&&(k.isOverTarget=!0,w(Xt(k.target,I),k.pointerType))},P.onPointerLeave=I=>{I.pointerId===k.activePointerId&&k.target&&k.isOverTarget&&k.pointerType!=null&&(k.isOverTarget=!1,j(Xt(k.target,I),k.pointerType,!1),L(I))};let C=I=>{if(I.pointerId===k.activePointerId&&k.isPressed&&I.button===0&&k.target){if(vt(k.target,Be(I))&&k.pointerType!=null){let q=!1,se=setTimeout(()=>{k.isPressed&&k.target instanceof HTMLElement&&(q?A(I):(Xs(k.target),k.target.click()))},80);b(I.currentTarget,"click",()=>q=!0,!0),k.disposables.push(()=>clearTimeout(se))}else A(I);k.isOverTarget=!1}},T=I=>{A(I)};P.onDragStart=I=>{vt(I.currentTarget,Be(I))&&A(I)}}return P},[b,l,m,S,f,L,w,O,D]);return c.useEffect(()=>{if(!h)return;const k=zt(h.current);if(!k||!k.head||k.getElementById(Jo))return;const P=k.createElement("style");P.id=Jo;let F=mh(k);F&&(P.nonce=F),P.textContent=`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ComposeBody-B7A7M4j3.js","assets/index-DQafamIy.js","assets/index-AAKtgqZz.css","assets/avatar-DfVX_XsZ.js","assets/kbd-CCL5EYSt.js","assets/shield-check-zKNWKLzR.js","assets/account-form-helpers-hmeH-7ez.js","assets/useSignature-DzGECw2G.js","assets/useDebouncedValue-B--1mDhF.js","assets/useRulePreview-7fdjaacZ.js","assets/ErrorState-Bv7-HYh6.js","assets/format-CKZmh-Ru.js","assets/move-targets-_q9cp5GP.js","assets/useLabels-CFxnGM7k.js","assets/ConfirmDialog-D5nahg6y.js","assets/circle-check-D_eO0Xzn.js","assets/folder-CZVXBM8D.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{R as K,c as tf,r as c,a as je,j as r,C as Kt,X as St,b as V,B as ae,d as yt,S as qt,e as Tt,f as os,L as Ms,g as Ia,h as sf,i as nf,k as nn,A as Ta,T as Rt,F as Ra,P as rf,l as rn,u as Xn,m as Ma,n as af,I as El,p as Il,o as Aa,q as of,D as lf,s as an,t as Jn,O as cf,M as uf,v as df,w as Tl,x as ff,y as mf,z as hf,E as pf,G as gf,H as Rl,J as Oa,K as xf,N as Ml,Q as bf,U as vf,V as Da,W as Pa,_ as $t,Y as Al,Z as yf,$ as La,a0 as wf,a1 as Sf,a2 as kf,a3 as ia,a4 as Cf,a5 as jf,a6 as Re,a7 as Nf,a8 as Ef,a9 as If,aa as Tf,ab as Rf,ac as Mf,ad as Bo,ae as Af,af as Of,ag as Df,ah as Fa,ai as Ol,aj as Dl,ak as Ht,al as He,am as it,an as on,ao as $e,ap as $a,aq as _a,ar as za,as as Ba,at as Zn,au as Es,av as Me,aw as ln,ax as ve,ay as Pl,az as Pf,aA as Oe,aB as Ll,aC as Lf,aD as er,aE as tr,aF as Fl,aG as $l,aH as Ff,aI as Mt,aJ as lt,aK as $f,aL as ht,aM as _l,aN as ts,aO as sr,aP as _f,aQ as nr,aR as Ka,aS as Ua,aT as is,aU as rr,aV as ls,aW as zf,aX as Bf,aY as zn,aZ as Kf,a_ as zl,a$ as Is,b0 as Uf,b1 as ar,b2 as qf,b3 as Hf,b4 as Wf,b5 as Bl,b6 as qa,b7 as Vf,b8 as Ko,b9 as Qf,ba as Gf,bb as As,bc as Yf,bd as Et,be as Kl,bf as Xf,bg as Jf,bh as Zf,bi as Ul,bj as em,bk as tm,bl as sm,bm as nm,bn as Uo,bo as rm,bp as am,bq as om,br as im,bs as Ha,bt as la,bu as ca,bv as lm,bw as cm,bx as ql,by as um,bz as Wa,bA as dm,bB as fm,bC as mm,bD as hm,bE as pm,bF as gm,bG as xm,bH as bm,bI as vm,bJ as ym,bK as Pt,bL as Nt,bM as wm}from"./index-DQafamIy.js";import{A as wt,M as Va,C as Sm}from"./avatar-DfVX_XsZ.js";import{K as ks}from"./kbd-CCL5EYSt.js";import{S as cn,C as Qa,R as km}from"./shield-check-zKNWKLzR.js";import{M as Hl,a as Cm}from"./account-form-helpers-hmeH-7ez.js";import{R as jm,u as Nm}from"./useSignature-DzGECw2G.js";import{u as or}from"./useDebouncedValue-B--1mDhF.js";import{B as Em,u as Wt,a as qo,b as Ho,c as Im,d as Tm,e as Rm,n as Mm,o as Am,f as Om,g as Dm,S as Pm}from"./useRulePreview-7fdjaacZ.js";import{E as Vt,f as Wl}from"./ErrorState-Bv7-HYh6.js";import{f as Vl,a as pt,b as Ql,c as ss,d as Bn,t as Lm}from"./format-CKZmh-Ru.js";import{P as Wo,u as Gl,b as Ga,M as ot}from"./move-targets-_q9cp5GP.js";import{u as Ya}from"./useLabels-CFxnGM7k.js";import{C as Xa}from"./ConfirmDialog-D5nahg6y.js";import{C as Fm}from"./circle-check-D_eO0Xzn.js";import{F as $m}from"./folder-CZVXBM8D.js";function Xs(e){if(_m())e.focus({preventScroll:!0});else{let t=zm(e);e.focus(),Bm(t)}}let Sn=null;function _m(){if(Sn==null){Sn=!1;try{document.createElement("div").focus({get preventScroll(){return Sn=!0,!0}})}catch{}}return Sn}function zm(e){let t=e.parentNode,s=[],n=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==n;)(t.offsetHeight<t.scrollHeight||t.offsetWidth<t.scrollWidth)&&s.push({element:t,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft}),t=t.parentNode;return n instanceof HTMLElement&&s.push({element:n,scrollTop:n.scrollTop,scrollLeft:n.scrollLeft}),s}function Bm(e){for(let{element:t,scrollTop:s,scrollLeft:n}of e)t.scrollTop=s,t.scrollLeft=n}const zt=e=>e?.ownerDocument??document,Ut=e=>e&&"window"in e&&e.window===e?e:zt(e).defaultView||window;function Km(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&typeof e.nodeType=="number"}function Um(e){return Km(e)&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e}let qm=!1;function Yl(){return qm}function vt(e,t){if(!Yl())return t&&e?e.contains(t):!1;if(!e||!t)return!1;let s=t;for(;s!==null;){if(s===e)return!0;s.tagName==="SLOT"&&s.assignedSlot?s=s.assignedSlot.parentNode:Um(s)?s=s.host:s=s.parentNode}return!1}function Be(e){if(Yl()&&e.target instanceof Element&&e.target.shadowRoot){if("composedPath"in e)return e.composedPath()[0]??null;if("composedPath"in e.nativeEvent)return e.nativeEvent.composedPath()[0]??null}return e.target}const Hm=typeof Element<"u"&&"checkVisibility"in Element.prototype;function Wm(e){const t=Ut(e);if(!(e instanceof t.HTMLElement)&&!(e instanceof t.SVGElement))return!1;let{display:s,visibility:n}=e.style,a=s!=="none"&&n!=="hidden"&&n!=="collapse";if(a){const{getComputedStyle:o}=Ut(e);let{display:i,visibility:l}=o(e);a=i!=="none"&&l!=="hidden"&&l!=="collapse"}return a}function Vm(e,t){return!e.hasAttribute("hidden")&&!e.hasAttribute("data-react-aria-prevent-focus")&&(e.nodeName==="DETAILS"&&t&&t.nodeName!=="SUMMARY"?e.hasAttribute("open"):!0)}function Xl(e,t){return Hm?e.checkVisibility({visibilityProperty:!0})&&!e.closest("[data-react-aria-prevent-focus]"):e.nodeName!=="#comment"&&Wm(e)&&Vm(e,t)&&(!e.parentElement||Xl(e.parentElement,e))}const Jl=["input:not([disabled]):not([type=hidden])","select:not([disabled])","textarea:not([disabled])","button:not([disabled])","a[href]","area[href]","summary","iframe","object","embed","audio[controls]","video[controls]",'[contenteditable]:not([contenteditable^="false"])',"permission"],Qm=Jl.join(":not([hidden]),")+",[tabindex]:not([disabled]):not([hidden])";Jl.push('[tabindex]:not([tabindex="-1"]):not([disabled])');function Gm(e,t){return e.matches(Qm)&&!Ym(e)&&(t?.skipVisibilityCheck||Xl(e))}function Ym(e){let t=e;for(;t!=null;){if(t instanceof Ut(t).HTMLElement&&t.inert)return!0;t=t.parentElement}return!1}const Ja=typeof document<"u"?K.useLayoutEffect:()=>{};function Xm(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function Jm(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}function Zm(e){for(;e&&!Gm(e,{skipVisibilityCheck:!0});)e=e.parentElement;let t=Ut(e),s=t.document.activeElement;if(!s||s===e)return;let n=!1,a=d=>{(Be(d)===s||n)&&d.stopImmediatePropagation()},o=d=>{(Be(d)===s||n)&&(d.stopImmediatePropagation(),!e&&!n&&(n=!0,Xs(s),u()))},i=d=>{(Be(d)===e||n)&&d.stopImmediatePropagation()},l=d=>{(Be(d)===e||n)&&(d.stopImmediatePropagation(),n||(n=!0,Xs(s),u()))};t.addEventListener("blur",a,!0),t.addEventListener("focusout",o,!0),t.addEventListener("focusin",l,!0),t.addEventListener("focus",i,!0);let u=()=>{cancelAnimationFrame(m),t.removeEventListener("blur",a,!0),t.removeEventListener("focusout",o,!0),t.removeEventListener("focusin",l,!0),t.removeEventListener("focus",i,!0),n=!1},m=requestAnimationFrame(u);return u}function ir(e){if(typeof window>"u"||window.navigator==null)return!1;let t=window.navigator.userAgentData?.brands;return Array.isArray(t)&&t.some(s=>e.test(s.brand))||e.test(window.navigator.userAgent)}function Za(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.userAgentData?.platform||window.navigator.platform):!1}function Qt(e){let t=null;return()=>(t==null&&(t=e()),t)}const Kn=Qt(function(){return Za(/^Mac/i)}),eh=Qt(function(){return Za(/^iPhone/i)}),Zl=Qt(function(){return Za(/^iPad/i)||Kn()&&navigator.maxTouchPoints>1}),ec=Qt(function(){return eh()||Zl()}),th=Qt(function(){return ir(/AppleWebKit/i)&&!sh()}),sh=Qt(function(){return ir(/Chrome/i)}),tc=Qt(function(){return ir(/Android/i)}),nh=Qt(function(){return ir(/Firefox/i)});function rh(e){return e.pointerType===""&&e.isTrusted?!0:tc()&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function ah(e){return!tc()&&e.width===0&&e.height===0||e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"}function Js(e,t,s=!0){let{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}=t;nh()&&window.event?.type?.startsWith("key")&&e.target==="_blank"&&(Kn()?n=!0:a=!0);let l=th()&&Kn()&&!Zl()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:n,ctrlKey:a,altKey:o,shiftKey:i}):new MouseEvent("click",{metaKey:n,ctrlKey:a,altKey:o,shiftKey:i,detail:1,bubbles:!0,cancelable:!0});Js.isOpening=s,Xs(e),e.dispatchEvent(l),Js.isOpening=!1}Js.isOpening=!1;let _t=new Map,ua=new Set;function Vo(){if(typeof window>"u")return;function e(n){return"propertyName"in n}let t=n=>{let a=Be(n);if(!e(n)||!a)return;let o=_t.get(a);o||(o=new Set,_t.set(a,o),a.addEventListener("transitioncancel",s,{once:!0})),o.add(n.propertyName)},s=n=>{let a=Be(n);if(!e(n)||!a)return;let o=_t.get(a);if(o&&(o.delete(n.propertyName),o.size===0&&(a.removeEventListener("transitioncancel",s),_t.delete(a)),_t.size===0)){for(let i of ua)i();ua.clear()}};document.body.addEventListener("transitionrun",t),document.body.addEventListener("transitionend",s)}typeof document<"u"&&(document.readyState!=="loading"?Vo():document.addEventListener("DOMContentLoaded",Vo));function oh(){for(const[e]of _t)"isConnected"in e&&!e.isConnected&&_t.delete(e)}function ih(e){requestAnimationFrame(()=>{oh(),_t.size===0?e():ua.add(e)})}function sc(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}let da=new Map;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{da.delete(e)});function lh(e,t){if(e===t)return e;let s=da.get(e);if(s)return s.forEach(a=>a.current=t),t;let n=da.get(t);return n?(n.forEach(a=>a.current=e),e):t}function ch(...e){return e.length===1&&e[0]?e[0]:t=>{let s=!1;const n=e.map(a=>{const o=Qo(a,t);return s||=typeof o=="function",o});if(s)return()=>{n.forEach((a,o)=>{typeof a=="function"?a():Qo(e[o],null)})}}}function Qo(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Os(...e){let t={...e[0]};for(let s=1;s<e.length;s++){let n=e[s];for(let a in n){let o=t[a],i=n[a];typeof o=="function"&&typeof i=="function"&&a[0]==="o"&&a[1]==="n"&&a.charCodeAt(2)>=65&&a.charCodeAt(2)<=90?t[a]=sc(o,i):(a==="className"||a==="UNSAFE_className")&&typeof o=="string"&&typeof i=="string"?t[a]=tf(o,i):a==="id"&&o&&i?t.id=lh(o,i):a==="ref"&&o&&i?t.ref=ch(o,i):t[a]=i!==void 0?i:o}}return t}function uh(e,t){Ja(()=>{if(e&&e.ref&&t)return e.ref.current=t.current,()=>{e.ref&&(e.ref.current=null)}})}const dh=K.useInsertionEffect??Ja;function Lr(e){const t=c.useRef(null);return dh(()=>{t.current=e},[e]),c.useCallback((...s)=>{const n=t.current;return n?.(...s)},[])}let ws="default",fa="",Pn=new WeakMap;function fh(e){if(ec()){if(ws==="default"){const t=zt(e);fa=t.documentElement.style.webkitUserSelect,t.documentElement.style.webkitUserSelect="none"}ws="disabled"}else if(e instanceof HTMLElement||e instanceof SVGElement){let t="userSelect"in e.style?"userSelect":"webkitUserSelect";Pn.set(e,e.style[t]),e.style[t]="none"}}function Go(e){if(ec()){if(ws!=="disabled")return;ws="restoring",setTimeout(()=>{ih(()=>{if(ws==="restoring"){const t=zt(e);t.documentElement.style.webkitUserSelect==="none"&&(t.documentElement.style.webkitUserSelect=fa||""),fa="",ws="default"}})},300)}else if((e instanceof HTMLElement||e instanceof SVGElement)&&e&&Pn.has(e)){let t=Pn.get(e),s="userSelect"in e.style?"userSelect":"webkitUserSelect";e.style[s]==="none"&&(e.style[s]=t),e.getAttribute("style")===""&&e.removeAttribute("style"),Pn.delete(e)}}function Yo(e){return e?.defaultView?.__webpack_nonce__||globalThis.__webpack_nonce__||void 0}let Fr=new WeakMap;function mh(e){let t=e??(typeof document<"u"?document:void 0);if(!t)return Yo(t);if(Fr.has(t))return Fr.get(t);let s=t.querySelector('meta[property="csp-nonce"]'),n=s&&s instanceof Ut(s).HTMLMetaElement&&(s.nonce||s.content)||Yo(t)||void 0;return n!==void 0&&Fr.set(t,n),n}const nc=K.createContext({register:()=>{}});nc.displayName="PressResponderContext";function rc(){let e=c.useRef(new Map),t=c.useCallback((a,o,i,l)=>{let u=l?.once?(...m)=>{e.current.delete(i),i(...m)}:i;e.current.set(i,{type:o,eventTarget:a,fn:u,options:l}),a.addEventListener(o,u,l)},[]),s=c.useCallback((a,o,i,l)=>{let u=e.current.get(i)?.fn||i;a.removeEventListener(o,u,l),e.current.delete(i)},[]),n=c.useCallback(()=>{e.current.forEach((a,o)=>{s(a.eventTarget,a.type,o,a.options)})},[s]);return c.useEffect(()=>n,[n]),{addGlobalListener:t,removeGlobalListener:s,removeAllGlobalListeners:n}}function hh(e){let t=c.useContext(nc);if(t){let{register:s,ref:n,...a}=t;e=Os(a,e),s()}return uh(t,e.ref),e}class kn{#s;constructor(t,s,n,a){this.#s=!0;const i=(a?.target??n.currentTarget)?.getBoundingClientRect();let l,u=0,m,d=null;n.clientX!=null&&n.clientY!=null&&(m=n.clientX,d=n.clientY),i&&(m!=null&&d!=null?(l=m-i.left,u=d-i.top):(l=i.width/2,u=i.height/2)),this.type=t,this.pointerType=s,this.target=n.currentTarget,this.shiftKey=n.shiftKey,this.metaKey=n.metaKey,this.ctrlKey=n.ctrlKey,this.altKey=n.altKey,this.x=l,this.y=u,this.key=n.key}continuePropagation(){this.#s=!1}get shouldStopPropagation(){return this.#s}}const Xo=Symbol("linkClicked"),Jo="react-aria-pressable-style",Zo="data-react-aria-pressable";function ph(e){let{onPress:t,onPressChange:s,onPressStart:n,onPressEnd:a,onPressUp:o,onClick:i,isDisabled:l,isPressed:u,preventFocusOnPress:m,shouldCancelOnPointerExit:d,allowTextSelectionOnPress:f,ref:h,...g}=hh(e),[x,p]=c.useState(!1),v=c.useRef({isPressed:!1,ignoreEmulatedMouseEvents:!1,didFirePressStart:!1,isTriggeringEvent:!1,activePointerId:null,target:null,isOverTarget:!1,pointerType:null,disposables:[]}),{addGlobalListener:b,removeAllGlobalListeners:S}=rc(),w=c.useCallback((k,P)=>{let F=v.current;if(l||F.didFirePressStart)return!1;let C=!0;if(F.isTriggeringEvent=!0,n){let T=new kn("pressstart",P,k);n(T),C=T.shouldStopPropagation}return s&&s(!0),F.isTriggeringEvent=!1,F.didFirePressStart=!0,p(!0),C},[l,n,s]),y=c.useCallback((k,P,F=!0)=>{let C=v.current;if(!C.didFirePressStart)return!1;C.didFirePressStart=!1,C.isTriggeringEvent=!0;let T=!0;if(a){let I=new kn("pressend",P,k);a(I),T=I.shouldStopPropagation}if(s&&s(!1),p(!1),t&&F&&!l){let I=new kn("press",P,k);t(I),T&&=I.shouldStopPropagation}return C.isTriggeringEvent=!1,T},[l,a,s,t]),j=Lr(y),E=c.useCallback((k,P)=>{let F=v.current;if(l)return!1;if(o){F.isTriggeringEvent=!0;let C=new kn("pressup",P,k);return o(C),F.isTriggeringEvent=!1,C.shouldStopPropagation}return!0},[l,o]),M=Lr(E),N=c.useCallback(k=>{let P=v.current;if(P.isPressed&&P.target){P.didFirePressStart&&P.pointerType!=null&&y(Xt(P.target,k),P.pointerType,!1),P.isPressed=!1,P.isOverTarget=!1,P.activePointerId=null,P.pointerType=null,S(),f||Go(P.target);for(let F of P.disposables)F();P.disposables=[]}},[f,S,y]),A=Lr(N);c.useEffect(()=>{l&&v.current.isPressed&&A({currentTarget:v.current.target,shiftKey:!1,ctrlKey:!1,metaKey:!1,altKey:!1})},[l]);let L=c.useCallback(k=>{d&&N(k)},[d,N]),O=c.useCallback(k=>{l||i?.(k)},[l,i]),D=c.useCallback((k,P)=>{if(!l&&i){let F=new MouseEvent("click",k);Jm(F,P),i(Xm(F))}},[l,i]),R=c.useMemo(()=>{let k=v.current,P={onKeyDown(C){if($r(C.nativeEvent,C.currentTarget)&&vt(C.currentTarget,Be(C))){ei(Be(C),C.key)&&C.preventDefault();let T=!0;!k.isPressed&&!C.repeat&&(k.target=C.currentTarget,k.isPressed=!0,k.pointerType="keyboard",T=w(C,"keyboard"));let I=C.currentTarget,q=se=>{$r(se,I)&&!se.repeat&&vt(I,Be(se))&&k.target&&M(Xt(k.target,se),"keyboard")};b(zt(C.currentTarget),"keyup",sc(q,F),!0),T&&C.stopPropagation(),C.metaKey&&Kn()&&k.metaKeyEvents?.set(C.key,C.nativeEvent)}else C.key==="Meta"&&(k.metaKeyEvents=new Map)},onClick(C){if(!(C&&!vt(C.currentTarget,Be(C)))&&C&&C.button===0&&!k.isTriggeringEvent&&!Js.isOpening){let T=!0;if(l&&C.preventDefault(),!k.ignoreEmulatedMouseEvents&&!k.isPressed&&(k.pointerType==="virtual"||rh(C.nativeEvent))){let I=w(C,"virtual"),q=M(C,"virtual"),se=j(C,"virtual");O(C),T=I&&q&&se}else if(k.isPressed&&k.pointerType!=="keyboard"){let I=k.pointerType||C.nativeEvent.pointerType||"virtual",q=M(Xt(C.currentTarget,C),I),se=j(Xt(C.currentTarget,C),I,!0);T=q&&se,k.isOverTarget=!1,O(C),A(C)}k.ignoreEmulatedMouseEvents=!1,T&&C.stopPropagation()}}},F=C=>{if(k.isPressed&&k.target&&$r(C,k.target)){ei(Be(C),C.key)&&C.preventDefault();let T=Be(C),I=vt(k.target,T);j(Xt(k.target,C),"keyboard",I),I&&D(C,k.target),S(),C.key!=="Enter"&&eo(k.target)&&vt(k.target,T)&&!C[Xo]&&(C[Xo]=!0,Js(k.target,C,!1)),k.isPressed=!1,k.metaKeyEvents?.delete(C.key)}else if(C.key==="Meta"&&k.metaKeyEvents?.size){let T=k.metaKeyEvents;k.metaKeyEvents=void 0;for(let I of T.values())k.target?.dispatchEvent(new KeyboardEvent("keyup",I))}};if(typeof PointerEvent<"u"){P.onPointerDown=I=>{if(I.button!==0||!vt(I.currentTarget,Be(I)))return;if(ah(I.nativeEvent)){k.pointerType="virtual";return}k.pointerType=I.pointerType;let q=!0;if(!k.isPressed){k.isPressed=!0,k.isOverTarget=!0,k.activePointerId=I.pointerId,k.target=I.currentTarget,f||fh(k.target),q=w(I,k.pointerType);let se=Be(I);"releasePointerCapture"in se&&("hasPointerCapture"in se?se.hasPointerCapture(I.pointerId)&&se.releasePointerCapture(I.pointerId):se.releasePointerCapture(I.pointerId)),b(zt(I.currentTarget),"pointerup",C,!1),b(zt(I.currentTarget),"pointercancel",T,!1)}q&&I.stopPropagation()},P.onMouseDown=I=>{if(vt(I.currentTarget,Be(I))&&I.button===0){if(m){let q=Zm(I.target);q&&k.disposables.push(q)}I.stopPropagation()}},P.onPointerUp=I=>{!vt(I.currentTarget,Be(I))||k.pointerType==="virtual"||I.button===0&&!k.isPressed&&M(I,k.pointerType||I.pointerType)},P.onPointerEnter=I=>{I.pointerId===k.activePointerId&&k.target&&!k.isOverTarget&&k.pointerType!=null&&(k.isOverTarget=!0,w(Xt(k.target,I),k.pointerType))},P.onPointerLeave=I=>{I.pointerId===k.activePointerId&&k.target&&k.isOverTarget&&k.pointerType!=null&&(k.isOverTarget=!1,j(Xt(k.target,I),k.pointerType,!1),L(I))};let C=I=>{if(I.pointerId===k.activePointerId&&k.isPressed&&I.button===0&&k.target){if(vt(k.target,Be(I))&&k.pointerType!=null){let q=!1,se=setTimeout(()=>{k.isPressed&&k.target instanceof HTMLElement&&(q?A(I):(Xs(k.target),k.target.click()))},80);b(I.currentTarget,"click",()=>q=!0,!0),k.disposables.push(()=>clearTimeout(se))}else A(I);k.isOverTarget=!1}},T=I=>{A(I)};P.onDragStart=I=>{vt(I.currentTarget,Be(I))&&A(I)}}return P},[b,l,m,S,f,L,w,O,D]);return c.useEffect(()=>{if(!h)return;const k=zt(h.current);if(!k||!k.head||k.getElementById(Jo))return;const P=k.createElement("style");P.id=Jo;let F=mh(k);F&&(P.nonce=F),P.textContent=`
|
|
3
3
|
@layer {
|
|
4
4
|
[${Zo}] {
|
|
5
5
|
touch-action: pan-x pan-y pinch-zoom;
|
|
@@ -113,6 +113,6 @@ a, a:visited {
|
|
|
113
113
|
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
114
114
|
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
115
115
|
`)},Nb=0,bs=[];function Eb(e){var t=c.useRef([]),s=c.useRef([0,0]),n=c.useRef(),a=c.useState(Nb++)[0],o=c.useState(Hc)[0],i=c.useRef(e);c.useEffect(function(){i.current=e},[e]),c.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var p=yf([e.lockRef.current],(e.shards||[]).map(Hi),!0).filter(Boolean);return p.forEach(function(v){return v.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),p.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var l=c.useCallback(function(p,v){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return!i.current.allowPinchZoom;var b=Tn(p),S=s.current,w="deltaX"in p?p.deltaX:S[0]-b[0],y="deltaY"in p?p.deltaY:S[1]-b[1],j,E=p.target,M=Math.abs(w)>Math.abs(y)?"h":"v";if("touches"in p&&M==="h"&&E.type==="range")return!1;var N=window.getSelection(),A=N&&N.anchorNode,L=A?A===E||A.contains(E):!1;if(L)return!1;var O=Ui(M,E);if(!O)return!0;if(O?j=M:(j=M==="v"?"h":"v",O=Ui(M,E)),!O)return!1;if(!n.current&&"changedTouches"in p&&(w||y)&&(n.current=j),!j)return!0;var D=n.current||j;return kb(D,v,p,D==="h"?w:y)},[]),u=c.useCallback(function(p){var v=p;if(!(!bs.length||bs[bs.length-1]!==o)){var b="deltaY"in v?qi(v):Tn(v),S=t.current.filter(function(j){return j.name===v.type&&(j.target===v.target||v.target===j.shadowParent)&&Cb(j.delta,b)})[0];if(S&&S.should){v.cancelable&&v.preventDefault();return}if(!S){var w=(i.current.shards||[]).map(Hi).filter(Boolean).filter(function(j){return j.contains(v.target)}),y=w.length>0?l(v,w[0]):!i.current.noIsolation;y&&v.cancelable&&v.preventDefault()}}},[]),m=c.useCallback(function(p,v,b,S){var w={name:p,delta:v,target:b,should:S,shadowParent:Ib(b)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(y){return y!==w})},1)},[]),d=c.useCallback(function(p){s.current=Tn(p),n.current=void 0},[]),f=c.useCallback(function(p){m(p.type,qi(p),p.target,l(p,e.lockRef.current))},[]),h=c.useCallback(function(p){m(p.type,Tn(p),p.target,l(p,e.lockRef.current))},[]);c.useEffect(function(){return bs.push(o),e.setCallbacks({onScrollCapture:f,onWheelCapture:f,onTouchMoveCapture:h}),document.addEventListener("wheel",u,xs),document.addEventListener("touchmove",u,xs),document.addEventListener("touchstart",d,xs),function(){bs=bs.filter(function(p){return p!==o}),document.removeEventListener("wheel",u,xs),document.removeEventListener("touchmove",u,xs),document.removeEventListener("touchstart",d,xs)}},[]);var g=e.removeScrollBar,x=e.inert;return c.createElement(c.Fragment,null,x?c.createElement(o,{styles:jb(a)}):null,g?c.createElement(gb,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Ib(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Tb=nb(qc,Eb);var Gc=c.forwardRef(function(e,t){return c.createElement(pr,$t({},e,{ref:t,sideCar:Tb}))});Gc.classNames=pr.classNames;var Rb=class extends La{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:s}=e,n=super.createResult(e,t),{isFetching:a,isRefetching:o,isError:i,isRefetchError:l}=n,u=s.fetchMeta?.fetchMore?.direction,m=i&&u==="forward",d=a&&u==="forward",f=i&&u==="backward",h=a&&u==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Sf(t,s.data),hasPreviousPage:wf(t,s.data),isFetchNextPageError:m,isFetchingNextPage:d,isFetchPreviousPageError:f,isFetchingPreviousPage:h,isRefetchError:l&&!m&&!f,isRefetching:o&&!d&&!h}}};function Wi(e,t){const s=new Set(t);return e.filter(n=>!s.has(n))}function Mb(e,t,s){const n=e.slice(0);return n[t]=s,n}var Ab=class extends kf{#s;#e;#a;#r;#t;#n;#o;#i;#l;#c=[];constructor(e,t,s){super(),this.#s=e,this.#r=s,this.#a=[],this.#t=[],this.#e=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#t.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#t.forEach(e=>{e.destroy()})}setQueries(e,t){this.#a=e,this.#r=t,ia.batch(()=>{const s=this.#t,n=this.#f(this.#a);n.forEach(d=>d.observer.setOptions(d.defaultedQueryOptions));const a=n.map(d=>d.observer),o=a.map(d=>d.getCurrentResult()),i=s.length!==a.length,l=a.some((d,f)=>d!==s[f]),u=i||l,m=u?!0:o.some((d,f)=>{const h=this.#e[f];return!h||!Cf(d,h)});!u&&!m||(u&&(this.#c=n,this.#t=a),this.#e=o,this.hasListeners()&&(u&&(Wi(s,a).forEach(d=>{d.destroy()}),Wi(a,s).forEach(d=>{d.subscribe(f=>{this.#m(d,f)})})),this.#h()))})}getCurrentResult(){return this.#e}getQueries(){return this.#t.map(e=>e.getCurrentQuery())}getObservers(){return this.#t}getOptimisticResult(e,t){const s=this.#f(e),n=s.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions)),a=s.map(o=>o.defaultedQueryOptions.queryHash);return[n,o=>this.#d(o??n,t,a),()=>this.#u(n,s)]}#u(e,t){return t.map((s,n)=>{const a=e[n];return s.defaultedQueryOptions.notifyOnChangeProps?a:s.observer.trackResult(a,o=>{t.forEach(i=>{i.observer.trackProp(o)})})})}#d(e,t,s){if(t){const n=this.#l,a=s!==void 0&&n!==void 0&&(n.length!==s.length||s.some((o,i)=>o!==n[i]));return(!this.#n||this.#e!==this.#i||a||t!==this.#o)&&(this.#o=t,this.#i=this.#e,s!==void 0&&(this.#l=s),this.#n=jf(this.#n,t(e))),this.#n}return e}#p(){return this.#r?.combine!==void 0&&this.#t.some((e,t)=>e.options.suspense&&this.#e[t]?.data===void 0)}#f(e){const t=new Map;this.#t.forEach(n=>{const a=n.options.queryHash;if(!a)return;const o=t.get(a);o?o.push(n):t.set(a,[n])});const s=[];return e.forEach(n=>{const a=this.#s.defaultQueryOptions(n),i=t.get(a.queryHash)?.shift()??new La(this.#s,a);s.push({defaultedQueryOptions:a,observer:i})}),s}#m(e,t){const s=this.#t.indexOf(e);s!==-1&&(this.#e=Mb(this.#e,s,t),this.#h())}#h(){if(this.hasListeners()){const e=this.#u(this.#e,this.#c),t=this.#p(),s=this.#n,n=t?s:this.#d(e,this.#r?.combine);(t||s!==n)&&ia.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}};function gt({queries:e,...t},s){const n=Re(),a=Nf(),o=Ef(),i=c.useMemo(()=>e.map(p=>{const v=n.defaultQueryOptions(p);return v._optimisticResults=a?"isRestoring":"optimistic",v}),[e,n,a]);i.forEach(p=>{If(p);const v=n.getQueryCache().get(p.queryHash);Tf(p,o,v)}),Rf(o);const[l]=c.useState(()=>new Ab(n,i,t)),[u,m,d]=l.getOptimisticResult(i,t.combine),f=!a&&t.subscribed!==!1;c.useSyncExternalStore(c.useCallback(p=>f?l.subscribe(ia.batchCalls(p)):Mf,[l,f]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),c.useEffect(()=>{l.setQueries(i,t)},[i,t,l]);const g=u.some((p,v)=>Bo(i[v],p))?u.flatMap((p,v)=>{const b=i[v];if(b&&Bo(b,p)){const S=new La(n,b);return Af(b,S,o)}return[]}):[];if(g.length>0)throw Promise.all(g);const x=u.find((p,v)=>{const b=i[v];return b&&Of({result:p,errorResetBoundary:o,throwOnError:b.throwOnError,query:n.getQueryCache().get(b.queryHash),suspense:b.suspense})});if(x?.error)throw x.error;return m(d())}function Yc(e,t){return Df(e,Rb)}function Ob(e,t){if(e===void 0)return{shouldBlockFn:()=>!0,withResolver:!1};if("shouldBlockFn"in e)return e;if(typeof e=="function")return{shouldBlockFn:async()=>await e(),enableBeforeUnload:!0,withResolver:!1};const s=!!(e.condition??!0),n=e.blockerFn;return{shouldBlockFn:async()=>s&&n!==void 0?await n():s,enableBeforeUnload:s,withResolver:n===void 0}}function Xc(e,t){const{shouldBlockFn:s,enableBeforeUnload:n=!0,disabled:a=!1,withResolver:o=!1}=Ob(e),i=Fa(),{history:l}=i,[u,m]=c.useState({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0});return c.useEffect(()=>{const d=async f=>{function h(b){const S=i.parseLocation(b),w=i.getMatchedRoutes(S.pathname);return w.foundRoute===void 0?{routeId:"__notFound__",fullPath:S.pathname,pathname:S.pathname,params:w.routeParams,search:i.options.parseSearch(b.search)}:{routeId:w.foundRoute.id,fullPath:w.foundRoute.fullPath,pathname:S.pathname,params:w.routeParams,search:i.options.parseSearch(b.search)}}const g=h(f.currentLocation),x=h(f.nextLocation);if(g.routeId==="__notFound__"&&x.routeId!=="__notFound__")return!1;const p=await s({action:f.action,current:g,next:x});if(!o)return p;if(!p)return!1;const v=await new Promise(b=>{m({status:"blocked",current:g,next:x,action:f.action,proceed:()=>b(!1),reset:()=>b(!0)})});return m({status:"idle",current:void 0,next:void 0,action:void 0,proceed:void 0,reset:void 0}),v};return a?void 0:l.block({blockerFn:d,enableBeforeUnload:n})},[s,n,a,o,l,i]),u}function It(e){const t=Fa({warn:e?.router===void 0}),s=e?.router||t;return Ol(s.stores.__store,Dl(e,s))}function gr(e){const t=Fa();return Ol(t.stores.location,Dl(e,t))}const Db=new Set(["outbox","flagged"]),Pb=e=>{const[,t,s]=e.split(/[?#]/)[0].split("/");return t!=="mail"||!s?!1:!Db.has(s)};function Lb(e){const t=gt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0}))});for(const[s,n]of e.entries()){const a=t[s];if(!a||a.isPending)return;const o=a.data?.items??[];if(o.length===0)continue;const i=on(n.folderAppointments);return(o.find(u=>i.get(u.mailboxId)==="inbox")??o[0])?.mailboxId}}function Jc(e){const{openCompose:t}=Ht(),s=He(),n=gr(),a=Lb(e);return c.useCallback(()=>{if(Pb(n.pathname)){c.startTransition(()=>{t({mode:"new"})});return}a&&(c.startTransition(()=>{t({mode:"new"})}),s({to:"/mail/$mailboxId",params:{mailboxId:a}}))},[t,s,n.pathname,a])}const Fb=e=>e.startsWith("/mail")||e.startsWith("/settings"),$b=({accounts:e})=>{const{state:t}=Ht(),s=gr(),n=Jc(e),a=s.search,o=typeof a?.selectedMessageId=="string"&&a.selectedMessageId.length>0;return!Fb(s.pathname)||t.isOpen||o?null:r.jsx("button",{type:"button",onClick:n,"aria-label":"Compose new message",className:"lg:hidden fixed right-4 z-30 h-14 w-14 rounded-full bg-accent text-accent-fg shadow-lg flex items-center justify-center hover:opacity-90 active:scale-95 transition-all",style:{bottom:"calc(env(safe-area-inset-bottom, 0) + 1rem)"},children:r.jsx(Eh,{className:"size-6"})})},Zc=({trigger:e,children:t,align:s="right"})=>{const[n,a]=c.useState(!1),o=c.useRef(null),i=c.useCallback(u=>{o.current&&!o.current.contains(u.target)&&a(!1)},[]),l=c.useCallback(u=>{u.key==="Escape"&&a(!1)},[]);return c.useEffect(()=>(n&&(document.addEventListener("mousedown",i),document.addEventListener("keydown",l)),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("keydown",l)}),[n,i,l]),r.jsxs("div",{ref:o,className:"relative",children:[r.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),a(!n)},className:$e("p-1.5 min-h-11 min-w-11 inline-flex items-center justify-center rounded-md transition-colors","hover:bg-surface-raised text-fg-muted hover:text-fg"),children:e}),n&&r.jsx("div",{className:$e("absolute z-50 mt-1 min-w-[180px] py-1","bg-surface border border-line rounded-md shadow-lg",s==="right"?"right-0":"left-0"),children:t})]})},Ss=({onClick:e,disabled:t,destructive:s,children:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t||e()},disabled:t,className:$e("w-full px-3 py-2 text-left text-sm transition-colors","flex items-center gap-2",t&&"opacity-50 cursor-not-allowed",!t&&"hover:bg-surface-raised",s&&"text-danger hover:text-danger"),children:n}),xa=()=>r.jsx("div",{className:"my-1 h-px bg-line"}),eu=({children:e})=>{const{Account:t}=$a();return r.jsx(t,{children:e})},_b=({email:e,onSignOut:t})=>{const s=He(),n=e??"Account";return r.jsxs(Zc,{trigger:r.jsx(wt,{name:n,email:e??void 0,size:"sm"}),align:"right",children:[e&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 py-2 text-xs text-fg-muted truncate",title:e,"data-testid":"account-menu-email",children:e}),r.jsx(xa,{})]}),r.jsxs(Ss,{onClick:()=>s({to:"/settings/accounts"}),children:[r.jsx(to,{className:"size-4"}),"Settings"]}),r.jsx(xa,{}),r.jsxs(Ss,{onClick:t,children:[r.jsx(dc,{className:"size-4"}),"Sign out"]})]})},zb=()=>r.jsx(eu,{children:({email:e,signOut:t})=>r.jsx(_b,{email:e,onSignOut:t})}),Vi=()=>{const e=_a(),t=za(e);window.open(t,"_blank","noopener,noreferrer")};function tu({variant:e="icon"}){return e==="drawer"?r.jsxs("button",{type:"button",onClick:Vi,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[r.jsx(ti,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Report a bug"})]}):r.jsx(ae,{variant:"ghost",size:"sm",icon:r.jsx(ti,{className:"size-4"}),title:"Report a bug","aria-label":"Report a bug",onClick:Vi})}const su="/mail/",uo="/mail/$mailboxId",nu="/mail/outbox",ru="/mail/flagged";function fo(e){return e.some(t=>t.routeId===su)}function un(e){return e.some(t=>t.routeId===ru)}function xr(e){return e.some(t=>t.routeId===nu)}function au(e){return e.some(t=>t.routeId===uo)}function Bb(e){const t=e.find(s=>s.params?.mailboxId)?.params?.mailboxId;return t?`${uo}:${t}`:un(e)?ru:xr(e)?nu:fo(e)?su:""}const $n="search-scope";function Kb(e){const t=e.trim().replace(/\s+/g," ").toLowerCase();return/\s/.test(t)?`in:"${t}"`:`in:${t}`}function ou(e){return un(e)||xr(e)||au(e)}function iu(e){return e.find(t=>t.routeId===uo)?.params?.mailboxId}function Ub(e){const t=iu(e.matches);return t||(ou(e.matches)?e.callerMailboxId:e.callerMailboxId??e.inTokenMailboxId)}function qb(e,t){return fo(e)?{kind:"global"}:un(e)?{kind:"scoped",chip:{id:$n,label:"is:starred"}}:xr(e)?{kind:"scoped",chip:{id:$n,label:"in:outbox"}}:au(e)?t?{kind:"scoped",chip:{id:$n,label:Kb(t)}}:{kind:"pending"}:{kind:"global"}}function Hb(e,t,s){return t.kind==="global"?{kind:"global"}:un(e)?{kind:"collection"}:{kind:"folder",...s?{role:s}:{}}}const lu=({accounts:e})=>{const t=Ba({strict:!1}),s=gr(),n=t.mailboxId,{t:a}=Zn("mail",{useSuspense:!1}),o=c.useCallback((l,u)=>a(l,{defaultValue:u}),[a]),i=gt({queries:e.map(l=>({...it({path:{accountId:l.accountId}}),staleTime:1/0}))});if(s.pathname.startsWith("/mail/outbox"))return"Outbox";if(!n)return null;for(let l=0;l<e.length;l++){const u=i[l]?.data?.items;if(!u)continue;const m=u.find(f=>f.mailboxId===n);if(!m)continue;const d=on(e[l].folderAppointments);return Es(m,d.get(n),o)}return null},Wb=({accounts:e})=>{const s=Ba({strict:!1}).mailboxId,n=gt({queries:e.map(a=>({...it({path:{accountId:a.accountId}}),staleTime:1/0}))});if(!s)return null;for(const a of n){const o=a.data?.items;if(!o)continue;const i=o.find(l=>l.mailboxId===s);if(i)return i.unseenCount}return null};function cu(e){const t=He(),{searchInput:s}=Me(),n=lu({accounts:e}),a=It({select:l=>l.matches}),o=qb(a,n),i=c.useCallback(l=>{l===$n&&t({to:"/mail",search:{q:s||void 0,selectedMessageId:void 0}})},[t,s]);return{scope:o,clearScope:i}}const uu=[{title:"Navigation",hints:[{action:"focusNext",keys:["j"],description:"Focus next message"},{action:"focusPrevious",keys:["k"],description:"Focus previous message"},{action:"focusNext",keys:["↓"],description:"Focus next message"},{action:"focusPrevious",keys:["↑"],description:"Focus previous message"},{action:"focusFirst",keys:["Home"],description:"Focus first"},{action:"focusLast",keys:["End"],description:"Focus last"},{action:"openFocused",keys:["Enter"],description:"Open focused thread"},{action:"back",keys:["Esc"],description:"Back / close overlay"}]},{title:"Selection",hints:[{action:"toggleSelect",keys:["x"],description:"Toggle select"},{action:"toggleSelect",keys:["Space"],description:"Toggle select"},{action:"extendSelectDown",keys:["Shift","j"],description:"Extend selection down"},{action:"extendSelectUp",keys:["Shift","k"],description:"Extend selection up"},{action:"extendSelectDown",keys:["Shift","↓"],description:"Extend selection down"},{action:"extendSelectUp",keys:["Shift","↑"],description:"Extend selection up"},{action:"selectAll",keys:["⌘","A"],description:"Select all"}]},{title:"Actions",hints:[{action:"reply",keys:["r"],description:"Reply"},{action:"replyAll",keys:["a"],description:"Reply all"},{action:"forward",keys:["f"],description:"Forward"},{action:"delete",keys:["#"],description:"Delete"},{action:"toggleStar",keys:["s"],description:"Star / unstar"},{action:"toggleRead",keys:["u"],description:"Toggle read / unread"}]},{title:"Sender",hints:[{action:"muteSender",keys:["m"],description:"Mute sender"},{action:"blockSender",keys:["b"],description:"Block sender"},{action:"vipSender",keys:["v"],description:"VIP sender"},{action:"markJunk",keys:["!"],description:"Mark junk"}]},{title:"Go to",hints:[{action:"goBrief",keys:["g","b"],description:"Daily brief"},{action:"goInbox",keys:["g","i"],description:"Inbox"},{action:"goSent",keys:["g","s"],description:"Sent"},{action:"goFlagged",keys:["g","f"],description:"Starred"},{action:"goSettings",keys:["g",","],description:"Settings"}]},{title:"View & global",hints:[{action:"toggleIntelligence",keys:["i"],description:"Toggle intelligence"},{action:"toggleDensity",keys:["d"],description:"Toggle density"},{action:"focusSearch",keys:["/"],description:"Focus search"},{action:"compose",keys:["c"],description:"Compose"},{action:"compose",keys:["⌘","N"],description:"Compose"},{action:"help",keys:["?"],description:"Shortcut help"}]}];function Vb(e){for(const t of uu){const s=t.hints.find(n=>n.action===e);if(s)return s.keys}}function ys(e){const t=Vb(e);return!t||t.length===0?"":t.length===1?`(${t[0]})`:t[0]==="g"?`(${t.join(" then ")})`:`(${t.join("")})`}const Qb={global:"Search all mail",pending:"Search mail",scoped:"Search this folder"};function Gb({accounts:e}){const{searchInput:t,onSearchChange:s,onSearchClear:n,onSearchClearQuery:a}=Me(),o=Jc(e),{scope:i,clearScope:l}=cu(e),u=i.kind==="scoped"?[{id:i.chip.id,label:i.chip.label,tone:"scope"}]:void 0,m=Qb[i.kind];return r.jsx(Bp,{search:r.jsx(ao,{value:t,onChange:s,onClear:n,onClearQuery:a,chips:u,onRemoveChip:l,placeholder:m,size:"lg"}),actions:r.jsxs(r.Fragment,{children:[r.jsx(ae,{variant:"ghost",size:"sm",icon:r.jsx(Rh,{className:"size-4"}),title:`Compose ${ys("compose")}`,"aria-label":"Compose",onClick:o}),r.jsx(tu,{}),r.jsx(zb,{})]})})}const mo=({isOpen:e,onClose:t,children:s,ariaLabel:n="Navigation",side:a="left",widthClassName:o="w-[80vw] max-w-[320px]"})=>{const i=c.useRef(null),l=c.useRef(null);if(c.useEffect(()=>{if(!e)return;l.current=document.activeElement;const m=h=>{h.key==="Escape"&&(h.preventDefault(),t())};document.addEventListener("keydown",m),i.current?.querySelector("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")?.focus();const f=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",m),document.body.style.overflow=f,l.current?.focus()}},[e,t]),!e)return null;const u=a==="left"?"left-0 border-r animate-in slide-in-from-left duration-150":"right-0 border-l animate-in slide-in-from-right duration-150";return r.jsxs("div",{className:"fixed inset-0 z-50 lg:hidden",role:"dialog","aria-modal":"true","aria-label":n,children:[r.jsx("button",{type:"button","aria-label":"Close menu",onClick:t,className:"absolute inset-0 bg-black/40 animate-in fade-in duration-150 cursor-default"}),r.jsxs("div",{ref:i,className:$e("absolute top-0 bottom-0 bg-canvas border-line shadow-xl flex flex-col",o,u),children:[r.jsx("div",{className:"flex items-center justify-end h-12 px-2 border-b border-line shrink-0",children:r.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close menu",children:r.jsx(St,{className:"size-5"})})}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:s})]})]})},Yb=e=>{const t=e.filter(a=>!a.isMultipart&&a.disposition!=="attachment"&&a.mediaType==="TEXT"&&a.contentUrl.length>0),s=t.find(a=>a.mediaSubtype.toUpperCase()==="HTML");if(s)return{kind:"html",contentUrl:s.contentUrl};const n=t.find(a=>a.mediaSubtype.toUpperCase()==="PLAIN");return n?{kind:"text",contentUrl:n.contentUrl}:null},ba={all:["messages"],detail:e=>[...ba.all,"detail",e],body:e=>[...ba.detail(e),"body"]};class Zt extends Error{reason;status;retryAfterSeconds;constructor(t,s,n,a){super(s),this.name="BodyFetchError",this.reason=t,this.status=n,this.retryAfterSeconds=a}}const Xb=e=>{const t=Number.parseInt(e??"",10);return!Number.isFinite(t)||t<=0?1:Math.min(t,30)},Jb=8,Zb="x-remit-403-reason",ev=(e,t)=>{const s=t?.trim()??"";return e===401?"auth":e===403?s.length>0?"auth":"body-missing":e===404?"body-missing":"generic"},tv=(e,t)=>(t??"").toLowerCase().startsWith("text/html")?/<div\s+id=["']root["']/i.test(e):!1,sv=(e,t)=>{const s=(t??"").toLowerCase();return!!(e==="text"&&s.startsWith("text/html"))},nv=async(e,t,s=async()=>null)=>{const n={},a=await s();a&&(n.Authorization=`Bearer ${a}`);const o=await Pf(e,{headers:n});if(o.status===202)throw new Zt("not-ready","Message body is still syncing",202,Xb(o.headers.get("Retry-After")));if(!o.ok){const u=o.headers.get(Zb),m=ev(o.status,u);throw new Zt(m,`Failed to load message body (${o.status} ${o.statusText})`,o.status)}const i=o.headers.get("content-type");if(sv(t,i))throw new Zt("content-type-mismatch",`Refusing to render message body — expected ${t}, got Content-Type ${i}`);const l=await o.text();if(tv(l,i))throw new Zt("spa-shell-leak","Refusing to render message body — response looks like the SPA shell (CloudFront 403/404 fallback leaked through to /content/*)");return l},rv=async(e,t)=>(t.isRetryAfterNotReady&&await e.refetchDescribeMessage(),e.fetchContent(t.contentUrl,t.kind)),du=({messageId:e,bodyParts:t,enabled:s=!0})=>{const n=t?Yb(t):null,a=ln(),{getToken:o}=$a(),i=c.useRef(null),l=Re(),u=c.useRef(!1),m=c.useRef(null),d=e&&n?`${e}:${n.contentUrl}`:null;m.current!==d&&(m.current=d,u.current=!1);const f=ve({queryKey:e?[...ba.body(e),n?.contentUrl??null]:["messages","body","noop"],queryFn:()=>{if(!n)throw new Error("No renderable body part");if(!e)throw new Error("No messageId");const x=u.current;return u.current=!1,rv({fetchContent:(p,v)=>nv(p,v,o),refetchDescribeMessage:()=>l.refetchQueries({queryKey:Pl({path:{messageId:e}})})},{contentUrl:n.contentUrl,kind:n.kind,isRetryAfterNotReady:x})},enabled:s&&!!e&&!!n,staleTime:300*1e3,gcTime:1800*1e3,retry:(x,p)=>p instanceof Zt&&p.reason==="not-ready"?x<Jb:x<1,retryDelay:(x,p)=>p instanceof Zt&&p.reason==="not-ready"?(u.current=!0,(p.retryAfterSeconds??1)*1e3):1e3,meta:{softError:!0}}),h=f.isLoading&&!!n;c.useEffect(()=>{h&&(i.current=performance.now())},[h]),c.useEffect(()=>{f.isSuccess&&i.current!==null&&(a.recordTiming("message.body.load",Math.round(performance.now()-i.current)),i.current=null)},[f.isSuccess,a]);const g=f.data&&n?{kind:n.kind,body:f.data}:void 0;return{picked:n,data:g,isLoading:h,isError:f.isError,error:f.error,refetch:f.refetch}},av=({outboxMessageId:e,onDraftCreated:t})=>{const[s,n]=c.useState("idle"),[a,o]=c.useState(null),i=c.useRef(void 0),l=Re(),u=Oe(Ll()),m=Oe(Lf()),d=c.useCallback(async x=>{if(n("saving"),o(null),e){const v=await m.mutateAsync({path:{outboxMessageId:e},body:{toAddresses:x.toAddresses,ccAddresses:x.ccAddresses,bccAddresses:x.bccAddresses,subject:x.subject,textBody:x.textBody,htmlBody:x.htmlBody,inReplyTo:x.inReplyTo,references:x.references}});return n("saved"),v}const p=await u.mutateAsync({body:{...x,sendImmediately:!1}});return t(p.outboxMessageId),n("saved"),l.invalidateQueries({queryKey:er().queryKey}),p},[e,u,m,t,l]),f=c.useCallback(x=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{d(x).catch(p=>{o(p),n("error")})},2e3)},[d]),h=c.useCallback(x=>(i.current&&clearTimeout(i.current),d(x)),[d]),g=c.useCallback(()=>{i.current&&clearTimeout(i.current)},[]);return{saveStatus:s,saveError:a,saveDraft:f,saveImmediately:h,cancelAutoSave:g}},fu=e=>"text"in e&&!("children"in e),mu=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),ov=e=>{let t=mu(e.text);return e.bold&&(t=`<strong>${t}</strong>`),e.italic&&(t=`<em>${t}</em>`),t},hu=e=>{const t=e.children.map(s=>fu(s)?ov(s):hu(s)).join("");switch(e.type){case"blockquote":return`<blockquote>${t}</blockquote>`;case"a":{const s=e.url??"";return`<a href="${mu(s)}">${t}</a>`}default:return`<p>${t}</p>`}},Qi=e=>e.map(hu).join(""),pu=e=>fu(e)?e.text:e.children.map(pu).join(""),va=e=>e.map(pu).join(`
|
|
116
|
-
`),iv=["Tab",","],Gi=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),lv=e=>{const t=e.trim();if(!t)return;const s=t.match(/^(.+?)\s*<([^>]+)>$/);if(s){const n=s[1].trim(),a=s[2].trim();if(Gi(a))return{email:a,displayName:n}}if(Gi(t))return{email:t}},Yr=({label:e,addresses:t,onChange:s,placeholder:n})=>{const[a,o]=c.useState(""),i=c.useRef(null),l=or(a,200),{data:u}=ve({...tr({query:{q:l,limit:8}}),enabled:l.length>=2}),m=u?.items??[],d=new Set(t.map(y=>y.email.toLowerCase())),f=a.length>=2?m.filter(y=>!d.has(y.normalizedEmail.toLowerCase())):[],h=c.useCallback(y=>{d.has(y.email.toLowerCase())||(s([...t,y]),o(""))},[t,d,s]),g=c.useCallback(y=>{s(t.filter((j,E)=>E!==y))},[t,s]),x=c.useCallback(y=>{h({email:y.normalizedEmail,displayName:y.displayName}),i.current?.focus()},[h]),p=c.useCallback(()=>{const y=lv(a);y&&h(y)},[a,h]),v=Fl({count:f.length,acceptKeys:iv,onAccept:y=>x(f[y])}),b=c.useMemo(()=>f.map(y=>({value:y.normalizedEmail,label:y.displayName??y.normalizedEmail,...y.displayName?{hint:y.normalizedEmail}:{}})),[f]),S=c.useCallback(y=>{if(y.key==="Backspace"&&a===""&&t.length>0){g(t.length-1);return}v.handleKeyDown(y)||(y.key==="Enter"||y.key==="Tab"||y.key===",")&&a.trim()&&(y.preventDefault(),p())},[a,t.length,g,v.handleKeyDown,p]),w=c.useCallback(()=>{setTimeout(()=>{p(),v.dismiss()},150)},[p,v.dismiss]);return r.jsxs("div",{className:"relative",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsxs("label",{htmlFor:`address-field-${e}`,className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:[e,":"]}),r.jsxs("div",{className:"flex-1 flex flex-wrap items-center gap-1 min-h-[36px] px-2 py-1 border rounded-md bg-canvas cursor-text",onClick:()=>i.current?.focus(),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&i.current?.focus()},children:[t.map((y,j)=>r.jsx(Dh,{email:y.email,displayName:y.displayName,onRemove:()=>g(j)},y.email)),r.jsx("input",{ref:i,id:`address-field-${e}`,type:"text",value:a,onChange:y=>{v.reopen(),o(y.target.value)},onKeyDown:S,onBlur:w,placeholder:t.length===0?n:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5",autoComplete:"off",...v.comboboxProps})]})]}),v.open&&r.jsx($l,{id:v.listId,suggestions:b,activeIndex:v.activeIndex,optionId:v.optionId,onPick:y=>{const j=f.find(E=>E.normalizedEmail===y.value);j&&x(j)},onHighlight:v.setActiveIndex,label:`${e} suggestions`,className:"absolute left-12 right-0 z-50 mt-1 max-h-[200px] shadow-lg"})]})},cv=({accountId:e})=>{const t=He();return r.jsxs("div",{role:"alert","data-testid":"compose-smtp-missing-banner",className:"flex items-start gap-3 border-b border-warning/50 bg-warning/10 px-3 py-2",children:[r.jsx(Oa,{className:"size-5 shrink-0 mt-0.5 text-warning","aria-hidden":"true"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm font-medium text-warning",children:"This account can't send mail until SMTP is configured."}),r.jsxs("button",{type:"button",onClick:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})},className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",r.jsx(Ff,{className:"size-3","aria-hidden":"true"})]})]})]})},Yi=150,uv=()=>{const[e,t]=c.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>Yi}});return c.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,n=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>Yi})};return n(),s.addEventListener("resize",n),()=>s.removeEventListener("resize",n)},[]),e},dv=({selectedAccountId:e,onSelect:t})=>{const{data:s}=ve({...Mt(),staleTime:1/0}),n=s?.accounts??[];if(c.useEffect(()=>{!e&&n.length===1&&n[0]&&t(n[0])},[e,n,t]),n.length<=1){const a=n[0];return a?r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=n.find(i=>i.accountId===a.target.value);o&&t(o)},className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",children:n.map(a=>r.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},fv=({value:e,onChange:t})=>r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"Subj:"}),r.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",placeholder:"Subject","data-subject-field":!0})]}),mv=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],hv=["href"],pv=e=>Il.sanitize(e,{ALLOWED_TAGS:mv,ALLOWED_ATTR:hv}),gv=c.lazy(()=>_f(()=>import("./ComposeBody-DzoUP5mO.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])).then(e=>({default:e.ComposeBody}))),xv=()=>r.jsxs("div",{className:"min-h-[120px] px-3 py-2",children:[r.jsx("div",{className:"h-8 mb-2 rounded bg-surface-sunken animate-pulse"}),r.jsx("div",{className:"min-h-[80px] rounded bg-surface-sunken/50 animate-pulse"})]}),gu=[{type:"p",children:[{text:""}]}],bv=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],vv=e=>e?[...bv,{type:"p",children:[{text:e}]}]:gu,yv=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",wv=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",Sv=(e,t,s)=>{const{envelope:n}=e,o=(n.replyTo.length>0?n.replyTo:n.from).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),l=new Set(o.map(m=>m.email.toLowerCase())),u=[...n.to,...n.cc].filter(m=>m.normalizedEmail.toLowerCase()!==i&&!l.has(m.normalizedEmail.toLowerCase())).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));return{to:o,cc:u}},kv=e=>{const t=e.envelope.messageIdValue,n=[...e.references.filter(a=>a.referenceType==="references").sort((a,o)=>a.referenceOrder-o.referenceOrder).map(a=>a.messageIdValue)];return t&&!n.includes(t)&&n.push(t),{inReplyTo:t,references:n}},Cv=(e,t,s,n,a)=>e.length===0&&t.length===0&&s.length===0&&n.trim()===""&&va(a).trim()==="",jv=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:n,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:l,showCc:u,setShowCc:m,showBcc:d,setShowBcc:f,subject:h,setSubject:g})=>{const x=Wt(),{isKeyboardOpen:p}=uv();if(!x&&p){const b=[];return s.length>0&&b.push(`To: ${s.map(S=>S.displayName??S.email).join(", ")}`),a.length>0&&b.push(`Cc: ${a.length}`),i.length>0&&b.push(`Bcc: ${i.length}`),h&&b.push(h),r.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b border-line overflow-hidden","data-testid":"compose-header-collapsed",children:[r.jsx("span",{className:"truncate text-xs text-fg-muted",children:b.length>0?b.join(" · "):"…"}),r.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded bg-surface-sunken px-1.5 py-0.5 text-2xs text-fg-muted",children:"…"})]})}return r.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[r.jsx(dv,{selectedAccountId:e,onSelect:t}),r.jsx(Yr,{label:"To",addresses:s,onChange:n,placeholder:"Recipients"}),u?r.jsx(Yr,{label:"Cc",addresses:a,onChange:o}):r.jsxs("div",{className:"flex gap-2 pl-14",children:[r.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Cc"}),r.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})]}),u&&!d&&r.jsx("div",{className:"pl-14",children:r.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})}),d&&r.jsx(Yr,{label:"Bcc",addresses:i,onChange:l}),r.jsx(fv,{value:h,onChange:g})]})},ho=({mode:e,account:t,sourceMessage:s,onClose:n,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=Ht(),{pushError:u}=lt(),{outboxMessageId:m}=o,[d,f]=c.useState([]),[h,g]=c.useState([]),[x,p]=c.useState([]),[v,b]=c.useState(""),[S,w]=c.useState(!1),[y,j]=c.useState(!1),[E,M]=c.useState(t?.accountId),[N,A]=c.useState(!1),L=c.useRef(m);c.useEffect(()=>{L.current!==m&&(L.current=m,m&&(f([]),g([]),p([]),b(""),w(!1),j(!1),R(gu),A(!1)))},[m]);const{signature:O}=Nm(E),[D,R]=c.useState(()=>vv(O.plainText)),{data:k}=ve({...$f({path:{outboxMessageId:m??""}}),enabled:!!m&&!N});c.useEffect(()=>{!k||N||(f(k.toAddresses.map(z=>({email:z,displayName:void 0}))),k.ccAddresses&&k.ccAddresses.length>0&&(g(k.ccAddresses.map(z=>({email:z,displayName:void 0}))),w(!0)),k.bccAddresses&&k.bccAddresses.length>0&&(p(k.bccAddresses.map(z=>({email:z,displayName:void 0}))),j(!0)),k.subject&&b(k.subject),k.textBody&&R([{type:"p",children:[{text:k.textBody}]}]),M(k.accountId),A(!0))},[k,N]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:z,cc:ce}=Sv(s,e,t?.email);f(z),g(ce),ce.length>0&&w(!0),b(yv(s.envelope.subject))}e==="forward"&&b(wv(s.envelope.subject))}},[e,s,t?.email]);const P=e==="reply"||e==="reply_all"||e==="forward",{data:F}=du({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:P&&!!s}),C=F?.kind==="text"?F.body:"",T=F?.kind==="html"?pv(F.body):void 0,I=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:q,saveError:se,saveDraft:G,cancelAutoSave:oe}=av({outboxMessageId:m,onDraftCreated:i});c.useEffect(()=>{se&&u({title:"Couldn't save draft",detail:ht(se)??"Saving the draft failed.",error:se})},[se,u]);const ne=Oe(Ll()),Z=Oe(_l()),pe=Oe({...sr(),onError:z=>{u(ts("Couldn't discard draft","The draft wasn't discarded.",z))}}),{data:me}=ve({...Mt(),staleTime:1/0}),Q=me?.accounts.find(z=>z.accountId===E),H=Q?Cm(Q):!1,de=ne.isPending||Z.isPending,ee=d.length>0&&!!E&&!H;c.useEffect(()=>{if(!E||m&&!N||Cv(d,h,x,v,D))return;const z=va(D),ce=Qi(D);G({accountId:E,toAddresses:d.map(be=>be.email),ccAddresses:h.length>0?h.map(be=>be.email):void 0,bccAddresses:x.length>0?x.map(be=>be.email):void 0,subject:v||void 0,textBody:z||void 0,htmlBody:ce||void 0})},[E,m,N,d,h,x,v,D,G]);const fe=c.useCallback(async()=>{if(!E||d.length===0)return;oe();const z=s&&(e==="reply"||e==="reply_all")?kv(s):{};let ce=m,be=!1;if(!ce){const ge=va(D),ie=Qi(D),Ae=await ne.mutateAsync({body:{accountId:E,toAddresses:d.map(we=>we.email),ccAddresses:h.length>0?h.map(we=>we.email):void 0,bccAddresses:x.length>0?x.map(we=>we.email):void 0,subject:v||void 0,textBody:ge||void 0,htmlBody:ie||void 0,sendImmediately:!0,...z}}).catch(we=>(u({title:"Couldn't send message",detail:ht(we)??"Saving the draft failed.",error:we}),null));if(Ae===null)return;ce=Ae.outboxMessageId,be=!0,i(ce)}await Z.mutateAsync({path:{outboxMessageId:ce}}).catch(ge=>(u({title:"Couldn't send message",detail:ht(ge)??(be?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:ge}),null))!==null&&(l(ce),n())},[E,d,h,x,v,D,e,s,m,ne,Z,oe,l,i,u,n]),U=c.useCallback(()=>{oe(),m&&pe.mutate({path:{outboxMessageId:m}}),n()},[oe,m,pe,n]),_=c.useCallback(z=>{M(z.accountId),a?.(z)},[a]);return r.jsx(Vp,{banner:Q&&H?r.jsx(cv,{accountId:Q.accountId}):void 0,header:r.jsx(jv,{selectedAccountId:E,onAccountChange:_,toAddresses:d,setToAddresses:f,ccAddresses:h,setCcAddresses:g,bccAddresses:x,setBccAddresses:p,showCc:S,setShowCc:w,showBcc:y,setShowBcc:j,subject:v,setSubject:b}),quoted:C||T?r.jsx(hg,{text:C,html:T,senderName:I}):void 0,actionBar:r.jsx(Wp,{onSend:fe,onDiscard:U,sending:de,canSend:ee,saveStatus:q,unavailableReason:H?"SMTP not configured":void 0,onUnavailable:z=>u({title:"Can't send yet",detail:z})}),children:r.jsx(c.Suspense,{fallback:r.jsx(xv,{}),children:r.jsx(gv,{value:D,onChange:R,onSubmit:fe,autoFocus:e==="new"})})})},Xi=({mode:e,account:t,sourceMessage:s,onClose:n})=>r.jsx("div",{className:"border-t border-line bg-canvas max-h-[400px] flex flex-col",children:r.jsx(ho,{mode:e,account:t,sourceMessage:s,onClose:n})}),xu=({message:e,icon:t})=>r.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center",children:[t&&r.jsx("div",{className:"mb-4 text-fg-muted",children:t}),r.jsx("p",{className:"text-fg-muted",children:e})]}),po=({enabled:e=!0,bindings:t,capture:s=!1})=>{const n=c.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const m=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(m&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);c.useEffect(()=>{if(e)return window.addEventListener("keydown",n,s),()=>window.removeEventListener("keydown",n,s)},[e,n,s])},go=e=>{const{data:t,isLoading:s}=ve({...Mt(),staleTime:1/0}),n=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=gt({queries:n.map(l=>({...it({path:{accountId:l}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(l=>l.isLoading);return{accountId:c.useMemo(()=>{if(e){for(let l=0;l<n.length;l++)if((a[l].data?.items??[]).some(d=>d.mailboxId===e))return n[l]}},[e,n,a]),isLoading:o}},Nv=100,qn=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),Ev=(e,t=Nv)=>{if(e.length===0)return[];const s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s},bu=async(e,t,s,n)=>{const a=Ev(e),o=e.length;let i=0;const l=[];for(let u=0;u<a.length;u++){if(n())return l.push(...a.slice(u).flat()),{done:i,failedIds:l,cancelled:!0};const m=a[u],d=await qn(t(m));if(!d.ok)return l.push(...a.slice(u).flat()),s({done:i,total:o}),{done:i,failedIds:l,cancelled:!1,error:d.error};i+=m.length,s({done:i,total:o})}return{done:i,failedIds:l,cancelled:!1}},br=async(e,t)=>{await bu(e,async s=>(await t(s),{successCount:s.length,failureCount:0}),()=>{},()=>!1)},Iv=async(e,t,s,n,a)=>{let o=0;const i=[];let l;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await qn(e(l));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const m=u.value;if(m.ids.length>0){const d=await qn(s(m.ids));if(!d.ok)return{done:o,failedIds:i,cancelled:!1,error:d.error};o+=m.ids.length,n({done:o,total:t})}l=m.continuationToken}while(l);return{done:o,failedIds:i,cancelled:!1}},Tv=e=>({done:e.done,total:Math.max(e.total,e.done)}),Rv=async(e,t,s)=>{let n=0,a;do{if(s())return{total:n,cancelled:!0};const o=await qn(e(a));if(!o.ok)return{total:n,cancelled:!1,error:o.error};const i=o.value;n+=i.ids.length,t(n),a=i.continuationToken}while(a);return{total:n,cancelled:!1}},vu=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),yu=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),wu=(e,t)=>e===void 0?e:vu(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:yu(e)?{...e,items:t(e.items)}:e,Ot=e=>{const t=[];for(const s of new Set(e))t.push(nr({path:{mailboxId:s}})),t.push(Ka({path:{mailboxId:s}}));return t.push(Ua()),t},dn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),fn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,n])=>({queryKey:s,data:n})),mn=(e,t,s)=>{const n=a=>wu(a,s);for(const a of t)e.setQueriesData({queryKey:a},n)},hn=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},Dt=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},Mv=3e3,Av=(e,t,s)=>{if(e.length===0)return()=>{};const n=setTimeout(()=>s(e),t);return()=>clearTimeout(n)},vr=(e,t,s)=>{const n=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(n.get(o)??s);return[...a]},Hn=(e,t,s)=>e.map(n=>t.has(n.messageId)?{...n,isRead:s}:n),Ov=(e,t,s,n)=>e.filter(a=>!a.isRead&&t.has(a.threadMessageId)&&!s.has(a.messageId)&&!n.has(a.messageId)).map(a=>a.messageId),Dv=({messages:e,expandedIds:t,threadId:s,mailboxId:n,accountId:a})=>{const o=Re(),{pushError:i}=lt(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:m}=Oe({...rr(),onMutate:async h=>{const g=new Set(h.body.messageIds??[]),x=h.body.isRead??!0,p=ls({path:{threadId:s}}),v=Ot(vr(g,e,n));await Promise.all([o.cancelQueries({queryKey:p}),dn(o,v)]);const b=o.getQueriesData({queryKey:p}).filter(w=>w[1]!==void 0).map(([w,y])=>({queryKey:w,data:y})),S=fn(o,v);return o.setQueriesData({queryKey:p},w=>w&&{...w,items:Hn(w.items,g,x)}),mn(o,v,w=>Hn(w,g,x)),{threadMessagesPrefix:p,listPrefixes:v,previousThreadMessages:b,previousThreadsList:S}},onSuccess:(h,g)=>{const x=g.body.messageIds??[];for(const p of x)l.current.add(p),u.current.delete(p)},onError:(h,g,x)=>{const p=g.body.messageIds??[];for(const b of p)u.current.delete(b);if(x){for(const b of x.previousThreadMessages)o.setQueryData(b.queryKey,b.data);hn(o,x.previousThreadsList)}const v=g.body.isRead??!0;i({title:v?"Couldn't mark as read":"Couldn't mark as unread",detail:ht(h),error:h})},onSettled:(h,g,x,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),Dt(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:is({path:{accountId:a}})}))}}),d=c.useCallback(h=>{const g=h.filter(x=>!l.current.has(x)&&!u.current.has(x));if(g.length!==0){for(const x of g)u.current.add(x);m({body:{messageIds:g,isRead:!0}})}},[m]),f=c.useMemo(()=>Ov(e,t,l.current,u.current),[e,t]);c.useEffect(()=>Av(f,Mv,d),[f,d]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},yr=e=>{const{mailboxId:t,accountId:s,messages:n}=e,a=Re(),{pushError:o}=lt(),{mutateAsync:i,isPending:l}=Oe({...rr(),onError:(m,d)=>{const f=d.body.isRead??!0;o({title:f?"Couldn't mark as read":"Couldn't mark as unread",detail:ht(m),error:m})},onSettled:(m,d,f)=>{Dt(a,Ot(vr(f.body.messageIds??[],n??[],t))),s&&a.invalidateQueries({queryKey:is({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((m,d)=>{m.length!==0&&br(m,f=>i({body:{messageIds:f,isRead:d}}))},[i]),isPending:l}},Pv=60,Lv=1.5,Fv=(e,t,s)=>{const n=Math.abs(e),a=Math.abs(t);return n<s?{direction:null}:n<a*Lv?{direction:null}:{direction:e<0?"left":"right"}},$v=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=Pv})=>{const n=c.useRef(null),a=c.useCallback(u=>{if(u.pointerType==="mouse"){n.current=null;return}n.current={x:u.clientX,y:u.clientY}},[]),o=c.useCallback(()=>{},[]),i=c.useCallback(u=>{const m=n.current;if(n.current=null,!m)return;const{direction:d}=Fv(u.clientX-m.x,u.clientY-m.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),l=c.useCallback(()=>{n.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:l}}},_v=(e,t,s)=>t?.find(n=>n.messageId===e)?.mailboxId??s,Ji=(e,t,s)=>e.map(n=>n.messageId===t?{...n,hasStars:s}:n),xo=({threadId:e,mailboxId:t,messages:s})=>{const n=Re(),{pushError:a}=lt(),{mutate:o,isPending:i,variables:l}=Oe({...zf(),onMutate:async m=>{const d=m.path.messageId,f=m.body.isStarred??!1,h=ls({path:{threadId:e}}),g=Ot([_v(d,s,t)]);await Promise.all([n.cancelQueries({queryKey:h}),dn(n,g)]);const x=n.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,b])=>({queryKey:v,data:b})),p=fn(n,g);return n.setQueriesData({queryKey:h},v=>wu(v,b=>Ji(b,d,f))),mn(n,g,v=>Ji(v,d,f)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:x,previousThreadsList:p}},onError:(m,d,f)=>{if(f){for(const g of f.previousThreadMessages)n.setQueryData(g.queryKey,g.data);hn(n,f.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:ht(m),error:m})},onSettled:(m,d,f,h)=>{h&&(n.invalidateQueries({queryKey:h.threadMessagesPrefix}),Dt(n,h.listPrefixes))}});return{toggleStar:(m,d)=>{o({path:{messageId:m},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function wr(e){return e===void 0?"uncategorized":e}const zv={inbox:"Inbox",junk:"Junk"},bo=e=>e.destinationMailboxId!==void 0,Bv=(e,t)=>{if(bo(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${zv[s]??"another folder"} by Remit`},Kv=(e,t)=>{if(e===Wo.MoveToInbox)return t.inboxMailboxId;if(e===Wo.MoveToJunk)return t.junkMailboxId},Uv=(e,t,s)=>{if(!e||!t)return!1;const n=bo(e)?e.destinationMailboxId:Kv(e.action,s);return n!==void 0&&n===t},qv=(e,t)=>{if(e){if(bo(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},Sr=(e,t)=>{const{data:s,isLoading:n}=ve({...Mt(),staleTime:1/0,enabled:!!e});return{mailboxId:c.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:n}},Hv=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Archive");return{archiveMailboxId:t,isLoading:s}},Wv=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},vo=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},Fs=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Junk");return{junkMailboxId:t,isLoading:s}},yo=e=>{const{data:t}=ve({...Mt(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},Zi=(e,t)=>e.filter(s=>!t.has(s.messageId)),rs=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=Re(),{pushError:o}=lt(),{mutateAsync:i,isPending:l}=Oe({...Bf(),onMutate:async m=>{const d=new Set(m.body.messageIds??[]),f=t?ls({path:{threadId:t}}):[],h=Ot([e,m.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:f})]:[],dn(a,h)]);const g=t?a.getQueriesData({queryKey:f}).filter(p=>p[1]!==void 0).map(([p,v])=>({queryKey:p,data:v})):[],x=fn(a,h);return t&&a.setQueriesData({queryKey:f},p=>p&&{...p,items:Zi(p.items,d)}),mn(a,h,p=>Zi(p,d)),n?.(Array.from(d)),{threadMessagesPrefix:f,listPrefixes:h,previousThreadMessages:g,previousThreadsList:x}},onError:(m,d,f)=>{if(f){for(const g of f.previousThreadMessages)a.setQueryData(g.queryKey,g.data);hn(a,f.previousThreadsList)}const h=d.body.messageIds?.length??0;o({title:h>1?`Couldn't move ${h} messages`:"Couldn't move this message",detail:ht(m),error:m})},onSettled:(m,d,f,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),Dt(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:is({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((m,d)=>{m.length!==0&&br(m,f=>i({body:{messageIds:f,destinationMailboxId:d}}))},[i]),isPending:l}},Vv=({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a})=>{const{inboxMailboxId:o}=vo(e),{junkMailboxId:i}=Fs(e),{moveMessages:l,isPending:u}=rs({mailboxId:n,threadId:s,accountId:e}),{data:m}=ve({...it({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),d={inboxMailboxId:o,junkMailboxId:i},f=Uv(a,n,d),h=qv(a,d),g=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!f||!a)return{show:!1,label:"",isUndoing:!1};const x=a.fromMailboxId?m?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>zn(p.fullPath))[0]:void 0;return{show:!0,label:Bv(a,x),onUndo:h?g:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function Qv({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a}){const o=Vv({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a});return o.show?r.jsx(Kp,{label:o.label,onUndo:o.onUndo,undoLabel:o.isUndoing?"Undoing…":"Undo",filtersHref:o.filtersHref}):null}const el=(e,t)=>e.filter(s=>!t.has(s.messageId)),Gv=e=>e.filter(t=>t.isDeleted!==!0),as=({mailboxId:e,threadId:t,accountId:s,messages:n,onAfterOptimisticRemove:a})=>{const o=Re(),{pushError:i}=lt(),{mutateAsync:l,isPending:u}=Oe({...Kf(),onMutate:async d=>{const f=new Set(d.body.messageIds??[]),h=t?ls({path:{threadId:t}}):[],g=Ot(vr(f,n??[],e));await Promise.all([o.cancelQueries({queryKey:h}),dn(o,g)]);const x=t?o.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,b])=>({queryKey:v,data:b})):[],p=fn(o,g);return t&&o.setQueriesData({queryKey:h},v=>v&&{...v,items:el(v.items,f)}),mn(o,g,v=>el(v,f)),a?.(Array.from(f)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:x,previousThreadsList:p}},onError:(d,f,h)=>{if(h){for(const x of h.previousThreadMessages)o.setQueryData(x.queryKey,x.data);hn(o,h.previousThreadsList)}const g=f.body.messageIds?.length??0;i({title:g>1?`Couldn't delete ${g} messages`:"Couldn't delete this message",detail:ht(d),error:d})},onSettled:(d,f,h,g)=>{g&&(t&&o.invalidateQueries({queryKey:g.threadMessagesPrefix}),Dt(o,g.listPrefixes),s&&o.invalidateQueries({queryKey:is({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(d=>{d.length!==0&&br(d,f=>l({body:{messageIds:f}}))},[l]),isPending:u}},Su=(e,t=Date.now())=>({value:e,setAt:t}),Yv=(e,t,s,n)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=Su(!0,n):delete a.trusted,{...e,flags:a}},Xv=(e,t,s,n)=>{const a=o=>o.map(i=>Yv(i,t,s,n));return{...e,envelope:{...e.envelope,from:a(e.envelope.from),to:a(e.envelope.to),cc:a(e.envelope.cc),bcc:a(e.envelope.bcc),replyTo:a(e.envelope.replyTo)}}},wo=({messageId:e})=>{const t=Re(),{pushError:s}=lt(),{mutate:n,isPending:a,error:o,reset:i}=Oe({...zl(),onMutate:async u=>{const m=u.path.addressId,f=u.body.flags?.trusted?.value===!0,h=Pl({path:{messageId:e}});await t.cancelQueries({queryKey:h});const g=t.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,p])=>({queryKey:x,data:p}));return t.setQueriesData({queryKey:h},x=>x&&Xv(x,m,f)),{describePrefix:h,previous:g}},onError:(u,m,d)=>{if(d)for(const f of d.previous)t.setQueryData(f.queryKey,f.data);s(ts("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,m,d,f)=>{f&&t.invalidateQueries({queryKey:f.describePrefix})}});return{toggleTrusted:(u,m)=>{n({path:{addressId:u},body:{flags:{trusted:Su(!m)}}})},isPending:a,error:o,reset:i}};var kr="Dialog",[ku]=rx(kr),[Jv,xt]=ku(kr),Cu=e=>{const{__scopeDialog:t,children:s,open:n,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,l=c.useRef(null),u=c.useRef(null),[m,d]=ix({prop:n,defaultProp:a??!1,onChange:o,caller:kr});return r.jsx(Jv,{scope:t,triggerRef:l,contentRef:u,contentId:Hr(),titleId:Hr(),descriptionId:Hr(),open:m,onOpenChange:d,onOpenToggle:c.useCallback(()=>d(f=>!f),[d]),modal:i,children:s})};Cu.displayName=kr;var ju="DialogTrigger",Zv=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(ju,s),o=cs(t,a.triggerRef);return r.jsx(At.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":ko(a.open),...n,ref:o,onClick:Bt(e.onClick,a.onOpenToggle)})});Zv.displayName=ju;var So="DialogPortal",[ey,Nu]=ku(So,{forceMount:void 0}),Eu=e=>{const{__scopeDialog:t,forceMount:s,children:n,container:a}=e,o=xt(So,t);return r.jsx(ey,{scope:t,forceMount:s,children:c.Children.map(n,i=>r.jsx(hr,{present:s||o.open,children:r.jsx(Bc,{asChild:!0,container:a,children:i})}))})};Eu.displayName=So;var Wn="DialogOverlay",Iu=c.forwardRef((e,t)=>{const s=Nu(Wn,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=xt(Wn,e.__scopeDialog);return o.modal?r.jsx(hr,{present:n||o.open,children:r.jsx(sy,{...a,ref:t})}):null});Iu.displayName=Wn;var ty=lo("DialogOverlay.RemoveScroll"),sy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Wn,s),o=Nx(),i=cs(t,o);return r.jsx(Gc,{as:ty,allowPinchZoom:!0,shards:[a.contentRef],children:r.jsx(At.div,{"data-state":ko(a.open),...n,ref:i,style:{pointerEvents:"auto",...n.style}})})}),Rs="DialogContent",Tu=c.forwardRef((e,t)=>{const s=Nu(Rs,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=xt(Rs,e.__scopeDialog);return r.jsx(hr,{present:n||o.open,children:o.modal?r.jsx(ny,{...a,ref:t}):r.jsx(ry,{...a,ref:t})})});Tu.displayName=Rs;var ny=c.forwardRef((e,t)=>{const s=xt(Rs,e.__scopeDialog),n=c.useRef(null),a=cs(t,s.contentRef,n);return c.useEffect(()=>{const o=n.current;if(o)return Qx(o)},[]),r.jsx(Ru,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Bt(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Bt(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:Bt(e.onFocusOutside,o=>o.preventDefault())})}),ry=c.forwardRef((e,t)=>{const s=xt(Rs,e.__scopeDialog),n=c.useRef(!1),a=c.useRef(!1);return r.jsx(Ru,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(n.current||s.triggerRef.current?.focus(),o.preventDefault()),n.current=!1,a.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const i=o.target;s.triggerRef.current?.contains(i)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&a.current&&o.preventDefault()}})}),Ru=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=xt(Rs,s);return Rx(),r.jsx(r.Fragment,{children:r.jsx(_c,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:o,children:r.jsx(Fc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":ko(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),Mu="DialogTitle",Au=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Mu,s);return r.jsx(At.h2,{id:a.titleId,...n,ref:t})});Au.displayName=Mu;var Ou="DialogDescription",ay=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Ou,s);return r.jsx(At.p,{id:a.descriptionId,...n,ref:t})});ay.displayName=Ou;var Du="DialogClose",oy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Du,s);return r.jsx(At.button,{type:"button",...n,ref:t,onClick:Bt(e.onClick,()=>a.onOpenChange(!1))})});oy.displayName=Du;function ko(e){return e?"open":"closed"}function iy(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",t.appendChild(s),s.styleSheet?s.styleSheet.cssText=e:s.appendChild(document.createTextNode(e))}const Pu=K.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),pn=()=>{const e=K.useContext(Pu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};iy(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(
|
|
116
|
+
`),iv=["Tab",","],Gi=e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()),lv=e=>{const t=e.trim();if(!t)return;const s=t.match(/^(.+?)\s*<([^>]+)>$/);if(s){const n=s[1].trim(),a=s[2].trim();if(Gi(a))return{email:a,displayName:n}}if(Gi(t))return{email:t}},Yr=({label:e,addresses:t,onChange:s,placeholder:n})=>{const[a,o]=c.useState(""),i=c.useRef(null),l=or(a,200),{data:u}=ve({...tr({query:{q:l,limit:8}}),enabled:l.length>=2}),m=u?.items??[],d=new Set(t.map(y=>y.email.toLowerCase())),f=a.length>=2?m.filter(y=>!d.has(y.normalizedEmail.toLowerCase())):[],h=c.useCallback(y=>{d.has(y.email.toLowerCase())||(s([...t,y]),o(""))},[t,d,s]),g=c.useCallback(y=>{s(t.filter((j,E)=>E!==y))},[t,s]),x=c.useCallback(y=>{h({email:y.normalizedEmail,displayName:y.displayName}),i.current?.focus()},[h]),p=c.useCallback(()=>{const y=lv(a);y&&h(y)},[a,h]),v=Fl({count:f.length,acceptKeys:iv,onAccept:y=>x(f[y])}),b=c.useMemo(()=>f.map(y=>({value:y.normalizedEmail,label:y.displayName??y.normalizedEmail,...y.displayName?{hint:y.normalizedEmail}:{}})),[f]),S=c.useCallback(y=>{if(y.key==="Backspace"&&a===""&&t.length>0){g(t.length-1);return}v.handleKeyDown(y)||(y.key==="Enter"||y.key==="Tab"||y.key===",")&&a.trim()&&(y.preventDefault(),p())},[a,t.length,g,v.handleKeyDown,p]),w=c.useCallback(()=>{setTimeout(()=>{p(),v.dismiss()},150)},[p,v.dismiss]);return r.jsxs("div",{className:"relative",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsxs("label",{htmlFor:`address-field-${e}`,className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:[e,":"]}),r.jsxs("div",{className:"flex-1 flex flex-wrap items-center gap-1 min-h-[36px] px-2 py-1 border rounded-md bg-canvas cursor-text",onClick:()=>i.current?.focus(),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&i.current?.focus()},children:[t.map((y,j)=>r.jsx(Dh,{email:y.email,displayName:y.displayName,onRemove:()=>g(j)},y.email)),r.jsx("input",{ref:i,id:`address-field-${e}`,type:"text",value:a,onChange:y=>{v.reopen(),o(y.target.value)},onKeyDown:S,onBlur:w,placeholder:t.length===0?n:"",className:"flex-1 min-w-[120px] bg-transparent outline-none text-sm py-0.5",autoComplete:"off",...v.comboboxProps})]})]}),v.open&&r.jsx($l,{id:v.listId,suggestions:b,activeIndex:v.activeIndex,optionId:v.optionId,onPick:y=>{const j=f.find(E=>E.normalizedEmail===y.value);j&&x(j)},onHighlight:v.setActiveIndex,label:`${e} suggestions`,className:"absolute left-12 right-0 z-50 mt-1 max-h-[200px] shadow-lg"})]})},cv=({accountId:e})=>{const t=He();return r.jsxs("div",{role:"alert","data-testid":"compose-smtp-missing-banner",className:"flex items-start gap-3 border-b border-warning/50 bg-warning/10 px-3 py-2",children:[r.jsx(Oa,{className:"size-5 shrink-0 mt-0.5 text-warning","aria-hidden":"true"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm font-medium text-warning",children:"This account can't send mail until SMTP is configured."}),r.jsxs("button",{type:"button",onClick:()=>{t({to:"/settings/accounts",search:{editAccountId:e,focusSmtp:!0}})},className:"mt-1 inline-flex items-center gap-1 text-xs font-medium text-warning hover:underline",children:["Configure SMTP",r.jsx(Ff,{className:"size-3","aria-hidden":"true"})]})]})]})},Yi=150,uv=()=>{const[e,t]=c.useState(()=>{if(typeof window>"u"||!window.visualViewport)return{viewportHeight:0,isKeyboardOpen:!1};const s=window.visualViewport.height;return{viewportHeight:s,isKeyboardOpen:window.innerHeight-s>Yi}});return c.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const s=window.visualViewport,n=()=>{const a=s.height;t({viewportHeight:a,isKeyboardOpen:window.innerHeight-a>Yi})};return n(),s.addEventListener("resize",n),()=>s.removeEventListener("resize",n)},[]),e},dv=({selectedAccountId:e,onSelect:t})=>{const{data:s}=ve({...Mt(),staleTime:1/0}),n=s?.accounts??[];if(c.useEffect(()=>{!e&&n.length===1&&n[0]&&t(n[0])},[e,n,t]),n.length<=1){const a=n[0];return a?r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("div",{className:"text-sm py-1.5",children:a.email})]}):null}return r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{htmlFor:"from-account-selector",className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"From:"}),r.jsx("select",{id:"from-account-selector",value:e??"",onChange:a=>{const o=n.find(i=>i.accountId===a.target.value);o&&t(o)},className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",children:n.map(a=>r.jsx("option",{value:a.accountId,children:a.email},a.accountId))})]})},fv=({value:e,onChange:t})=>r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("label",{className:"text-sm text-fg-muted shrink-0 w-12 pt-1.5",children:"Subj:"}),r.jsx("input",{type:"text",value:e,onChange:s=>t(s.target.value),className:"flex-1 px-2 py-1.5 border rounded-md bg-canvas text-sm",placeholder:"Subject","data-subject-field":!0})]}),mv=["p","br","strong","b","em","i","a","blockquote","ul","ol","li"],hv=["href"],pv=e=>Il.sanitize(e,{ALLOWED_TAGS:mv,ALLOWED_ATTR:hv}),gv=c.lazy(()=>_f(()=>import("./ComposeBody-B7A7M4j3.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])).then(e=>({default:e.ComposeBody}))),xv=()=>r.jsxs("div",{className:"min-h-[120px] px-3 py-2",children:[r.jsx("div",{className:"h-8 mb-2 rounded bg-surface-sunken animate-pulse"}),r.jsx("div",{className:"min-h-[80px] rounded bg-surface-sunken/50 animate-pulse"})]}),gu=[{type:"p",children:[{text:""}]}],bv=[{type:"p",children:[{text:""}]},{type:"p",children:[{text:"-- "}]}],vv=e=>e?[...bv,{type:"p",children:[{text:e}]}]:gu,yv=e=>e?/^re:\s/i.test(e)?e:`Re: ${e}`:"Re: ",wv=e=>e?/^fwd?:\s/i.test(e)?e:`Fwd: ${e}`:"Fwd: ",Sv=(e,t,s)=>{const{envelope:n}=e,o=(n.replyTo.length>0?n.replyTo:n.from).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));if(t!=="reply_all")return{to:o,cc:[]};const i=s?.toLowerCase(),l=new Set(o.map(m=>m.email.toLowerCase())),u=[...n.to,...n.cc].filter(m=>m.normalizedEmail.toLowerCase()!==i&&!l.has(m.normalizedEmail.toLowerCase())).map(m=>({email:m.normalizedEmail,displayName:m.displayName}));return{to:o,cc:u}},kv=e=>{const t=e.envelope.messageIdValue,n=[...e.references.filter(a=>a.referenceType==="references").sort((a,o)=>a.referenceOrder-o.referenceOrder).map(a=>a.messageIdValue)];return t&&!n.includes(t)&&n.push(t),{inReplyTo:t,references:n}},Cv=(e,t,s,n,a)=>e.length===0&&t.length===0&&s.length===0&&n.trim()===""&&va(a).trim()==="",jv=({selectedAccountId:e,onAccountChange:t,toAddresses:s,setToAddresses:n,ccAddresses:a,setCcAddresses:o,bccAddresses:i,setBccAddresses:l,showCc:u,setShowCc:m,showBcc:d,setShowBcc:f,subject:h,setSubject:g})=>{const x=Wt(),{isKeyboardOpen:p}=uv();if(!x&&p){const b=[];return s.length>0&&b.push(`To: ${s.map(S=>S.displayName??S.email).join(", ")}`),a.length>0&&b.push(`Cc: ${a.length}`),i.length>0&&b.push(`Bcc: ${i.length}`),h&&b.push(h),r.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b border-line overflow-hidden","data-testid":"compose-header-collapsed",children:[r.jsx("span",{className:"truncate text-xs text-fg-muted",children:b.length>0?b.join(" · "):"…"}),r.jsx("span",{className:"shrink-0 inline-flex items-center justify-center rounded bg-surface-sunken px-1.5 py-0.5 text-2xs text-fg-muted",children:"…"})]})}return r.jsxs("div",{className:"space-y-1 px-3 py-2 border-b border-line",children:[r.jsx(dv,{selectedAccountId:e,onSelect:t}),r.jsx(Yr,{label:"To",addresses:s,onChange:n,placeholder:"Recipients"}),u?r.jsx(Yr,{label:"Cc",addresses:a,onChange:o}):r.jsxs("div",{className:"flex gap-2 pl-14",children:[r.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Cc"}),r.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})]}),u&&!d&&r.jsx("div",{className:"pl-14",children:r.jsx("button",{type:"button",onClick:()=>f(!0),className:"text-xs text-fg-muted hover:text-fg transition-colors",children:"Bcc"})}),d&&r.jsx(Yr,{label:"Bcc",addresses:i,onChange:l}),r.jsx(fv,{value:h,onChange:g})]})},ho=({mode:e,account:t,sourceMessage:s,onClose:n,onAccountChange:a})=>{const{state:o,setOutboxMessageId:i,startSendPolling:l}=Ht(),{pushError:u}=lt(),{outboxMessageId:m}=o,[d,f]=c.useState([]),[h,g]=c.useState([]),[x,p]=c.useState([]),[v,b]=c.useState(""),[S,w]=c.useState(!1),[y,j]=c.useState(!1),[E,M]=c.useState(t?.accountId),[N,A]=c.useState(!1),L=c.useRef(m);c.useEffect(()=>{L.current!==m&&(L.current=m,m&&(f([]),g([]),p([]),b(""),w(!1),j(!1),R(gu),A(!1)))},[m]);const{signature:O}=Nm(E),[D,R]=c.useState(()=>vv(O.plainText)),{data:k}=ve({...$f({path:{outboxMessageId:m??""}}),enabled:!!m&&!N});c.useEffect(()=>{!k||N||(f(k.toAddresses.map(z=>({email:z,displayName:void 0}))),k.ccAddresses&&k.ccAddresses.length>0&&(g(k.ccAddresses.map(z=>({email:z,displayName:void 0}))),w(!0)),k.bccAddresses&&k.bccAddresses.length>0&&(p(k.bccAddresses.map(z=>({email:z,displayName:void 0}))),j(!0)),k.subject&&b(k.subject),k.textBody&&R([{type:"p",children:[{text:k.textBody}]}]),M(k.accountId),A(!0))},[k,N]),c.useEffect(()=>{if(s){if(e==="reply"||e==="reply_all"){const{to:z,cc:ce}=Sv(s,e,t?.email);f(z),g(ce),ce.length>0&&w(!0),b(yv(s.envelope.subject))}e==="forward"&&b(wv(s.envelope.subject))}},[e,s,t?.email]);const P=e==="reply"||e==="reply_all"||e==="forward",{data:F}=du({messageId:s?.message.messageId,bodyParts:s?.bodyParts,enabled:P&&!!s}),C=F?.kind==="text"?F.body:"",T=F?.kind==="html"?pv(F.body):void 0,I=s?.envelope.from[0]?.displayName??s?.envelope.from[0]?.normalizedEmail,{saveStatus:q,saveError:se,saveDraft:G,cancelAutoSave:oe}=av({outboxMessageId:m,onDraftCreated:i});c.useEffect(()=>{se&&u({title:"Couldn't save draft",detail:ht(se)??"Saving the draft failed.",error:se})},[se,u]);const ne=Oe(Ll()),Z=Oe(_l()),pe=Oe({...sr(),onError:z=>{u(ts("Couldn't discard draft","The draft wasn't discarded.",z))}}),{data:me}=ve({...Mt(),staleTime:1/0}),Q=me?.accounts.find(z=>z.accountId===E),H=Q?Cm(Q):!1,de=ne.isPending||Z.isPending,ee=d.length>0&&!!E&&!H;c.useEffect(()=>{if(!E||m&&!N||Cv(d,h,x,v,D))return;const z=va(D),ce=Qi(D);G({accountId:E,toAddresses:d.map(be=>be.email),ccAddresses:h.length>0?h.map(be=>be.email):void 0,bccAddresses:x.length>0?x.map(be=>be.email):void 0,subject:v||void 0,textBody:z||void 0,htmlBody:ce||void 0})},[E,m,N,d,h,x,v,D,G]);const fe=c.useCallback(async()=>{if(!E||d.length===0)return;oe();const z=s&&(e==="reply"||e==="reply_all")?kv(s):{};let ce=m,be=!1;if(!ce){const ge=va(D),ie=Qi(D),Ae=await ne.mutateAsync({body:{accountId:E,toAddresses:d.map(we=>we.email),ccAddresses:h.length>0?h.map(we=>we.email):void 0,bccAddresses:x.length>0?x.map(we=>we.email):void 0,subject:v||void 0,textBody:ge||void 0,htmlBody:ie||void 0,sendImmediately:!0,...z}}).catch(we=>(u({title:"Couldn't send message",detail:ht(we)??"Saving the draft failed.",error:we}),null));if(Ae===null)return;ce=Ae.outboxMessageId,be=!0,i(ce)}await Z.mutateAsync({path:{outboxMessageId:ce}}).catch(ge=>(u({title:"Couldn't send message",detail:ht(ge)??(be?"The draft was saved but the send request failed. Try again from the Outbox.":"The send request failed. Try again."),error:ge}),null))!==null&&(l(ce),n())},[E,d,h,x,v,D,e,s,m,ne,Z,oe,l,i,u,n]),U=c.useCallback(()=>{oe(),m&&pe.mutate({path:{outboxMessageId:m}}),n()},[oe,m,pe,n]),_=c.useCallback(z=>{M(z.accountId),a?.(z)},[a]);return r.jsx(Vp,{banner:Q&&H?r.jsx(cv,{accountId:Q.accountId}):void 0,header:r.jsx(jv,{selectedAccountId:E,onAccountChange:_,toAddresses:d,setToAddresses:f,ccAddresses:h,setCcAddresses:g,bccAddresses:x,setBccAddresses:p,showCc:S,setShowCc:w,showBcc:y,setShowBcc:j,subject:v,setSubject:b}),quoted:C||T?r.jsx(hg,{text:C,html:T,senderName:I}):void 0,actionBar:r.jsx(Wp,{onSend:fe,onDiscard:U,sending:de,canSend:ee,saveStatus:q,unavailableReason:H?"SMTP not configured":void 0,onUnavailable:z=>u({title:"Can't send yet",detail:z})}),children:r.jsx(c.Suspense,{fallback:r.jsx(xv,{}),children:r.jsx(gv,{value:D,onChange:R,onSubmit:fe,autoFocus:e==="new"})})})},Xi=({mode:e,account:t,sourceMessage:s,onClose:n})=>r.jsx("div",{className:"border-t border-line bg-canvas max-h-[400px] flex flex-col",children:r.jsx(ho,{mode:e,account:t,sourceMessage:s,onClose:n})}),xu=({message:e,icon:t})=>r.jsxs("div",{className:"flex flex-col items-center justify-center p-8 text-center",children:[t&&r.jsx("div",{className:"mb-4 text-fg-muted",children:t}),r.jsx("p",{className:"text-fg-muted",children:e})]}),po=({enabled:e=!0,bindings:t,capture:s=!1})=>{const n=c.useCallback(a=>{const o=a.target;if(!(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))for(const i of t){if(!(a.key.toLowerCase()===i.key.toLowerCase())||i.requireShift!==void 0&&i.requireShift!==a.shiftKey)continue;const u=a.ctrlKey||a.metaKey;if(i.requireMeta!==void 0){if(i.requireMeta!==u)continue}else{const m=i.noModifiers??!0,d=u||a.altKey||i.requireShift===void 0&&a.shiftKey;if(m&&d)continue}i.preventDefault&&a.preventDefault(),i.stopPropagation&&(a.stopPropagation(),a.stopImmediatePropagation()),i.handler(a);return}},[t]);c.useEffect(()=>{if(e)return window.addEventListener("keydown",n,s),()=>window.removeEventListener("keydown",n,s)},[e,n,s])},go=e=>{const{data:t,isLoading:s}=ve({...Mt(),staleTime:1/0}),n=c.useMemo(()=>(t?.accounts??[]).map(l=>l.accountId),[t?.accounts]),a=gt({queries:n.map(l=>({...it({path:{accountId:l}}),staleTime:1/0,enabled:!!e}))}),o=s||a.some(l=>l.isLoading);return{accountId:c.useMemo(()=>{if(e){for(let l=0;l<n.length;l++)if((a[l].data?.items??[]).some(d=>d.mailboxId===e))return n[l]}},[e,n,a]),isLoading:o}},Nv=100,qn=async e=>e.then(t=>({ok:!0,value:t}),t=>({ok:!1,error:t})),Ev=(e,t=Nv)=>{if(e.length===0)return[];const s=[];for(let n=0;n<e.length;n+=t)s.push(e.slice(n,n+t));return s},bu=async(e,t,s,n)=>{const a=Ev(e),o=e.length;let i=0;const l=[];for(let u=0;u<a.length;u++){if(n())return l.push(...a.slice(u).flat()),{done:i,failedIds:l,cancelled:!0};const m=a[u],d=await qn(t(m));if(!d.ok)return l.push(...a.slice(u).flat()),s({done:i,total:o}),{done:i,failedIds:l,cancelled:!1,error:d.error};i+=m.length,s({done:i,total:o})}return{done:i,failedIds:l,cancelled:!1}},br=async(e,t)=>{await bu(e,async s=>(await t(s),{successCount:s.length,failureCount:0}),()=>{},()=>!1)},Iv=async(e,t,s,n,a)=>{let o=0;const i=[];let l;do{if(a())return{done:o,failedIds:i,cancelled:!0};const u=await qn(e(l));if(!u.ok)return{done:o,failedIds:i,cancelled:!1,error:u.error};const m=u.value;if(m.ids.length>0){const d=await qn(s(m.ids));if(!d.ok)return{done:o,failedIds:i,cancelled:!1,error:d.error};o+=m.ids.length,n({done:o,total:t})}l=m.continuationToken}while(l);return{done:o,failedIds:i,cancelled:!1}},Tv=e=>({done:e.done,total:Math.max(e.total,e.done)}),Rv=async(e,t,s)=>{let n=0,a;do{if(s())return{total:n,cancelled:!0};const o=await qn(e(a));if(!o.ok)return{total:n,cancelled:!1,error:o.error};const i=o.value;n+=i.ids.length,t(n),a=i.continuationToken}while(a);return{total:n,cancelled:!1}},vu=e=>typeof e=="object"&&e!==null&&Array.isArray(e.pages),yu=e=>typeof e=="object"&&e!==null&&Array.isArray(e.items),wu=(e,t)=>e===void 0?e:vu(e)?{...e,pages:e.pages.map(s=>({...s,items:t(s.items)}))}:yu(e)?{...e,items:t(e.items)}:e,Ot=e=>{const t=[];for(const s of new Set(e))t.push(nr({path:{mailboxId:s}})),t.push(Ka({path:{mailboxId:s}}));return t.push(Ua()),t},dn=(e,t)=>Promise.all(t.map(s=>e.cancelQueries({queryKey:s}))),fn=(e,t)=>t.flatMap(s=>e.getQueriesData({queryKey:s})).filter(s=>s[1]!==void 0).map(([s,n])=>({queryKey:s,data:n})),mn=(e,t,s)=>{const n=a=>wu(a,s);for(const a of t)e.setQueriesData({queryKey:a},n)},hn=(e,t)=>{for(const s of t)e.setQueryData(s.queryKey,s.data)},Dt=(e,t)=>{for(const s of t)e.invalidateQueries({queryKey:s})},Mv=3e3,Av=(e,t,s)=>{if(e.length===0)return()=>{};const n=setTimeout(()=>s(e),t);return()=>clearTimeout(n)},vr=(e,t,s)=>{const n=new Map(t.map(o=>[o.messageId,o.mailboxId])),a=new Set;for(const o of e)a.add(n.get(o)??s);return[...a]},Hn=(e,t,s)=>e.map(n=>t.has(n.messageId)?{...n,isRead:s}:n),Ov=(e,t,s,n)=>e.filter(a=>!a.isRead&&t.has(a.threadMessageId)&&!s.has(a.messageId)&&!n.has(a.messageId)).map(a=>a.messageId),Dv=({messages:e,expandedIds:t,threadId:s,mailboxId:n,accountId:a})=>{const o=Re(),{pushError:i}=lt(),l=c.useRef(new Set),u=c.useRef(new Set),{mutate:m}=Oe({...rr(),onMutate:async h=>{const g=new Set(h.body.messageIds??[]),x=h.body.isRead??!0,p=ls({path:{threadId:s}}),v=Ot(vr(g,e,n));await Promise.all([o.cancelQueries({queryKey:p}),dn(o,v)]);const b=o.getQueriesData({queryKey:p}).filter(w=>w[1]!==void 0).map(([w,y])=>({queryKey:w,data:y})),S=fn(o,v);return o.setQueriesData({queryKey:p},w=>w&&{...w,items:Hn(w.items,g,x)}),mn(o,v,w=>Hn(w,g,x)),{threadMessagesPrefix:p,listPrefixes:v,previousThreadMessages:b,previousThreadsList:S}},onSuccess:(h,g)=>{const x=g.body.messageIds??[];for(const p of x)l.current.add(p),u.current.delete(p)},onError:(h,g,x)=>{const p=g.body.messageIds??[];for(const b of p)u.current.delete(b);if(x){for(const b of x.previousThreadMessages)o.setQueryData(b.queryKey,b.data);hn(o,x.previousThreadsList)}const v=g.body.isRead??!0;i({title:v?"Couldn't mark as read":"Couldn't mark as unread",detail:ht(h),error:h})},onSettled:(h,g,x,p)=>{p&&(o.invalidateQueries({queryKey:p.threadMessagesPrefix}),Dt(o,p.listPrefixes),a&&o.invalidateQueries({queryKey:is({path:{accountId:a}})}))}}),d=c.useCallback(h=>{const g=h.filter(x=>!l.current.has(x)&&!u.current.has(x));if(g.length!==0){for(const x of g)u.current.add(x);m({body:{messageIds:g,isRead:!0}})}},[m]),f=c.useMemo(()=>Ov(e,t,l.current,u.current),[e,t]);c.useEffect(()=>Av(f,Mv,d),[f,d]),c.useEffect(()=>{l.current.clear(),u.current.clear()},[s])},yr=e=>{const{mailboxId:t,accountId:s,messages:n}=e,a=Re(),{pushError:o}=lt(),{mutateAsync:i,isPending:l}=Oe({...rr(),onError:(m,d)=>{const f=d.body.isRead??!0;o({title:f?"Couldn't mark as read":"Couldn't mark as unread",detail:ht(m),error:m})},onSettled:(m,d,f)=>{Dt(a,Ot(vr(f.body.messageIds??[],n??[],t))),s&&a.invalidateQueries({queryKey:is({path:{accountId:s}})})}});return{toggleReadFor:c.useCallback((m,d)=>{m.length!==0&&br(m,f=>i({body:{messageIds:f,isRead:d}}))},[i]),isPending:l}},Pv=60,Lv=1.5,Fv=(e,t,s)=>{const n=Math.abs(e),a=Math.abs(t);return n<s?{direction:null}:n<a*Lv?{direction:null}:{direction:e<0?"left":"right"}},$v=({onSwipeLeft:e,onSwipeRight:t,thresholdPx:s=Pv})=>{const n=c.useRef(null),a=c.useCallback(u=>{if(u.pointerType==="mouse"){n.current=null;return}n.current={x:u.clientX,y:u.clientY}},[]),o=c.useCallback(()=>{},[]),i=c.useCallback(u=>{const m=n.current;if(n.current=null,!m)return;const{direction:d}=Fv(u.clientX-m.x,u.clientY-m.y,s);d==="left"&&e?.(),d==="right"&&t?.()},[e,t,s]),l=c.useCallback(()=>{n.current=null},[]);return{handlers:{onPointerDown:a,onPointerMove:o,onPointerUp:i,onPointerCancel:l}}},_v=(e,t,s)=>t?.find(n=>n.messageId===e)?.mailboxId??s,Ji=(e,t,s)=>e.map(n=>n.messageId===t?{...n,hasStars:s}:n),xo=({threadId:e,mailboxId:t,messages:s})=>{const n=Re(),{pushError:a}=lt(),{mutate:o,isPending:i,variables:l}=Oe({...zf(),onMutate:async m=>{const d=m.path.messageId,f=m.body.isStarred??!1,h=ls({path:{threadId:e}}),g=Ot([_v(d,s,t)]);await Promise.all([n.cancelQueries({queryKey:h}),dn(n,g)]);const x=n.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,b])=>({queryKey:v,data:b})),p=fn(n,g);return n.setQueriesData({queryKey:h},v=>wu(v,b=>Ji(b,d,f))),mn(n,g,v=>Ji(v,d,f)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:x,previousThreadsList:p}},onError:(m,d,f)=>{if(f){for(const g of f.previousThreadMessages)n.setQueryData(g.queryKey,g.data);hn(n,f.previousThreadsList)}const h=d.body.isStarred??!1;a({title:h?"Couldn't star message":"Couldn't unstar message",detail:ht(m),error:m})},onSettled:(m,d,f,h)=>{h&&(n.invalidateQueries({queryKey:h.threadMessagesPrefix}),Dt(n,h.listPrefixes))}});return{toggleStar:(m,d)=>{o({path:{messageId:m},body:{isStarred:!d}})},isPending:i,pendingMessageId:i?l?.path.messageId:void 0}};function wr(e){return e===void 0?"uncategorized":e}const zv={inbox:"Inbox",junk:"Junk"},bo=e=>e.destinationMailboxId!==void 0,Bv=(e,t)=>{if(bo(e))return`Moved from ${t??"another folder"} by Remit`;const s=e.fromPlacement??"";return`Moved from ${zv[s]??"another folder"} by Remit`},Kv=(e,t)=>{if(e===Wo.MoveToInbox)return t.inboxMailboxId;if(e===Wo.MoveToJunk)return t.junkMailboxId},Uv=(e,t,s)=>{if(!e||!t)return!1;const n=bo(e)?e.destinationMailboxId:Kv(e.action,s);return n!==void 0&&n===t},qv=(e,t)=>{if(e){if(bo(e))return e.fromMailboxId;if(e.fromPlacement==="inbox")return t.inboxMailboxId;if(e.fromPlacement==="junk")return t.junkMailboxId}},Sr=(e,t)=>{const{data:s,isLoading:n}=ve({...Mt(),staleTime:1/0,enabled:!!e});return{mailboxId:c.useMemo(()=>e?s?.accounts.find(i=>i.accountId===e)?.folderAppointments.find(i=>i.role===t)?.mailboxId:void 0,[s,e,t]),isLoading:n}},Hv=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Archive");return{archiveMailboxId:t,isLoading:s}},Wv=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Drafts");return{draftsMailboxId:t,isLoading:s}},vo=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Inbox");return{inboxMailboxId:t,isLoading:s}},Fs=e=>{const{mailboxId:t,isLoading:s}=Sr(e,"Junk");return{junkMailboxId:t,isLoading:s}},yo=e=>{const{data:t}=ve({...Mt(),staleTime:1/0,enabled:!!e});return c.useMemo(()=>t?.accounts.find(s=>s.accountId===e)?.folderAppointments??[],[t,e])},Zi=(e,t)=>e.filter(s=>!t.has(s.messageId)),rs=({mailboxId:e,threadId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=Re(),{pushError:o}=lt(),{mutateAsync:i,isPending:l}=Oe({...Bf(),onMutate:async m=>{const d=new Set(m.body.messageIds??[]),f=t?ls({path:{threadId:t}}):[],h=Ot([e,m.body.destinationMailboxId]);await Promise.all([...t?[a.cancelQueries({queryKey:f})]:[],dn(a,h)]);const g=t?a.getQueriesData({queryKey:f}).filter(p=>p[1]!==void 0).map(([p,v])=>({queryKey:p,data:v})):[],x=fn(a,h);return t&&a.setQueriesData({queryKey:f},p=>p&&{...p,items:Zi(p.items,d)}),mn(a,h,p=>Zi(p,d)),n?.(Array.from(d)),{threadMessagesPrefix:f,listPrefixes:h,previousThreadMessages:g,previousThreadsList:x}},onError:(m,d,f)=>{if(f){for(const g of f.previousThreadMessages)a.setQueryData(g.queryKey,g.data);hn(a,f.previousThreadsList)}const h=d.body.messageIds?.length??0;o({title:h>1?`Couldn't move ${h} messages`:"Couldn't move this message",detail:ht(m),error:m})},onSettled:(m,d,f,h)=>{h&&(t&&a.invalidateQueries({queryKey:h.threadMessagesPrefix}),Dt(a,h.listPrefixes),s&&a.invalidateQueries({queryKey:is({path:{accountId:s}})}))}});return{moveMessages:c.useCallback((m,d)=>{m.length!==0&&br(m,f=>i({body:{messageIds:f,destinationMailboxId:d}}))},[i]),isPending:l}},Vv=({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a})=>{const{inboxMailboxId:o}=vo(e),{junkMailboxId:i}=Fs(e),{moveMessages:l,isPending:u}=rs({mailboxId:n,threadId:s,accountId:e}),{data:m}=ve({...it({path:{accountId:e??""}}),staleTime:1/0,enabled:!!e&&a?.fromMailboxId!==void 0}),d={inboxMailboxId:o,junkMailboxId:i},f=Uv(a,n,d),h=qv(a,d),g=c.useCallback(()=>{h&&l([t],h)},[l,t,h]);if(!f||!a)return{show:!1,label:"",isUndoing:!1};const x=a.fromMailboxId?m?.items.filter(p=>p.mailboxId===a.fromMailboxId).map(p=>zn(p.fullPath))[0]:void 0;return{show:!0,label:Bv(a,x),onUndo:h?g:void 0,isUndoing:u,...a.filterId?{filtersHref:"/settings/filters"}:{}}};function Qv({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a}){const o=Vv({accountId:e,messageId:t,threadId:s,mailboxId:n,autoMoved:a});return o.show?r.jsx(Kp,{label:o.label,onUndo:o.onUndo,undoLabel:o.isUndoing?"Undoing…":"Undo",filtersHref:o.filtersHref}):null}const el=(e,t)=>e.filter(s=>!t.has(s.messageId)),Gv=e=>e.filter(t=>t.isDeleted!==!0),as=({mailboxId:e,threadId:t,accountId:s,messages:n,onAfterOptimisticRemove:a})=>{const o=Re(),{pushError:i}=lt(),{mutateAsync:l,isPending:u}=Oe({...Kf(),onMutate:async d=>{const f=new Set(d.body.messageIds??[]),h=t?ls({path:{threadId:t}}):[],g=Ot(vr(f,n??[],e));await Promise.all([o.cancelQueries({queryKey:h}),dn(o,g)]);const x=t?o.getQueriesData({queryKey:h}).filter(v=>v[1]!==void 0).map(([v,b])=>({queryKey:v,data:b})):[],p=fn(o,g);return t&&o.setQueriesData({queryKey:h},v=>v&&{...v,items:el(v.items,f)}),mn(o,g,v=>el(v,f)),a?.(Array.from(f)),{threadMessagesPrefix:h,listPrefixes:g,previousThreadMessages:x,previousThreadsList:p}},onError:(d,f,h)=>{if(h){for(const x of h.previousThreadMessages)o.setQueryData(x.queryKey,x.data);hn(o,h.previousThreadsList)}const g=f.body.messageIds?.length??0;i({title:g>1?`Couldn't delete ${g} messages`:"Couldn't delete this message",detail:ht(d),error:d})},onSettled:(d,f,h,g)=>{g&&(t&&o.invalidateQueries({queryKey:g.threadMessagesPrefix}),Dt(o,g.listPrefixes),s&&o.invalidateQueries({queryKey:is({path:{accountId:s}})}))}});return{deleteMessages:c.useCallback(d=>{d.length!==0&&br(d,f=>l({body:{messageIds:f}}))},[l]),isPending:u}},Su=(e,t=Date.now())=>({value:e,setAt:t}),Yv=(e,t,s,n)=>{if(e.addressId!==t)return e;const a={...e.flags??{}};return s?a.trusted=Su(!0,n):delete a.trusted,{...e,flags:a}},Xv=(e,t,s,n)=>{const a=o=>o.map(i=>Yv(i,t,s,n));return{...e,envelope:{...e.envelope,from:a(e.envelope.from),to:a(e.envelope.to),cc:a(e.envelope.cc),bcc:a(e.envelope.bcc),replyTo:a(e.envelope.replyTo)}}},wo=({messageId:e})=>{const t=Re(),{pushError:s}=lt(),{mutate:n,isPending:a,error:o,reset:i}=Oe({...zl(),onMutate:async u=>{const m=u.path.addressId,f=u.body.flags?.trusted?.value===!0,h=Pl({path:{messageId:e}});await t.cancelQueries({queryKey:h});const g=t.getQueriesData({queryKey:h}).filter(x=>x[1]!==void 0).map(([x,p])=>({queryKey:x,data:p}));return t.setQueriesData({queryKey:h},x=>x&&Xv(x,m,f)),{describePrefix:h,previous:g}},onError:(u,m,d)=>{if(d)for(const f of d.previous)t.setQueryData(f.queryKey,f.data);s(ts("Couldn't trust sender","The change wasn't saved.",u))},onSettled:(u,m,d,f)=>{f&&t.invalidateQueries({queryKey:f.describePrefix})}});return{toggleTrusted:(u,m)=>{n({path:{addressId:u},body:{flags:{trusted:Su(!m)}}})},isPending:a,error:o,reset:i}};var kr="Dialog",[ku]=rx(kr),[Jv,xt]=ku(kr),Cu=e=>{const{__scopeDialog:t,children:s,open:n,defaultOpen:a,onOpenChange:o,modal:i=!0}=e,l=c.useRef(null),u=c.useRef(null),[m,d]=ix({prop:n,defaultProp:a??!1,onChange:o,caller:kr});return r.jsx(Jv,{scope:t,triggerRef:l,contentRef:u,contentId:Hr(),titleId:Hr(),descriptionId:Hr(),open:m,onOpenChange:d,onOpenToggle:c.useCallback(()=>d(f=>!f),[d]),modal:i,children:s})};Cu.displayName=kr;var ju="DialogTrigger",Zv=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(ju,s),o=cs(t,a.triggerRef);return r.jsx(At.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":ko(a.open),...n,ref:o,onClick:Bt(e.onClick,a.onOpenToggle)})});Zv.displayName=ju;var So="DialogPortal",[ey,Nu]=ku(So,{forceMount:void 0}),Eu=e=>{const{__scopeDialog:t,forceMount:s,children:n,container:a}=e,o=xt(So,t);return r.jsx(ey,{scope:t,forceMount:s,children:c.Children.map(n,i=>r.jsx(hr,{present:s||o.open,children:r.jsx(Bc,{asChild:!0,container:a,children:i})}))})};Eu.displayName=So;var Wn="DialogOverlay",Iu=c.forwardRef((e,t)=>{const s=Nu(Wn,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=xt(Wn,e.__scopeDialog);return o.modal?r.jsx(hr,{present:n||o.open,children:r.jsx(sy,{...a,ref:t})}):null});Iu.displayName=Wn;var ty=lo("DialogOverlay.RemoveScroll"),sy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Wn,s),o=Nx(),i=cs(t,o);return r.jsx(Gc,{as:ty,allowPinchZoom:!0,shards:[a.contentRef],children:r.jsx(At.div,{"data-state":ko(a.open),...n,ref:i,style:{pointerEvents:"auto",...n.style}})})}),Rs="DialogContent",Tu=c.forwardRef((e,t)=>{const s=Nu(Rs,e.__scopeDialog),{forceMount:n=s.forceMount,...a}=e,o=xt(Rs,e.__scopeDialog);return r.jsx(hr,{present:n||o.open,children:o.modal?r.jsx(ny,{...a,ref:t}):r.jsx(ry,{...a,ref:t})})});Tu.displayName=Rs;var ny=c.forwardRef((e,t)=>{const s=xt(Rs,e.__scopeDialog),n=c.useRef(null),a=cs(t,s.contentRef,n);return c.useEffect(()=>{const o=n.current;if(o)return Qx(o)},[]),r.jsx(Ru,{...e,ref:a,trapFocus:s.open,disableOutsidePointerEvents:s.open,onCloseAutoFocus:Bt(e.onCloseAutoFocus,o=>{o.preventDefault(),s.triggerRef.current?.focus()}),onPointerDownOutside:Bt(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&o.preventDefault()}),onFocusOutside:Bt(e.onFocusOutside,o=>o.preventDefault())})}),ry=c.forwardRef((e,t)=>{const s=xt(Rs,e.__scopeDialog),n=c.useRef(!1),a=c.useRef(!1);return r.jsx(Ru,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(n.current||s.triggerRef.current?.focus(),o.preventDefault()),n.current=!1,a.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const i=o.target;s.triggerRef.current?.contains(i)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&a.current&&o.preventDefault()}})}),Ru=c.forwardRef((e,t)=>{const{__scopeDialog:s,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,l=xt(Rs,s);return Rx(),r.jsx(r.Fragment,{children:r.jsx(_c,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:o,children:r.jsx(Fc,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":ko(l.open),...i,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),Mu="DialogTitle",Au=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Mu,s);return r.jsx(At.h2,{id:a.titleId,...n,ref:t})});Au.displayName=Mu;var Ou="DialogDescription",ay=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Ou,s);return r.jsx(At.p,{id:a.descriptionId,...n,ref:t})});ay.displayName=Ou;var Du="DialogClose",oy=c.forwardRef((e,t)=>{const{__scopeDialog:s,...n}=e,a=xt(Du,s);return r.jsx(At.button,{type:"button",...n,ref:t,onClick:Bt(e.onClick,()=>a.onOpenChange(!1))})});oy.displayName=Du;function ko(e){return e?"open":"closed"}function iy(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",t.appendChild(s),s.styleSheet?s.styleSheet.cssText=e:s.appendChild(document.createTextNode(e))}const Pu=K.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),pn=()=>{const e=K.useContext(Pu);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};iy(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(
|
|
117
117
|
[data-state=closed]
|
|
118
118
|
){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}`);function ly(){const e=navigator.userAgent;return typeof window<"u"&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))}function cy(){return Co(/^Mac/)}function uy(){return Co(/^iPhone/)}function tl(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function dy(){return Co(/^iPad/)||cy()&&navigator.maxTouchPoints>1}function Lu(){return uy()||dy()}function Co(e){return typeof window<"u"&&window.navigator!=null?e.test(window.navigator.platform):void 0}const fy=24,my=typeof window<"u"?c.useLayoutEffect:c.useEffect;function sl(...e){return(...t)=>{for(let s of e)typeof s=="function"&&s(...t)}}const Xr=typeof document<"u"&&window.visualViewport;function nl(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function Fu(e){for(nl(e)&&(e=e.parentElement);e&&!nl(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const hy=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let Rn=0,Jr;function py(e={}){let{isDisabled:t}=e;my(()=>{if(!t)return Rn++,Rn===1&&Lu()&&(Jr=gy()),()=>{Rn--,Rn===0&&Jr?.()}},[t])}function gy(){let e,t=0,s=f=>{e=Fu(f.target),!(e===document.documentElement&&e===document.body)&&(t=f.changedTouches[0].pageY)},n=f=>{if(!e||e===document.documentElement||e===document.body){f.preventDefault();return}let h=f.changedTouches[0].pageY,g=e.scrollTop,x=e.scrollHeight-e.clientHeight;x!==0&&((g<=0&&h>t||g>=x&&h<t)&&f.preventDefault(),t=h)},a=f=>{let h=f.target;ya(h)&&h!==document.activeElement&&(f.preventDefault(),h.style.transform="translateY(-2000px)",h.focus(),requestAnimationFrame(()=>{h.style.transform=""}))},o=f=>{let h=f.target;ya(h)&&(h.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{h.style.transform="",Xr&&(Xr.height<window.innerHeight?requestAnimationFrame(()=>{rl(h)}):Xr.addEventListener("resize",()=>rl(h),{once:!0}))}))},i=()=>{window.scrollTo(0,0)},l=window.pageXOffset,u=window.pageYOffset,m=sl(xy(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let d=sl(Us(document,"touchstart",s,{passive:!1,capture:!0}),Us(document,"touchmove",n,{passive:!1,capture:!0}),Us(document,"touchend",a,{passive:!1,capture:!0}),Us(document,"focus",o,!0),Us(window,"scroll",i));return()=>{m(),d(),window.scrollTo(l,u)}}function xy(e,t,s){let n=e.style[t];return e.style[t]=s,()=>{e.style[t]=n}}function Us(e,t,s,n){return e.addEventListener(t,s,n),()=>{e.removeEventListener(t,s,n)}}function rl(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let s=Fu(e);if(s!==document.documentElement&&s!==document.body&&s!==e){let n=s.getBoundingClientRect().top,a=e.getBoundingClientRect().top,o=e.getBoundingClientRect().bottom;const i=s.getBoundingClientRect().bottom+fy;o>i&&(s.scrollTop+=a-n)}e=s.parentElement}}function ya(e){return e instanceof HTMLInputElement&&!hy.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function by(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function vy(...e){return t=>e.forEach(s=>by(s,t))}function $u(...e){return c.useCallback(vy(...e),e)}const _u=new WeakMap;function ze(e,t,s=!1){if(!e||!(e instanceof HTMLElement))return;let n={};Object.entries(t).forEach(([a,o])=>{if(a.startsWith("--")){e.style.setProperty(a,o);return}n[a]=e.style[a],e.style[a]=o}),!s&&_u.set(e,n)}function yy(e,t){if(!e||!(e instanceof HTMLElement))return;let s=_u.get(e);s&&(e.style[t]=s[t])}const Fe=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function Mn(e,t){if(!e)return null;const s=window.getComputedStyle(e),n=s.transform||s.webkitTransform||s.mozTransform;let a=n.match(/^matrix3d\((.+)\)$/);return a?parseFloat(a[1].split(", ")[Fe(t)?13:12]):(a=n.match(/^matrix\((.+)\)$/),a?parseFloat(a[1].split(", ")[Fe(t)?5:4]):null)}function wy(e){return 8*(Math.log(e+1)-2)}function Zr(e,t){if(!e)return()=>{};const s=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=s}}function Sy(...e){return(...t)=>{for(const s of e)typeof s=="function"&&s(...t)}}const Te={DURATION:.5,EASE:[.32,.72,0,1]},zu=.4,ky=.25,Cy=100,Bu=8,Jt=16,wa=26,ea="vaul-dragging";function Ku(e){const t=K.useRef(e);return K.useEffect(()=>{t.current=e}),K.useMemo(()=>(...s)=>t.current==null?void 0:t.current.call(t,...s),[])}function jy({defaultProp:e,onChange:t}){const s=K.useState(e),[n]=s,a=K.useRef(n),o=Ku(t);return K.useEffect(()=>{a.current!==n&&(o(n),a.current=n)},[n,a,o]),s}function Uu({prop:e,defaultProp:t,onChange:s=()=>{}}){const[n,a]=jy({defaultProp:t,onChange:s}),o=e!==void 0,i=o?e:n,l=Ku(s),u=K.useCallback(m=>{if(o){const f=typeof m=="function"?m(e):m;f!==e&&l(f)}else a(m)},[o,e,a,l]);return[i,u]}function Ny({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:s,drawerRef:n,overlayRef:a,fadeFromIndex:o,onSnapPointChange:i,direction:l="bottom",container:u,snapToSequentialPoint:m}){const[d,f]=Uu({prop:e,defaultProp:s?.[0],onChange:t}),[h,g]=K.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);K.useEffect(()=>{function M(){g({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",M),()=>window.removeEventListener("resize",M)},[]);const x=K.useMemo(()=>d===s?.[s.length-1]||null,[s,d]),p=K.useMemo(()=>{var M;return(M=s?.findIndex(N=>N===d))!=null?M:null},[s,d]),v=s&&s.length>0&&(o||o===0)&&!Number.isNaN(o)&&s[o]===d||!s,b=K.useMemo(()=>{const M=u?{width:u.getBoundingClientRect().width,height:u.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var N;return(N=s?.map(A=>{const L=typeof A=="string";let O=0;if(L&&(O=parseInt(A,10)),Fe(l)){const R=L?O:h?A*M.height:0;return h?l==="bottom"?M.height-R:-M.height+R:R}const D=L?O:h?A*M.width:0;return h?l==="right"?M.width-D:-M.width+D:D}))!=null?N:[]},[s,h,u]),S=K.useMemo(()=>p!==null?b?.[p]:null,[b,p]),w=K.useCallback(M=>{var N;const A=(N=b?.findIndex(L=>L===M))!=null?N:null;i(A),ze(n.current,{transition:`transform ${Te.DURATION}s cubic-bezier(${Te.EASE.join(",")})`,transform:Fe(l)?`translate3d(0, ${M}px, 0)`:`translate3d(${M}px, 0, 0)`}),b&&A!==b.length-1&&o!==void 0&&A!==o&&A<o?ze(a.current,{transition:`opacity ${Te.DURATION}s cubic-bezier(${Te.EASE.join(",")})`,opacity:"0"}):ze(a.current,{transition:`opacity ${Te.DURATION}s cubic-bezier(${Te.EASE.join(",")})`,opacity:"1"}),f(s?.[Math.max(A,0)])},[n.current,s,b,o,a,f]);K.useEffect(()=>{if(d||e){var M;const N=(M=s?.findIndex(A=>A===e||A===d))!=null?M:-1;b&&N!==-1&&typeof b[N]=="number"&&w(b[N])}},[d,e,s,b,w]);function y({draggedDistance:M,closeDrawer:N,velocity:A,dismissible:L}){if(o===void 0)return;const O=l==="bottom"||l==="right"?(S??0)-M:(S??0)+M,D=p===o-1,R=p===0,k=M>0;if(D&&ze(a.current,{transition:`opacity ${Te.DURATION}s cubic-bezier(${Te.EASE.join(",")})`}),!m&&A>2&&!k){L?N():w(b[0]);return}if(!m&&A>2&&k&&b&&s){w(b[s.length-1]);return}const P=b?.reduce((C,T)=>typeof C!="number"||typeof T!="number"?C:Math.abs(T-O)<Math.abs(C-O)?T:C),F=Fe(l)?window.innerHeight:window.innerWidth;if(A>zu&&Math.abs(M)<F*.4){const C=k?1:-1;if(C>0&&x&&s){w(b[s.length-1]);return}if(R&&C<0&&L&&N(),p===null)return;w(b[p+C]);return}w(P)}function j({draggedDistance:M}){if(S===null)return;const N=l==="bottom"||l==="right"?S-M:S+M;(l==="bottom"||l==="right")&&N<b[b.length-1]||(l==="top"||l==="left")&&N>b[b.length-1]||ze(n.current,{transform:Fe(l)?`translate3d(0, ${N}px, 0)`:`translate3d(${N}px, 0, 0)`})}function E(M,N){if(!s||typeof p!="number"||!b||o===void 0)return null;const A=p===o-1;if(p>=o&&N)return 0;if(A&&!N)return 1;if(!v&&!A)return null;const O=A?p+1:p-1,D=A?b[O]-b[O-1]:b[O+1]-b[O],R=M/Math.abs(D);return A?1-R:R}return{isLastSnapPoint:x,activeSnapPoint:d,shouldFade:v,getPercentageDragged:E,setActiveSnapPoint:f,activeSnapPointIndex:p,onRelease:y,onDrag:j,snapPointsOffset:b}}const Ey=()=>()=>{};function Iy(){const{direction:e,isOpen:t,shouldScaleBackground:s,setBackgroundColorOnScale:n,noBodyStyles:a}=pn(),o=K.useRef(null),i=c.useMemo(()=>document.body.style.backgroundColor,[]);function l(){return(window.innerWidth-wa)/window.innerWidth}K.useEffect(()=>{if(t&&s){o.current&&clearTimeout(o.current);const u=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!u)return;Sy(n&&!a?Zr(document.body,{background:"black"}):Ey,Zr(u,{transformOrigin:Fe(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${Te.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Te.EASE.join(",")})`}));const m=Zr(u,{borderRadius:`${Bu}px`,overflow:"hidden",...Fe(e)?{transform:`scale(${l()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${l()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{m(),o.current=window.setTimeout(()=>{i?document.body.style.background=i:document.body.style.removeProperty("background")},Te.DURATION*1e3)}}},[t,s,i])}let qs=null;function Ty({isOpen:e,modal:t,nested:s,hasBeenOpened:n,preventScrollRestoration:a,noBodyStyles:o}){const[i,l]=K.useState(()=>typeof window<"u"?window.location.href:""),u=K.useRef(0),m=K.useCallback(()=>{if(tl()&&qs===null&&e&&!o){qs={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:f,innerHeight:h}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-u.current}px`,left:`${-f}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const g=h-window.innerHeight;g&&u.current>=h&&(document.body.style.top=`${-(u.current+g)}px`)}),300)}},[e]),d=K.useCallback(()=>{if(tl()&&qs!==null&&!o){const f=-parseInt(document.body.style.top,10),h=-parseInt(document.body.style.left,10);Object.assign(document.body.style,qs),window.requestAnimationFrame(()=>{if(a&&i!==window.location.href){l(window.location.href);return}window.scrollTo(h,f)}),qs=null}},[i]);return K.useEffect(()=>{function f(){u.current=window.scrollY}return f(),window.addEventListener("scroll",f),()=>{window.removeEventListener("scroll",f)}},[]),K.useEffect(()=>{if(t)return()=>{typeof document>"u"||document.querySelector("[data-vaul-drawer]")||d()}},[t,d]),K.useEffect(()=>{s||!n||(e?(!window.matchMedia("(display-mode: standalone)").matches&&m(),t||window.setTimeout(()=>{d()},500)):d())},[e,n,i,t,s,m,d]),{restorePositionSetting:d}}function Ry({open:e,onOpenChange:t,children:s,onDrag:n,onRelease:a,snapPoints:o,shouldScaleBackground:i=!1,setBackgroundColorOnScale:l=!0,closeThreshold:u=ky,scrollLockTimeout:m=Cy,dismissible:d=!0,handleOnly:f=!1,fadeFromIndex:h=o&&o.length-1,activeSnapPoint:g,setActiveSnapPoint:x,fixed:p,modal:v=!0,onClose:b,nested:S,noBodyStyles:w=!1,direction:y="bottom",defaultOpen:j=!1,disablePreventScroll:E=!0,snapToSequentialPoint:M=!1,preventScrollRestoration:N=!1,repositionInputs:A=!0,onAnimationEnd:L,container:O,autoFocus:D=!1}){var R,k;const[P=!1,F]=Uu({defaultProp:j,prop:e,onChange:W=>{t?.(W),!W&&!S&&ue(),setTimeout(()=>{L?.(W)},Te.DURATION*1e3),W&&!v&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),W||(document.body.style.pointerEvents="auto")}}),[C,T]=K.useState(!1),[I,q]=K.useState(!1),[se,G]=K.useState(!1),oe=K.useRef(null),ne=K.useRef(null),Z=K.useRef(null),pe=K.useRef(null),me=K.useRef(null),Q=K.useRef(!1),H=K.useRef(null),de=K.useRef(0),ee=K.useRef(!1),fe=K.useRef(!j),U=K.useRef(0),_=K.useRef(null),z=K.useRef(((R=_.current)==null?void 0:R.getBoundingClientRect().height)||0),ce=K.useRef(((k=_.current)==null?void 0:k.getBoundingClientRect().width)||0),be=K.useRef(0),Ke=K.useCallback(W=>{o&&W===Ne.length-1&&(ne.current=new Date)},[]),{activeSnapPoint:ge,activeSnapPointIndex:ie,setActiveSnapPoint:Ae,onRelease:we,snapPointsOffset:Ne,onDrag:ft,shouldFade:Y,getPercentageDragged:Ee}=Ny({snapPoints:o,activeSnapPointProp:g,setActiveSnapPointProp:x,drawerRef:_,fadeFromIndex:h,overlayRef:oe,onSnapPointChange:Ke,direction:y,container:O,snapToSequentialPoint:M});py({isDisabled:!P||I||!v||se||!C||!A||!E});const{restorePositionSetting:ue}=Ty({isOpen:P,modal:v,nested:S??!1,hasBeenOpened:C,preventScrollRestoration:N,noBodyStyles:w});function ke(){return(window.innerWidth-wa)/window.innerWidth}function et(W){var re,he;!d&&!o||_.current&&!_.current.contains(W.target)||(z.current=((re=_.current)==null?void 0:re.getBoundingClientRect().height)||0,ce.current=((he=_.current)==null?void 0:he.getBoundingClientRect().width)||0,q(!0),Z.current=new Date,Lu()&&window.addEventListener("touchend",()=>Q.current=!1,{once:!0}),W.target.setPointerCapture(W.pointerId),de.current=Fe(y)?W.pageY:W.pageX)}function ct(W,re){var he;let le=W;const ye=(he=window.getSelection())==null?void 0:he.toString(),Ce=_.current?Mn(_.current,y):null,xe=new Date;if(le.tagName==="SELECT"||le.hasAttribute("data-vaul-no-drag")||le.closest("[data-vaul-no-drag]"))return!1;if(y==="right"||y==="left")return!0;if(ne.current&&xe.getTime()-ne.current.getTime()<500)return!1;if(Ce!==null&&(y==="bottom"?Ce>0:Ce<0))return!0;if(ye&&ye.length>0)return!1;if(me.current&&xe.getTime()-me.current.getTime()<m&&Ce===0||re)return me.current=xe,!1;for(;le;){if(le.scrollHeight>le.clientHeight){if(le.scrollTop!==0)return me.current=new Date,!1;if(le.getAttribute("role")==="dialog")return!0}le=le.parentNode}return!0}function Ye(W){if(_.current&&I){const re=y==="bottom"||y==="right"?1:-1,he=(de.current-(Fe(y)?W.pageY:W.pageX))*re,le=he>0,ye=o&&!d&&!le;if(ye&&ie===0)return;const Ce=Math.abs(he),xe=document.querySelector("[data-vaul-drawer-wrapper]"),Ve=y==="bottom"||y==="top"?z.current:ce.current;let Pe=Ce/Ve;const Je=Ee(Ce,le);if(Je!==null&&(Pe=Je),ye&&Pe>=1||!Q.current&&!ct(W.target,le))return;if(_.current.classList.add(ea),Q.current=!0,ze(_.current,{transition:"none"}),ze(oe.current,{transition:"none"}),o&&ft({draggedDistance:he}),le&&!o){const Le=wy(he),st=Math.min(Le*-1,0)*re;ze(_.current,{transform:Fe(y)?`translate3d(0, ${st}px, 0)`:`translate3d(${st}px, 0, 0)`});return}const _e=1-Pe;if((Y||h&&ie===h-1)&&(n?.(W,Pe),ze(oe.current,{opacity:`${_e}`,transition:"none"},!0)),xe&&oe.current&&i){const Le=Math.min(ke()+Pe*(1-ke()),1),st=8-Pe*8,Qe=Math.max(0,14-Pe*14);ze(xe,{borderRadius:`${st}px`,transform:Fe(y)?`scale(${Le}) translate3d(0, ${Qe}px, 0)`:`scale(${Le}) translate3d(${Qe}px, 0, 0)`,transition:"none"},!0)}if(!o){const Le=Ce*re;ze(_.current,{transform:Fe(y)?`translate3d(0, ${Le}px, 0)`:`translate3d(${Le}px, 0, 0)`})}}}K.useEffect(()=>{window.requestAnimationFrame(()=>{fe.current=!0})},[]),K.useEffect(()=>{var W;function re(){if(!_.current||!A)return;const he=document.activeElement;if(ya(he)||ee.current){var le;const ye=((le=window.visualViewport)==null?void 0:le.height)||0,Ce=window.innerHeight;let xe=Ce-ye;const Ve=_.current.getBoundingClientRect().height||0,Pe=Ve>Ce*.8;be.current||(be.current=Ve);const Je=_.current.getBoundingClientRect().top;if(Math.abs(U.current-xe)>60&&(ee.current=!ee.current),o&&o.length>0&&Ne&&ie){const _e=Ne[ie]||0;xe+=_e}if(U.current=xe,Ve>ye||ee.current){const _e=_.current.getBoundingClientRect().height;let Le=_e;_e>ye&&(Le=ye-(Pe?Je:wa)),p?_.current.style.height=`${_e-Math.max(xe,0)}px`:_.current.style.height=`${Math.max(Le,ye-Je)}px`}else ly()||(_.current.style.height=`${be.current}px`);o&&o.length>0&&!ee.current?_.current.style.bottom="0px":_.current.style.bottom=`${Math.max(xe,0)}px`}}return(W=window.visualViewport)==null||W.addEventListener("resize",re),()=>{var he;return(he=window.visualViewport)==null?void 0:he.removeEventListener("resize",re)}},[ie,o,Ne]);function Ie(W){We(),b?.(),W||F(!1),setTimeout(()=>{o&&Ae(o[0])},Te.DURATION*1e3)}function De(){if(!_.current)return;const W=document.querySelector("[data-vaul-drawer-wrapper]"),re=Mn(_.current,y);ze(_.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${Te.DURATION}s cubic-bezier(${Te.EASE.join(",")})`}),ze(oe.current,{transition:`opacity ${Te.DURATION}s cubic-bezier(${Te.EASE.join(",")})`,opacity:"1"}),i&&re&&re>0&&P&&ze(W,{borderRadius:`${Bu}px`,overflow:"hidden",...Fe(y)?{transform:`scale(${ke()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${ke()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${Te.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Te.EASE.join(",")})`},!0)}function We(){!I||!_.current||(_.current.classList.remove(ea),Q.current=!1,q(!1),pe.current=new Date)}function Xe(W){if(!I||!_.current)return;_.current.classList.remove(ea),Q.current=!1,q(!1),pe.current=new Date;const re=Mn(_.current,y);if(!W||!ct(W.target,!1)||!re||Number.isNaN(re)||Z.current===null)return;const he=pe.current.getTime()-Z.current.getTime(),le=de.current-(Fe(y)?W.pageY:W.pageX),ye=Math.abs(le)/he;if(ye>.05&&(G(!0),setTimeout(()=>{G(!1)},200)),o){we({draggedDistance:le*(y==="bottom"||y==="right"?1:-1),closeDrawer:Ie,velocity:ye,dismissible:d}),a?.(W,!0);return}if(y==="bottom"||y==="right"?le>0:le<0){De(),a?.(W,!0);return}if(ye>zu){Ie(),a?.(W,!1);return}var Ce;const xe=Math.min((Ce=_.current.getBoundingClientRect().height)!=null?Ce:0,window.innerHeight);var Ve;const Pe=Math.min((Ve=_.current.getBoundingClientRect().width)!=null?Ve:0,window.innerWidth),Je=y==="left"||y==="right";if(Math.abs(re)>=(Je?Pe:xe)*u){Ie(),a?.(W,!1);return}a?.(W,!0),De()}K.useEffect(()=>(P&&(ze(document.documentElement,{scrollBehavior:"auto"}),ne.current=new Date),()=>{yy(document.documentElement,"scrollBehavior")}),[P]);function Ue(W){const re=W?(window.innerWidth-Jt)/window.innerWidth:1,he=W?-Jt:0;H.current&&window.clearTimeout(H.current),ze(_.current,{transition:`transform ${Te.DURATION}s cubic-bezier(${Te.EASE.join(",")})`,transform:Fe(y)?`scale(${re}) translate3d(0, ${he}px, 0)`:`scale(${re}) translate3d(${he}px, 0, 0)`}),!W&&_.current&&(H.current=setTimeout(()=>{const le=Mn(_.current,y);ze(_.current,{transition:"none",transform:Fe(y)?`translate3d(0, ${le}px, 0)`:`translate3d(${le}px, 0, 0)`})},500))}function tt(W,re){if(re<0)return;const he=(window.innerWidth-Jt)/window.innerWidth,le=he+re*(1-he),ye=-Jt+re*Jt;ze(_.current,{transform:Fe(y)?`scale(${le}) translate3d(0, ${ye}px, 0)`:`scale(${le}) translate3d(${ye}px, 0, 0)`,transition:"none"})}function Se(W,re){const he=Fe(y)?window.innerHeight:window.innerWidth,le=re?(he-Jt)/he:1,ye=re?-Jt:0;re&&ze(_.current,{transition:`transform ${Te.DURATION}s cubic-bezier(${Te.EASE.join(",")})`,transform:Fe(y)?`scale(${le}) translate3d(0, ${ye}px, 0)`:`scale(${le}) translate3d(${ye}px, 0, 0)`})}return K.useEffect(()=>{v||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[v]),K.createElement(Cu,{defaultOpen:j,onOpenChange:W=>{!d&&!W||(W?T(!0):Ie(!0),F(W))},open:P},K.createElement(Pu.Provider,{value:{activeSnapPoint:ge,snapPoints:o,setActiveSnapPoint:Ae,drawerRef:_,overlayRef:oe,onOpenChange:t,onPress:et,onRelease:Xe,onDrag:Ye,dismissible:d,shouldAnimate:fe,handleOnly:f,isOpen:P,isDragging:I,shouldFade:Y,closeDrawer:Ie,onNestedDrag:tt,onNestedOpenChange:Ue,onNestedRelease:Se,keyboardIsOpen:ee,modal:v,snapPointsOffset:Ne,activeSnapPointIndex:ie,direction:y,shouldScaleBackground:i,setBackgroundColorOnScale:l,noBodyStyles:w,container:O,autoFocus:D}},s))}const qu=K.forwardRef(function({...e},t){const{overlayRef:s,snapPoints:n,onRelease:a,shouldFade:o,isOpen:i,modal:l,shouldAnimate:u}=pn(),m=$u(t,s),d=n&&n.length>0;if(!l)return null;const f=K.useCallback(h=>a(h),[a]);return K.createElement(Iu,{onMouseUp:f,ref:m,"data-vaul-overlay":"","data-vaul-snap-points":i&&d?"true":"false","data-vaul-snap-points-overlay":i&&o?"true":"false","data-vaul-animate":u?.current?"true":"false",...e})});qu.displayName="Drawer.Overlay";const Hu=K.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:s,...n},a){const{drawerRef:o,onPress:i,onRelease:l,onDrag:u,keyboardIsOpen:m,snapPointsOffset:d,activeSnapPointIndex:f,modal:h,isOpen:g,direction:x,snapPoints:p,container:v,handleOnly:b,shouldAnimate:S,autoFocus:w}=pn(),[y,j]=K.useState(!1),E=$u(a,o),M=K.useRef(null),N=K.useRef(null),A=K.useRef(!1),L=p&&p.length>0;Iy();const O=(R,k,P=0)=>{if(A.current)return!0;const F=Math.abs(R.y),C=Math.abs(R.x),T=C>F,I=["bottom","right"].includes(k)?1:-1;if(k==="left"||k==="right"){if(!(R.x*I<0)&&C>=0&&C<=P)return T}else if(!(R.y*I<0)&&F>=0&&F<=P)return!T;return A.current=!0,!0};K.useEffect(()=>{L&&window.requestAnimationFrame(()=>{j(!0)})},[]);function D(R){M.current=null,A.current=!1,l(R)}return K.createElement(Tu,{"data-vaul-drawer-direction":x,"data-vaul-drawer":"","data-vaul-delayed-snap-points":y?"true":"false","data-vaul-snap-points":g&&L?"true":"false","data-vaul-custom-container":v?"true":"false","data-vaul-animate":S?.current?"true":"false",...n,ref:E,style:d&&d.length>0?{"--snap-point-height":`${d[f??0]}px`,...t}:t,onPointerDown:R=>{b||(n.onPointerDown==null||n.onPointerDown.call(n,R),M.current={x:R.pageX,y:R.pageY},i(R))},onOpenAutoFocus:R=>{s?.(R),w||R.preventDefault()},onPointerDownOutside:R=>{if(e?.(R),!h||R.defaultPrevented){R.preventDefault();return}m.current&&(m.current=!1)},onFocusOutside:R=>{if(!h){R.preventDefault();return}},onPointerMove:R=>{if(N.current=R,b||(n.onPointerMove==null||n.onPointerMove.call(n,R),!M.current))return;const k=R.pageY-M.current.y,P=R.pageX-M.current.x,F=R.pointerType==="touch"?10:2;O({x:P,y:k},x,F)?u(R):(Math.abs(P)>F||Math.abs(k)>F)&&(M.current=null)},onPointerUp:R=>{n.onPointerUp==null||n.onPointerUp.call(n,R),M.current=null,A.current=!1,l(R)},onPointerOut:R=>{n.onPointerOut==null||n.onPointerOut.call(n,R),D(N.current)},onContextMenu:R=>{n.onContextMenu==null||n.onContextMenu.call(n,R),N.current&&D(N.current)}})});Hu.displayName="Drawer.Content";const My=250,Ay=120,Wu=K.forwardRef(function({preventCycle:e=!1,children:t,...s},n){const{closeDrawer:a,isDragging:o,snapPoints:i,activeSnapPoint:l,setActiveSnapPoint:u,dismissible:m,handleOnly:d,isOpen:f,onPress:h,onDrag:g}=pn(),x=K.useRef(null),p=K.useRef(!1);function v(){if(p.current){w();return}window.setTimeout(()=>{b()},Ay)}function b(){if(o||e||p.current){w();return}if(w(),!i||i.length===0){m||a();return}if(l===i[i.length-1]&&m){a();return}const j=i.findIndex(M=>M===l);if(j===-1)return;const E=i[j+1];u(E)}function S(){x.current=window.setTimeout(()=>{p.current=!0},My)}function w(){x.current&&window.clearTimeout(x.current),p.current=!1}return K.createElement("div",{onClick:v,onPointerCancel:w,onPointerDown:y=>{d&&h(y),S()},onPointerMove:y=>{d&&g(y)},ref:n,"data-vaul-drawer-visible":f?"true":"false","data-vaul-handle":"","aria-hidden":"true",...s},K.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});Wu.displayName="Drawer.Handle";function Oy(e){const t=pn(),{container:s=t.container,...n}=e;return K.createElement(Eu,{container:s,...n})}const dt={Root:Ry,Content:Hu,Overlay:qu,Portal:Oy,Handle:Wu,Title:Au},Vu="inline-flex items-center justify-center transition-colors",Dy=$e(Vu,"min-h-11 min-w-11 rounded hover:bg-surface-raised"),Py=$e(Vu,"min-h-11 gap-1.5 px-3 rounded text-sm font-medium hover:bg-surface-raised"),jo=({accountId:e,currentMailboxId:t,onMove:s,disabled:n=!1,disabledHint:a,variant:o="icon-only",label:i})=>{const[l,u]=c.useState(!1),m=Wt(),d=c.useRef(null),f=i??"Move to folder",h=c.useId(),{t:g}=Zn("mail",{useSuspense:!1}),x=c.useCallback((D,R)=>g(D,{defaultValue:R}),[g]),{data:p,isLoading:v,isError:b,error:S,refetch:w}=ve({...it({path:{accountId:e}}),staleTime:1/0,enabled:l}),y=yo(e),{createFolder:j}=Gl(e),E=c.useMemo(()=>{const D=Ga(p?.items??[],y),R=on(y);return D.map(k=>({id:k.mailboxId,label:Es(k,R.get(k.mailboxId),x),searchValue:k.fullPath,isCurrent:k.mailboxId===t}))},[p?.items,y,t,x]),M=c.useCallback(D=>{u(!1),s(D)},[s]),N=c.useCallback(async(D,R)=>{const k=await j(D,R);return{id:k.id,label:k.label}},[j]);c.useEffect(()=>{if(!l||!m)return;const D=k=>{d.current&&!d.current.contains(k.target)&&u(!1)},R=k=>{k.key==="Escape"&&u(!1)};return document.addEventListener("mousedown",D),document.addEventListener("keydown",R),()=>{document.removeEventListener("mousedown",D),document.removeEventListener("keydown",R)}},[l,m]);const A=n||!!a,L=r.jsxs("button",{type:"button",onClick:D=>{D.stopPropagation(),!A&&u(R=>!R)},"aria-label":f,"aria-haspopup":m?"listbox":"dialog","aria-expanded":l,"aria-controls":l?h:void 0,title:a,className:o==="icon-only"?Dy:Py,children:[r.jsx(Ra,{className:o==="icon-only"?"size-5":"size-4"}),o==="compact"&&r.jsx("span",{className:"hidden sm:inline",children:"Move"})]}),O=v?r.jsx("div",{className:"px-3 py-5 text-sm text-fg-muted",children:"Loading folders…"}):b?r.jsx("div",{className:"p-3",children:r.jsx(Vt,{variant:"inline",title:"Couldn't load folders",error:S,onRetry:()=>w()})}):r.jsx(Ml,{mailboxes:E,onSelect:M,onCreateFolder:N,onCancel:()=>u(!1),autoFocus:!m,labels:{createLabel:D=>`Create "${D}"`,searchPlaceholder:g("move_picker_placeholder",{defaultValue:"Move to…"}),searchAriaLabel:g("move_picker_filter_label",{defaultValue:"Filter folders"}),optionLabel:D=>`Move to ${D}`,currentSuffix:"(current folder)",currentTag:"current",emptyMessage:D=>`No folders match "${D}"`}});return m?r.jsxs("div",{ref:d,className:"relative inline-block",children:[L,l&&r.jsx("div",{id:h,className:$e("absolute right-0 mt-1 z-50 w-72 max-h-96 flex flex-col","bg-surface border border-line rounded-md shadow-lg"),children:O})]}):r.jsxs(r.Fragment,{children:[L,r.jsx(dt.Root,{open:l,onOpenChange:u,children:r.jsxs(dt.Portal,{children:[r.jsx(dt.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(dt.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{maxHeight:"85dvh"},id:h,children:[r.jsx(dt.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-subtle/30"}),r.jsx(dt.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:"Move to folder"}),r.jsx("div",{className:"flex-1 overflow-hidden",children:O})]})]})})]})},Ly=({messageId:e,threadId:t,mailboxId:s,isRead:n,accountId:a,fromAddressId:o,isTrusted:i=!1,showRaw:l=!1,onToggleRaw:u})=>{const m=Re(),d=He(),{pushError:f}=lt(),{selectedMessageId:h}=Is({strict:!1}),{mutate:g,isPending:x}=Oe({...rr(),onMutate:async P=>{const F=P.body.isRead??!0,C=new Set(P.body.messageIds??[]),T=ls({path:{threadId:t}}),I=Ot([s]);await Promise.all([m.cancelQueries({queryKey:T}),dn(m,I)]);const q=m.getQueriesData({queryKey:T}).filter(G=>G[1]!==void 0).map(([G,oe])=>({queryKey:G,data:oe})),se=fn(m,I);return m.setQueriesData({queryKey:T},G=>G&&{...G,items:Hn(G.items,C,F)}),mn(m,I,G=>Hn(G,C,F)),{threadMessagesPrefix:T,listPrefixes:I,previousThreadMessages:q,previousThreadsList:se}},onError:(P,F,C)=>{if(C){for(const I of C.previousThreadMessages)m.setQueryData(I.queryKey,I.data);hn(m,C.previousThreadsList)}const T=F.body.isRead??!0;f({title:T?"Couldn't mark as read":"Couldn't mark as unread",detail:ht(P),error:P})},onSettled:(P,F,C,T)=>{T&&(m.invalidateQueries({queryKey:T.threadMessagesPrefix}),Dt(m,T.listPrefixes))}}),p=c.useCallback(P=>{h&&P.includes(h)&&d({to:"/mail/$mailboxId",params:{mailboxId:s},search:F=>({...F,selectedMessageId:void 0})})},[h,s,d]),{deleteMessages:v,isPending:b}=as({mailboxId:s,threadId:t,onAfterOptimisticRemove:p}),{moveMessages:S,isPending:w}=rs({mailboxId:s,threadId:t,accountId:a,onAfterOptimisticRemove:p}),{toggleTrusted:y,isPending:j,error:E,reset:M}=wo({messageId:e}),N=()=>{g({body:{messageIds:[e],isRead:!1}})},A=()=>{v([e])},L=()=>{o&&y(o,i)},O=x||b||w||j,D=O||!o,R=c.useCallback(P=>{S([e],P)},[S,e]),k=o?void 0:"Sender has no parseable address";return r.jsxs("div",{className:"flex flex-col items-end gap-1",children:[r.jsxs("div",{className:"flex items-center gap-1",children:[a&&r.jsx(jo,{accountId:a,currentMailboxId:s,onMove:R,disabled:O,label:"Move this message"}),r.jsxs(Zc,{trigger:r.jsx(cc,{className:"size-4"}),children:[r.jsxs(Ss,{onClick:L,disabled:D,children:[i?r.jsx(lr,{className:"size-4 text-positive"}):r.jsx(nn,{className:"size-4 opacity-0"}),r.jsx("span",{title:k,children:"Trusted sender"})]}),n&&r.jsxs(Ss,{onClick:N,disabled:O,children:[r.jsx(cr,{className:"size-4"}),"Mark as unread"]}),u&&r.jsxs(Ss,{onClick:u,children:[r.jsx(lc,{className:"size-4"}),l?"Show formatted":"Show raw email"]}),r.jsx(xa,{}),r.jsxs(Ss,{onClick:A,disabled:O,destructive:!0,children:[r.jsx(Rt,{className:"size-4"}),"Delete"]})]})]}),E&&r.jsx("div",{className:"w-64",children:r.jsx(Vt,{variant:"inline",title:"Couldn't update trust",error:E,onRetry:()=>{M(),L()}})})]})},Fy=()=>{const[e,t]=c.useState(()=>typeof document<"u"&&document.documentElement.classList.contains("dark"));return c.useEffect(()=>{const s=document.documentElement,n=new MutationObserver(()=>{t(s.classList.contains("dark"))});return n.observe(s,{attributes:!0,attributeFilter:["class"]}),()=>n.disconnect()},[]),e},$y=({blockedImageCount:e,canAlwaysTrust:t,isTrustPending:s,onLoadOnce:n,onAlwaysTrust:a})=>r.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-md bg-surface-sunken/50 px-3 py-2 text-sm",children:[r.jsxs("span",{className:"text-fg-muted",children:[e," image",e>1?"s":""," blocked for privacy"]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("button",{type:"button",onClick:n,className:"text-accent hover:underline",children:"Load once"}),t&&r.jsx("button",{type:"button",onClick:a,"aria-busy":s,className:"text-accent hover:underline aria-busy:opacity-50",children:s?"Trusting…":"Always trust"})]})]}),_y=(e,t)=>{switch(e){case"auth":return{title:"Your session expired",detail:"Sign in again to reload the message body. Other parts of the app may also stop responding until you do."};case"body-missing":return{title:"Message body is missing in storage",detail:"A sync failure may have left this message without its body bytes. Contact support, or run the reconcile script to refetch from the upstream IMAP server."};case"content-type-mismatch":return{title:"Couldn't load message body",detail:"The server returned an unexpected content type for this part. The message body has not been rendered to keep you safe."};case"spa-shell-leak":return{title:"Couldn't load message body",detail:"The server returned the app shell instead of the message body. This is an infrastructure bug — please report it."};case"not-ready":return{title:"Message body is still syncing",detail:"This message's body hasn't finished downloading from the mail server yet. It should appear shortly — reopen the message to try again."};default:return{title:"Couldn't load message body",detail:t}}},zy=e=>e instanceof Zt?e.reason:"generic",By=e=>e instanceof Error?e.message:typeof e=="string"?e:"An unexpected error occurred while loading the message body.",Ky=({error:e,onRetry:t})=>{const s=zy(e),n=By(e),{title:a,detail:o}=_y(s,n),[i,l]=c.useState(!1),{Account:u}=$a();return i?null:r.jsxs("div",{role:"alert","data-testid":"message-body-error-banner","data-reason":s,className:"flex items-start gap-2 rounded-md border border-danger/40 bg-danger-soft px-3 py-2 text-sm",children:[r.jsx(os,{className:"size-4 shrink-0 text-danger mt-0.5","aria-hidden":"true"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"font-medium text-danger",children:a}),r.jsx("p",{className:"text-fg-muted mt-1 break-words",children:o})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[s==="auth"&&r.jsx(u,{children:({signOut:m})=>r.jsx("button",{type:"button",onClick:()=>m(),className:"text-sm font-medium text-accent hover:underline",children:"Sign in again"})}),t&&r.jsx("button",{type:"button",onClick:t,className:"text-sm font-medium text-accent hover:underline",children:"Retry"}),r.jsx("button",{type:"button",onClick:()=>l(!0),"aria-label":"Dismiss message body error",className:"rounded-md p-1 text-fg-muted hover:bg-surface-raised hover:text-fg transition-colors",children:r.jsx(St,{className:"size-4","aria-hidden":"true"})})]})]})},Uy=()=>r.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading message body",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"})]}),al=()=>r.jsx("p",{className:"text-fg-muted text-sm italic",children:"This message has no body content."}),Qu=({bodyParts:e,html:t,text:s,isTrusted:n=!1,messageId:a,fromAddressId:o,category:i,className:l})=>{const[u,m]=c.useState(!1),d=n||u,f=Fy(),{toggleTrusted:h,isPending:g}=wo({messageId:a??""}),x=!!e&&e.length>0,{picked:p,data:v,isLoading:b,isError:S,error:w,refetch:y}=du({messageId:a,bodyParts:e,enabled:x}),j=c.useMemo(()=>ip(e??[]),[e]),E=x&&v?.kind==="html"?v.body:t,M=x&&v?.kind==="text"?v.body:s;if(x){if(b)return r.jsx("div",{className:$e("message-body",l),children:r.jsx(Uy,{})});if(S)return r.jsx("div",{className:$e("message-body",l),children:r.jsx(Ky,{error:w,onRetry:()=>y()})});if(!p)return r.jsx("div",{className:$e("message-body",l),children:r.jsx(al,{})})}else if(!t&&!s)return r.jsx("div",{className:$e("message-body",l),children:r.jsx(al,{})});const N=!!(o&&a),A=()=>{!o||g||(m(!0),h(o,!1))};return r.jsx(jc,{className:l,html:E,text:M,isDark:f,category:i,allowImages:d,resolveCid:j,renderBlockedNotice:L=>r.jsx($y,{blockedImageCount:L,canAlwaysTrust:N,isTrustPending:g,onLoadOnce:()=>m(!0),onAlwaysTrust:A})})},qy=({messageId:e,threadId:t,mailboxId:s,accountId:n,isRead:a,isStarred:o,onToggleStar:i,fromAddressId:l,isTrusted:u,showRaw:m,onToggleRaw:d,onReply:f,onReplyAll:h,onForward:g})=>{const x=Re(),{deleteMessages:p}=as({mailboxId:s,threadId:t}),{moveMessages:v}=rs({mailboxId:s,threadId:t,accountId:n}),{toggleTrusted:b}=wo({messageId:e}),{mutate:S}=Oe({...rr(),onSettled:()=>{x.invalidateQueries({queryKey:ls({path:{threadId:t}})}),Dt(x,Ot([s]))}}),w=c.useCallback(M=>{v([e],M)},[v,e]),y=c.useCallback(()=>{p([e])},[p,e]),j=c.useCallback(()=>{S({body:{messageIds:[e],isRead:!a}})},[S,e,a]),E=[];return l&&E.push({key:"trusted",label:u?"Trusted sender":"Mark sender trusted",icon:u?r.jsx(lr,{className:"size-4 text-positive"}):r.jsx(nn,{className:"size-4"}),onSelect:()=>b(l,u)}),d&&E.push({key:"raw",label:m?"Show formatted":"Show raw email",icon:r.jsx(lc,{className:"size-4"}),onSelect:d}),r.jsx(Cc,{hasThread:!0,onReply:f,onReplyAll:h,onForward:g,isStarred:o,onToggleStar:i,onDelete:y,isRead:a,onToggleRead:j,overflowItems:E,moveSlot:n?r.jsx(jo,{accountId:n,currentMailboxId:s,onMove:w,label:"Move this message"}):void 0})},Hy=()=>r.jsxs("div",{className:"animate-pulse space-y-2",role:"status","aria-label":"Loading raw email",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-11/12"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-5/6"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"})]}),Wy=({messageId:e,enabled:t=!0})=>{const{data:s,isLoading:n,isError:a,error:o,refetch:i}=ve({...Uf({path:{messageId:e}}),enabled:t});if(n)return r.jsx("div",{className:"message-body",children:r.jsx(Hy,{})});if(a)return r.jsx("div",{className:"message-body",children:r.jsx(Vt,{variant:"inline",title:"Couldn't load the raw email",error:o,onRetry:()=>i()})});const l=s?.raw??"";return l===""?r.jsx("div",{className:"message-body",children:r.jsx("p",{className:"text-fg-muted text-sm italic",children:"No raw source available for this message."})}):r.jsx("div",{className:"message-body",children:r.jsx("pre",{className:"email-text whitespace-pre-wrap break-words text-sm leading-relaxed bg-surface-sunken rounded-md p-3 max-h-[32rem] overflow-auto",children:l})})},Vy=()=>r.jsx(lr,{className:"inline-block size-4 ml-1 -mt-0.5 text-positive align-middle","aria-label":"Trusted sender","data-testid":"trusted-sender-badge"}),Gu=(e,t)=>({id:e.messageId,fromName:e.fromName??e.fromEmail??"?",fromEmail:e.fromEmail??"",toLabel:"",dateLabel:t,snippet:e.snippet||"",bodyHtml:""}),Yu=({isStarred:e,onToggleStar:t,isStarPending:s,hoverReveal:n})=>r.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),t()},disabled:s,"aria-label":e?"Remove star":"Add star",className:$e("shrink-0 p-0.5 rounded transition-colors",e?"text-warning":$e("text-fg-subtle hover:text-warning",n&&"opacity-0 group-hover:opacity-100 focus:opacity-100"),s&&"opacity-50"),children:r.jsx(qt,{className:$e("size-3.5",e&&"fill-current")})}),Qy=({threadMessage:e,isFocused:t,onToggle:s,onToggleStar:n,isStarPending:a})=>{const o=Vl(e.sentDate,"datetime"),i=Gu(e,o);return r.jsx(Nc,{message:i,onClick:s,isFocused:t,isUnread:!e.isRead,trailing:r.jsxs(r.Fragment,{children:[e.hasAttachment&&r.jsx(ur,{className:"size-3 shrink-0 text-fg-subtle"}),r.jsx(Yu,{isStarred:e.hasStars,onToggleStar:n,isStarPending:a,hoverReveal:!0}),r.jsx("span",{"data-testid":"message-date",className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:o})]})})},Gy=({threadMessage:e,messageData:t,isLoading:s,isError:n,error:a,onRetry:o,isFocused:i,onToggle:l,onToggleStar:u,isStarPending:m,accountId:d,showRaw:f,onToggleRaw:h,mobile:g,onReply:x,onReplyAll:p,onForward:v})=>{const b=Vl(e.sentDate,"long"),S=!e.isRead,w=t?.envelope.from[0]?.flags?.trusted?.value===!0,y=t?.envelope.from[0]?.addressId,j=Gu(e,b),E=e.autoMoved?r.jsx(Qv,{accountId:d,messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,autoMoved:e.autoMoved}):null;return r.jsx(Ec,{message:j,isFocused:g?!1:i,onHeaderClick:l,senderBadge:w?r.jsx(Vy,{}):void 0,trailing:r.jsx("span",{"data-testid":"message-date",className:"text-2xs text-fg-subtle",children:b}),to:t?r.jsx(Oh,{label:"To",addresses:t.envelope.to}):null,indicators:E||!g?r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-0.5",children:[E,!g&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[r.jsx(Yu,{isStarred:e.hasStars,onToggleStar:u,isStarPending:m}),e.hasAttachment&&r.jsx("span",{className:"text-fg-subtle p-0.5",children:r.jsx(ur,{className:"size-3.5"})})]}),S&&r.jsx("span",{className:"size-1.5 rounded-full bg-accent","aria-label":"Unread"})]})]}):void 0,actionMenu:g?void 0:r.jsx(Ly,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,isRead:e.isRead,accountId:d,fromAddressId:y,isTrusted:w,showRaw:f,onToggleRaw:h}),actionBar:g?r.jsx(qy,{messageId:e.messageId,threadId:e.threadId,mailboxId:e.mailboxId,accountId:d,isRead:e.isRead,isStarred:e.hasStars,onToggleStar:u,fromAddressId:y,isTrusted:w,showRaw:f,onToggleRaw:h,onReply:x,onReplyAll:p,onForward:v}):void 0,body:s?r.jsxs("div",{className:"mt-3 animate-pulse space-y-2",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-full"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-3/4"}),r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-1/2"})]}):n&&qf(a)?r.jsx("div",{className:"mt-3",children:r.jsx(xu,{message:"This message has been deleted"})}):n?r.jsx("div",{className:"mt-3",children:r.jsx(Vt,{variant:"inline",title:"Couldn't load this message",error:a,onRetry:o})}):f?r.jsx("div",{className:"mt-3",children:r.jsx(Wy,{messageId:e.messageId})}):r.jsx("div",{className:"mt-3",children:r.jsx(Qu,{bodyParts:t?.bodyParts,messageId:e.messageId,fromAddressId:t?.envelope.from[0]?.addressId,isTrusted:w,category:wr(e.category)})})})},Yy=({threadMessage:e,isExpanded:t,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,mobile:l,onReply:u,onReplyAll:m,onForward:d})=>{const[f,h]=c.useState(!1),{data:g,isLoading:x,isError:p,error:v,refetch:b}=ve({...ar({path:{messageId:e.messageId}}),enabled:t,meta:{softError:!0}});return t?r.jsx(Gy,{threadMessage:e,messageData:g,isLoading:x,isError:p,error:v,onRetry:()=>b(),isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o,accountId:i,showRaw:f,onToggleRaw:()=>h(S=>!S),mobile:l,onReply:u,onReplyAll:m,onForward:d}):r.jsx(Qy,{threadMessage:e,isFocused:s,onToggle:n,onToggleStar:a,isStarPending:o})},Xy=()=>r.jsxs("div",{className:"animate-pulse p-4",children:[r.jsx("div",{className:"h-6 bg-surface-sunken rounded w-3/4 mb-5"}),r.jsx("div",{className:"space-y-4",children:Array.from({length:2}).map((e,t)=>r.jsxs("div",{className:"flex gap-3 py-3",children:[r.jsx("div",{className:"size-10 bg-surface-sunken rounded-full shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("div",{className:"h-4 bg-surface-sunken rounded w-32 mb-2"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-48"})]})]},t))})]});function ol({authenticity:e,onOpenIntelligence:t}){return e.dkimMismatch?r.jsxs("div",{className:"flex items-start gap-2 rounded-none border-b border-danger/20 bg-danger-soft px-5 py-2.5 text-sm",children:[r.jsx(Ds,{className:"mt-0.5 size-4 shrink-0 text-danger"}),r.jsxs("p",{className:"flex-1 leading-snug text-fg",children:["This message claims to be from"," ",r.jsx("span",{className:"font-semibold",children:e.fromDomain})," but was sent",e.dkimDomain?` via ${e.dkimDomain}`:" from a different domain","."]}),t&&r.jsx("button",{type:"button",onClick:t,className:"shrink-0 text-2xs font-medium text-danger hover:underline",children:"Why?"})]}):null}const $s=({threadId:e,mailboxId:t,subject:s,selectedMessageId:n,authenticity:a,onOpenIntelligence:o,onBack:i,composeRequest:l,onComposeClose:u,onSwipeNext:m,onSwipePrevious:d,mobileIntelligenceOpen:f})=>{const h=Wt(),{handlers:g}=$v({onSwipeLeft:m,onSwipeRight:d}),{accountId:x}=go(t),{data:p,isLoading:v,isError:b,error:S,refetch:w}=ve({...Hf({path:{threadId:e}})}),y=c.useMemo(()=>p?.items??[],[p?.items]),j=y[y.length-1],E=c.useRef(new Map),[M,N]=c.useState(new Set),[A,L]=c.useState(null),[O,D]=c.useState(0);c.useEffect(()=>{if(y.length>0&&e!==A){L(e);const z=new Set([y[y.length-1].threadMessageId]);if(n){const ce=y.find(be=>be.messageId===n);ce&&z.add(ce.threadMessageId)}N(z),D(y.length-1)}},[e,y,A,n]);const R=c.useCallback(z=>{N(ce=>{const be=new Set(ce);return be.has(z)?be.delete(z):be.add(z),be})},[]),k=c.useCallback(z=>{const ce=y[z];if(!ce)return;E.current.get(ce.threadMessageId)?.scrollIntoView({behavior:"smooth",block:"nearest"})},[y]),P=c.useCallback(()=>{if(y.length===0)return;const z=Math.min(O+1,y.length-1);D(z),k(z)},[y.length,O,k]),F=c.useCallback(()=>{if(y.length===0)return;const z=Math.max(O-1,0);D(z),k(z)},[y.length,O,k]),C=c.useCallback(()=>{const z=y[O];z&&R(z.threadMessageId)},[y,O,R]),{data:T}=ve({...Mt(),staleTime:1/0}),I=T?.accounts?.[0],q=!!I?.smtpHost;Dv({messages:y,expandedIds:M,threadId:e,mailboxId:t,accountId:I?.accountId});const{toggleStar:se,isPending:G,pendingMessageId:oe}=xo({threadId:e,mailboxId:t,messages:y}),[ne,Z]=c.useState(null);c.useEffect(()=>{l&&l!=="new"&&(Z(l),u?.())},[l,u]);const{data:pe}=ve({...ar({path:{messageId:j?.messageId??""}}),enabled:!!j&&ne!==null}),me=c.useCallback(()=>{Z("reply")},[]),Q=c.useCallback(()=>{Z("reply_all")},[]),H=c.useCallback(()=>{Z("forward")},[]),de=c.useCallback(()=>{Z(null),u?.()},[u]);if(po({enabled:!v&&y.length>0&&ne===null,bindings:[{key:"j",handler:P,preventDefault:!0},{key:"ArrowDown",handler:P,preventDefault:!0},{key:"k",handler:F,preventDefault:!0},{key:"ArrowUp",handler:F,preventDefault:!0},{key:"Enter",handler:C,preventDefault:!0},{key:"o",handler:C,preventDefault:!0},...q?[{key:"r",handler:me,preventDefault:!0},{key:"R",handler:Q,noModifiers:!1,preventDefault:!0},{key:"f",handler:H,preventDefault:!0}]:[]]}),v)return r.jsx(Xy,{});if(b)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(Vt,{title:"Couldn't load this conversation",error:S,onRetry:()=>w()})});if(y.length===0)return r.jsx("div",{className:"flex h-full items-center justify-center",children:r.jsx(xu,{message:"No messages in this thread"})});const ee=s||y[0]?.subject||"(No subject)",fe=y.length,U=z=>r.jsx("div",{children:y.map((ce,be)=>r.jsx("div",{ref:Ke=>{Ke&&E.current.set(ce.threadMessageId,Ke)},children:r.jsx(Yy,{threadMessage:ce,isExpanded:M.has(ce.threadMessageId),isFocused:be===O,onToggle:()=>R(ce.threadMessageId),onToggleStar:()=>se(ce.messageId,ce.hasStars),isStarPending:G&&oe===ce.messageId,accountId:x,mobile:z,onReply:z&&q?me:void 0,onReplyAll:z&&q?Q:void 0,onForward:z&&q?H:void 0})},ce.threadMessageId))}),_=r.jsxs("header",{className:"border-b border-line px-5 pt-5 pb-3",children:[r.jsx("h1",{className:"max-w-2xl text-lg font-semibold leading-snug text-fg",children:ee}),r.jsxs("p",{className:"mt-1 text-2xs text-fg-subtle",children:[fe," ",fe===1?"message":"messages"]})]});return h?r.jsxs("article",{className:"h-full flex flex-col",children:[_,a?.dkimMismatch&&r.jsx(ol,{authenticity:a,onOpenIntelligence:o}),r.jsx("div",{className:"flex-1 overflow-auto",children:U(!1)}),ne!==null&&r.jsx(Xi,{mode:ne,account:I,sourceMessage:pe,onClose:de})]}):r.jsxs(Ap,{thread:{subject:ee,messages:[]},onBack:i??(()=>{}),intelligenceOpen:f,onToggleIntelligence:o,touchHandlers:g,children:[a?.dkimMismatch&&r.jsx(ol,{authenticity:a,onOpenIntelligence:o}),U(!0),ne!==null&&r.jsx(Xi,{mode:ne,account:I,sourceMessage:pe,onClose:de})]})},Jy=new Set(["discovering_mailboxes","syncing_inbox","syncing_others"]);function Xu(e){return!!e&&Jy.has(e)}const Ju=3e3,Zy=Ju*2,il={syncing:!1,resolved:!1,synced:0,total:0};function e0(e,t){const s=e.join(","),[n,a]=c.useState(!1),[o,i]=c.useState(!1);c.useEffect(()=>{a(!1),i(!1)},[s,t]),c.useEffect(()=>{if(!t)return;const x=setTimeout(()=>i(!0),Zy);return()=>clearTimeout(x)},[s,t]);const l=gt({queries:e.map(x=>({...Wf({path:{accountId:x}}),enabled:t&&!n,refetchInterval:Ju,meta:{softError:!0}}))}),u=l.every(x=>x.isSuccess||x.isError),m=l.length===0||u||o;let d=!1,f=0,h=0;for(const x of l)if(Xu(x.data?.syncPhase)){d=!0;for(const p of x.data?.mailboxes??[])f+=p.messagesSynced,h+=p.messagesTotal}const g=t&&m&&!d;return c.useEffect(()=>{g&&a(!0)},[g]),!t||!m?il:{syncing:d,resolved:!0,synced:f,total:h}}function us(){const{mailboxNameIndex:e,accountNameIndex:t}=Me();return{...It({select:n=>ou(n.matches)})?{}:{mailboxesByName:e},accountsByName:t}}const No=e=>e.trim().toLocaleLowerCase(),Zu={personal:"Personal",uncategorized:"Unclassified",transactional:"Transactional",newsletter:"Newsletter",marketing:"Marketing",social:"Social",automated:"Automated"},t0=Object.values(ot).map(e=>({value:e,label:Zu[e]})),s0={unclassified:"uncategorized"},Sa=[{name:"from",label:"Sender",values:"contact"},{name:"subject",label:"Subject",values:"text"},{name:"category",label:"Category",values:"fixed",options:t0},{name:"is",label:"State",values:"fixed",options:[{value:"unread",label:"Unread"},{value:"read",label:"Read"},{value:"starred",label:"Starred"}]},{name:"has",label:"Contents",values:"fixed",options:[{value:"attachment",label:"Has attachment"}]},{name:"in",label:"Folder",values:"mailbox"},{name:"account",label:"Account",values:"account"},{name:"after",label:"Sent on or after",values:"date"},{name:"before",label:"Sent before",values:"date"}],n0=new Map(Sa.map(e=>[e.name,e])),ed=e=>n0.get(e.toLowerCase()),r0=/^\d{4}-\d{2}-\d{2}$/,a0=e=>/[\s"]/.test(e),o0=e=>a0(e)?`"${e.replace(/"/g,"")}"`:e,td=(e,t)=>`${e}:${o0(t)}`,i0=e=>{if(!e.startsWith('"'))return e;const t=e.slice(1);return t.endsWith('"')?t.slice(0,-1):t};function Eo(e){const t=[];let s=-1,n=!1;for(let a=0;a<e.length;a++){const o=e[a];if(o==='"'){n=!n,s<0&&(s=a);continue}if(!n&&/\s/.test(o)){s>=0&&t.push({raw:e.slice(s,a),start:s,end:a}),s=-1;continue}s<0&&(s=a)}return s>=0&&t.push({raw:e.slice(s),start:s,end:e.length}),t}function sd(e){const t=e.indexOf(":");if(t<=0)return;const s=e.slice(t+1);return{name:e.slice(0,t).toLowerCase(),value:i0(s),rawValue:s}}function l0(e,t,s){if(!r0.test(s))return;const n=Date.parse(`${s}T00:00:00Z`);if(!Number.isNaN(n))return{type:e,raw:t,value:s,epochSeconds:Math.floor(n/1e3)}}function c0(e){const t=e.toLowerCase(),s=s0[t];return s||Object.values(ot).find(a=>a===t)}function u0(e,t){switch(t.toLowerCase()){case"unread":return{type:"isUnread",raw:e};case"read":return{type:"isRead",raw:e};case"starred":case"flagged":return{type:"isStarred",raw:e};default:return}}function d0(e,t){const s=sd(e);if(!s||s.value.length===0)return;const{name:n,value:a}=s;switch(n){case"from":return{type:"from",raw:e,value:a};case"subject":return{type:"subject",raw:e,value:a};case"category":{const o=c0(a);return o?{type:"category",raw:e,value:a,category:o}:void 0}case"is":return u0(e,a);case"has":return a.toLowerCase()==="attachment"?{type:"hasAttachment",raw:e}:void 0;case"before":case"after":return l0(n,e,a);case"in":{const o=t.mailboxesByName?.get(a.toLowerCase());return o?{type:"in",raw:e,value:a,mailboxId:o}:void 0}case"account":{const o=t.accountsByName?.get(a.toLowerCase());return o?{type:"account",raw:e,value:a,accountId:o}:void 0}default:return}}function _s(e,t={}){const s=[],n=[];for(const a of Eo(e)){const o=d0(a.raw,t);o?s.push(o):n.push(a.raw)}return{freeText:n.join(" "),tokens:s}}function f0(e,t){return Eo(e).filter(s=>s.raw!==t.raw).map(s=>s.raw).join(" ")}function nd(e){switch(e.type){case"from":return`From: ${e.value}`;case"subject":return`Subject: ${e.value}`;case"category":return`Category: ${Zu[e.category]}`;case"hasAttachment":return"Has attachment";case"isUnread":return"Unread";case"isRead":return"Read";case"isStarred":return"Starred";case"before":return`Before ${e.value}`;case"after":return`After ${e.value}`;case"in":return`In: ${e.value}`;case"account":return`Account: ${e.value}`}}const m0=20,h0=new Set(Object.values(ot)),p0=e=>e!==void 0&&h0.has(e)?e:void 0,g0=e=>{if(e.some(t=>t.type==="isUnread"))return!1;if(e.some(t=>t.type==="isRead"))return!0};function rd({mailboxId:e,filterCategory:t}={}){const{searchQuery:s}=Me(),n=us(),a=It({select:y=>y.matches}),o=No(s),{freeText:i,tokens:l}=_s(o,n),u=i.length>0,m=l.find(y=>y.type==="category"),d=p0(t)??m?.category,f=l.some(y=>y.type==="hasAttachment")?!0:void 0,h=l.some(y=>y.type==="isStarred")?!0:void 0,g=g0(l),x=l.find(y=>y.type==="after"),p=l.find(y=>y.type==="before"),v=l.find(y=>y.type==="in"),b=Ub({matches:a,callerMailboxId:e,inTokenMailboxId:v?.mailboxId}),{data:S,isLoading:w}=ve({...Bl({query:{query:i,mailboxId:b,limit:m0,...d!==void 0?{category:d}:{},...f!==void 0?{hasAttachment:f}:{},...h!==void 0?{hasStars:h}:{},...g!==void 0?{isRead:g}:{},...x?{sentDateFrom:x.epochSeconds}:{},...p?{sentDateTo:p.epochSeconds}:{}}}),enabled:u,staleTime:6e4});return{hits:S?.items??[],isLoading:u&&w}}const x0=(e,t)=>e.createdAt!==t.createdAt?e.createdAt-t.createdAt:e.accountId.localeCompare(t.accountId),b0=e=>[...e].sort(x0);function Vn(e){const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountId,mailboxId:e.mailboxId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:pt(e.sentDate),sentDate:e.sentDate,isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:wr(e.category),suspicious:t}}function ll(e){return e.filter(t=>t.muted!==!0)}function v0(e,t){const s=new Set,n=[];for(const a of[...e,...t])s.has(a.id)||(s.add(a.id),n.push(a));return n.sort((a,o)=>(o.sentDate??0)-(a.sentDate??0))}const cl=[{id:"personal",label:"Personal",category:ot.personal},{id:"transactional",label:"Transactional",category:ot.transactional},{id:"newsletter",label:"Newsletter",category:ot.newsletter},{id:"marketing",label:"Marketing",category:ot.marketing},{id:"social",label:"Social",category:ot.social},{id:"automated",label:"Automated",category:ot.automated},{id:"uncategorized",label:"Unclassified",category:ot.uncategorized}];function y0(e){const t=new Map(cl.map(n=>[n.category,[]]));for(const n of e){const a=n.category??ot.uncategorized;(t.get(a)??t.get(ot.uncategorized))?.push(n)}const s=[];for(const n of cl){const a=t.get(n.category);a&&a.length>0&&s.push({id:n.id,label:n.label,threads:a})}return s}function ad(e,t){return e.fromName.toLowerCase().includes(t)||e.fromEmail.toLowerCase().includes(t)||e.subject.toLowerCase().includes(t)||e.snippet.toLowerCase().includes(t)}function Io(e,t){return t.every(s=>{switch(s.type){case"from":{const n=s.value.toLowerCase();return e.fromEmail.toLowerCase().includes(n)||e.fromName.toLowerCase().includes(n)}case"subject":return e.subject.toLowerCase().includes(s.value.toLowerCase());case"category":return(e.category??"uncategorized")===s.category;case"hasAttachment":return e.hasAttachment===!0;case"isUnread":return!e.isRead;case"isRead":return e.isRead===!0;case"isStarred":return e.starred===!0;case"after":return e.sentDate!=null&&e.sentDate>=s.epochSeconds*1e3;case"before":return e.sentDate!=null&&e.sentDate<s.epochSeconds*1e3;case"in":return e.mailboxId===s.mailboxId;case"account":return e.accountId===s.accountId;default:return!1}})}const w0={sender:"sender",recipient:"recipient",subject:"subject",attachment:"attachment",body:"body",entities:"entities"};function S0(e){return w0[e]??e}function k0(e,t){const{folder:s}=qa(t,[e.mailboxId]);return{id:e.messageId,sender:e.fromName??e.fromEmail??"Unknown",...e.fromEmail?{senderEmail:e.fromEmail}:{},subject:e.subject??"(No subject)",snippet:e.snippet??"",date:pt(e.sentDate),unread:!e.isRead,flagged:e.hasStars===!0,threadId:e.threadId,mailboxId:e.mailboxId,...s?{folder:s}:{}}}function od(e,t){const{folder:s}=qa(t,e.mailboxId?[e.mailboxId]:[]);return{id:e.id,sender:e.fromName,...e.fromEmail?{senderEmail:e.fromEmail}:{},subject:e.subject,snippet:e.snippet,date:e.timeLabel,unread:!e.isRead,flagged:e.starred===!0,...e.mailboxId?{mailboxId:e.mailboxId}:{},...s?{folder:s}:{}}}function C0(e,t){const{mailboxId:s,folder:n}=qa(t,e.mailboxIds);return{id:e.messageId,sender:e.fromName??"Unknown",subject:e.subject??"(No subject)",snippet:"",date:e.sentDate!=null?pt(e.sentDate*1e3):"",threadId:e.threadId,matchedChunkLabel:S0(e.matchedChunkType),score:e.score,...s?{mailboxId:s}:{},...n?{folder:n}:{}}}function id(e,t,s){const n=new Set(t),a=[];for(const o of[...e].sort((i,l)=>l.score-i.score))n.has(o.threadId)||(n.add(o.threadId),a.push(C0(o,s)));return a}const j0=e=>{const{mailboxId:t,messages:s}=e,n=Re(),{pushError:a}=lt(),{mutateAsync:o,isPending:i}=Oe({...Vf(),onError:(u,m)=>{a({title:m.body.action==="Remove"?"Couldn't remove label":"Couldn't apply label",detail:ht(u),error:u})},onSettled:(u,m,d)=>{Dt(n,Ot(vr(d.body.messageIds??[],s??[],t)))}});return{applyLabel:c.useCallback((u,m,d)=>{u.length!==0&&br(u,f=>o({body:{messageIds:f,labelId:m,action:d}}))},[o]),isPending:i}};function ld({accountId:e,mailboxId:t,messageIds:s}){const{labels:n}=Ya(e),{applyLabel:a}=j0({mailboxId:t}),o=c.useMemo(()=>n.map(i=>({key:i.labelId,label:i.name,icon:r.jsx("span",{className:`size-2.5 rounded-full ${Qf(i.color)?Ko[i.color]:Ko.Default}`}),onSelect:()=>a(s,i.labelId,"Apply")})),[n,s,a]);return o.length===0?null:r.jsx(ro,{triggerLabel:"Apply label to selected messages",triggerIcon:r.jsx(Gf,{className:"size-4 text-fg-subtle"}),triggerText:"Apply label",items:o,align:"start",nested:!0,touch:!1,triggerClassName:"min-h-11 w-full justify-start gap-3 px-4 py-2.5 text-sm font-normal text-fg"})}const N0=768,E0=1024,cd=e=>e!=="desktop",Cr=()=>{const e=qo(`(min-width: ${N0}px)`);return qo(`(min-width: ${E0}px)`)?"desktop":e?"tablet":"phone"},ud=8;function To(e,t){const s=Math.max(0,Math.min(t,e.length)),n=Eo(e).find(o=>s>=o.start&&s<=o.end);if(!n)return{start:s,end:s,raw:""};const a=sd(n.raw);return a?{start:n.start,end:n.end,raw:n.raw,name:a.name,value:a.value}:{start:n.start,end:n.end,raw:n.raw}}function I0(e,t){const s=To(e,t);if(s.name===void 0)return{kind:"token",query:s.raw};const n=ed(s.name);if(n)return{kind:"value",token:n.name,source:n.values,query:s.value??""}}const T0={mailbox:"mailboxes",account:"accounts",contact:"contacts"},R0=(e,t)=>{if(e.values==="fixed")return e.options??[];const s=T0[e.values];return s?t[s]??[]:[]},M0=(e,t)=>{if(t==="")return 1;const s=e.toLowerCase();return s.startsWith(t)?0:s.includes(t)?1:-1},ka=(e,...t)=>{let s=-1;for(const n of t){if(n===void 0)continue;const a=M0(n,e);a<0||(s<0||a<s)&&(s=a)}return s},dd=e=>{const t=new Set;return e.filter(s=>s.rank>=0).sort((s,n)=>s.rank-n.rank).filter(s=>{const n=s.suggestion.value.toLowerCase();return t.has(n)?!1:(t.add(n),!0)}).slice(0,ud).map(s=>s.suggestion)},ul=e=>({value:`${e.name}:`,label:`${e.name}:`,hint:e.label});function A0(e){const t=e.trim().toLowerCase();if(t==="")return Sa.map(ul);const s=[];for(const n of Sa)if(s.push({rank:ka(t,`${n.name}:`,n.label),suggestion:ul(n)}),n.values==="fixed")for(const a of n.options??[]){const o=td(n.name,a.value);s.push({rank:ka(t,o,a.label),suggestion:{value:o,label:a.label??o,hint:o}})}return dd(s)}function O0(e,t,s){const n=t.trim().toLowerCase(),a=R0(e,s).map(o=>({rank:ka(n,o.value,o.label),suggestion:{value:td(e.name,o.value),label:o.label??o.value,...o.hint?{hint:o.hint}:{}}}));return dd(a)}function D0(e,t,s={}){const n=To(e,t);if(n.name===void 0)return A0(n.raw);const a=ed(n.name);return a?O0(a,n.value??"",s):[]}function P0(e,t,s){const n=To(e,t),a=!s.value.endsWith(":"),o=/\s/.test(e.slice(n.end,n.end+1)),i=a&&!o?`${s.value} `:s.value;return{query:e.slice(0,n.start)+i+e.slice(n.end),cursor:n.start+i.length+(a&&o?1:0)}}const L0=e=>({value:e.normalizedEmail,...e.displayName?{label:e.displayName,hint:e.normalizedEmail}:{}});function F0(e){const t=new Map;for(const s of e){const n=s.email.toLowerCase(),a=n.split("@")[0];a&&!t.has(a)&&t.set(a,s.accountId),t.has(n)||t.set(n,s.accountId)}return t}function $0(e){const t=new Map;for(const s of e)for(const n of s){const a=n.fullPath?.toLowerCase();if(!a)continue;const o=a.split("/").pop();t.has(a)||t.set(a,n.mailboxId),o&&!t.has(o)&&t.set(o,n.mailboxId)}return t}function _0(e,t=[]){const s=e.flat().filter(o=>o.fullPath),n=new Map;for(const o of s){const i=zn(o.fullPath).toLowerCase();n.set(i,(n.get(i)??0)+1)}const a=new Map(t.map(o=>[o.accountId,o.email]));return s.map(o=>{const i=zn(o.fullPath),l=n.get(i.toLowerCase())===1,u=t.length>1?a.get(o.accountId):void 0;return{value:l?i:o.fullPath,label:o.displayNameOverride?.trim()||i,...u?{hint:u}:{}}})}function z0(e){const t=new Map;for(const s of e){const n=s.email.toLowerCase().split("@")[0]??"";t.set(n,(t.get(n)??0)+1)}return e.map(s=>{const n=s.email.split("@")[0]??s.email,a=t.get(n.toLowerCase())===1,o=s.displayName?.trim();return{value:a?n:s.email,label:o||s.email,...o?{hint:s.email}:{}}})}const B0=250,K0=2;function U0({query:e,cursor:t,enabled:s}){const{accounts:n}=Me(),{mailboxesByName:a}=us(),o=a!==void 0,i=s?I0(e,t):void 0,l=i?.source==="contact"?i.query.trim():"",u=or(l,B0),{data:m}=ve({...tr({query:{q:u,limit:ud}}),enabled:u.length>=K0}),d=gt({queries:n.map(x=>({...it({path:{accountId:x.accountId}}),staleTime:1/0}))}),f=c.useMemo(()=>o?_0(d.map(x=>x.data?.items??[]),n):[],[o,d,n]),h=c.useMemo(()=>z0(n),[n]),g=c.useMemo(()=>(m?.items??[]).map(L0),[m]);return c.useMemo(()=>{if(!s)return[];const x=D0(e,t,{mailboxes:f,accounts:h,contacts:g});return o?x:x.filter(p=>p.value!=="in:")},[s,e,t,f,h,g,o])}const q0={title:"",navSlot:null,titleMeta:null,searchSlot:null,searchField:null,searchResults:null,makeFilterSlot:null},Ca=c.createContext(q0),jr=()=>c.useContext(Ca),H0=new Set(["hasAttachment","isUnread","isRead","isStarred","category","before","after"]),W0=e=>H0.has(e),V0=(e,{searchHadSemanticReach:t})=>{const s=[],n=[];let a,o;for(const u of e.tokens){if(u.type==="from"){s.push({field:"From",value:u.value});continue}if(u.type==="subject"){s.push({field:"Subject",value:u.value});continue}if(u.type==="in"){a={mailboxId:u.mailboxId,label:u.value};continue}if(u.type==="account"){o=u.accountId;continue}W0(u.type)&&n.push({type:u.type,label:nd(u)})}const i=e.freeText.trim(),l=i.length>0;return l&&s.push({field:"HasWords",value:i}),{clauses:s,matchOperator:"all",scopedOut:a,droppedFacets:n,targetAccountId:o,keptTerms:l,droppedSemantic:l&&t}},fd="remit.recentSearches",Q0=5;function ja(){try{const e=localStorage.getItem(fd);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function dl(e){const t=e.trim();if(!t)return ja();const s=[t,...ja().filter(n=>n!==t)].slice(0,Q0);try{localStorage.setItem(fd,JSON.stringify(s))}catch{return s}return s}const G0=e=>e.tier!=="phone"&&e.hasLiveInput&&!(e.bodyRendersCommittedResults&&e.hasCommittedQuery);function Y0(e){const{spam:t}=Tc([...e]),s=new Map;for(const a of t)a.mailboxId&&s.set(a.mailboxId,(s.get(a.mailboxId)??0)+1);let n;for(const[a,o]of s)(!n||o>n.count)&&(n={mailboxId:a,count:o});return n}function md({title:e,unreadCount:t,children:s,selectionBar:n,paneOverlay:a,footer:o,searchFilter:i,searchResults:l,searchLoading:u,relatedResults:m,relatedLoading:d,onSelectSearchResult:f,searchResultsLabel:h="Top matches",relatedResultsLabel:g="Related",searchResultsInBody:x=!1}){const{accounts:p,resultFolderIndex:v,searchQuery:b,searchInput:S,onSearchChange:w,onSearchClear:y,searchViewKey:j}=Me(),E=us(),M=He(),N=As(),A=Cr(),[L,O]=c.useState(!1),[D,R]=c.useState(ja),k=Yf(),P=c.useRef(j);c.useEffect(()=>{P.current!==j&&(P.current=j,O(!1))},[j]);const[F,C]=c.useState(0),[T,I]=c.useState(!1),[q,se]=c.useState(void 0),G=U0({query:S,cursor:F,enabled:T&&S.trim().length>0}),oe=c.useCallback(re=>{const he=P0(S,F,re);w(he.query),se({cursor:he.cursor})},[S,F,w]),ne=Fl({count:G.length,onAccept:re=>{const he=G[re];he&&oe(he)}}),{comboboxProps:Z,handleKeyDown:pe}=ne,me=c.useMemo(()=>({comboboxProps:Z,onKeyDown:pe,onCaretChange:C,onFocusChange:I,...q?{caret:q}:{}}),[Z,pe,q]),Q=ne.open?r.jsx($l,{id:ne.listId,suggestions:G,activeIndex:ne.activeIndex,optionId:ne.optionId,onPick:oe,onHighlight:ne.setActiveIndex,label:"Search suggestions",className:"mx-row-inset mt-1 shrink-0"}):null,H=S.trim().length>0,{mailboxesByName:de,accountsByName:ee}=E,fe=c.useMemo(()=>_s(S,{mailboxesByName:de,accountsByName:ee}),[S,de,ee]),U=fe.tokens.map(re=>({label:nd(re),onRemove:()=>w(f0(S,re))})),_=l??[],z=m??[],ce=H?[{id:"top",label:h,results:_},{id:"related",label:g,results:z}]:[],Ke=!(_.length+z.length>0)&&(u===!0||d===!0),{scope:ge}=cu(p),ie=It({select:re=>re.matches}),Ae=iu(ie),we=Hb(ie,ge,Ae?v.get(Ae)?.role:void 0),Ne=we.kind==="global"?Y0([..._,...z]):void 0,ft=Ne?{kind:"global",onScopeToSpam:()=>M({to:"/mail/$mailboxId",params:{mailboxId:Ne.mailboxId},search:{q:b||void 0,selectedMessageId:void 0,selectedThreadId:void 0}})}:we,Y=z.length>0,Ee=c.useMemo(()=>V0(fe,{searchHadSemanticReach:Y}),[fe,Y]),ue=H?Ee:void 0,ke=H?{onClick:()=>{O(!1),k("properties","search")},blockedReason:tx(Ee)?void 0:"Add a sender or words to filter on"}:void 0,et=ke?r.jsx(Rc,{...ke}):null,ct=G0({tier:A,hasLiveInput:H,hasCommittedQuery:b.trim().length>0,bodyRendersCommittedResults:x}),Ye=re=>{R(dl(S)),f?.(re)},Ie=r.jsx(Mc,{value:S,sections:ce,loading:Ke,onSelectResult:Ye,tokens:U,scope:ft}),De=n===void 0,We=ct?r.jsx("div",{className:"h-full overflow-y-auto",children:Ie}):null,Xe=We&&!De?We:s,Ue=We&&De?We:null,tt=cd(A),Se=tt&&(L||H),W=c.useMemo(()=>({title:e,searchResults:Ue,makeFilterSlot:et,searchConversion:ue,navSlot:N&&!N.showNavPane&&r.jsx(ae,{variant:"ghost",size:"touch",icon:r.jsx(Va,{className:"size-5"}),onClick:()=>N.openNav(),"aria-label":"Menu",className:"-ml-2 shrink-0"}),titleMeta:r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[t.toLocaleString()," unread"]}),searchSlot:tt&&!Se&&r.jsx(ae,{variant:"ghost",size:"touch",icon:r.jsx(Jn,{className:"size-5"}),onClick:()=>O(!0),"aria-label":"Search",className:"shrink-0"}),searchField:Se&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"min-w-0 flex-1",children:r.jsx(ao,{value:S,onChange:w,onClear:y,globalFocusKey:!1,showClearButton:!1,suggest:me})}),r.jsx(ae,{variant:"ghost",size:"touch",icon:r.jsx(St,{className:"size-5"}),onClick:()=>{y(),O(!1)},"aria-label":"Close search",className:"shrink-0"})]})}),[e,t,N,tt,Se,S,w,y,me,Ue,et,ue]);if(A==="phone"&&L){const re=he=>{R(dl(S)),O(!1),f?.(he)};return r.jsxs(Ca.Provider,{value:W,children:[r.jsx(lg,{value:S,onChange:w,onClear:y,onCancel:()=>{O(!1),y()},filter:i,recentSearches:D,onPickRecent:w,makeFilter:ke,sections:ce,loading:Ke,onSelectResult:re,tokens:U,scope:ft,suggest:me,suggestList:Q}),a]})}return r.jsx(Ca.Provider,{value:W,children:r.jsxs("section",{className:"relative flex h-full w-full flex-col bg-surface",children:[n?.(W),Q,r.jsx("div",{className:"min-h-0 flex-1",children:Xe}),o,a]})})}const X0=120,hd=({keyboardFocusedMessageId:e,openMessageId:t,enabled:s,open:n,delayMs:a=X0})=>{const o=c.useRef(n);o.current=n;const i=c.useRef(void 0);c.useEffect(()=>{const l=e;if(!s){i.current=l;return}if(l===void 0||l===t)return;if(l===i.current){i.current=void 0;return}const u=setTimeout(()=>o.current(l),a);return()=>clearTimeout(u)},[s,e,t,a])},J0=(e,t,s)=>{const n=e.indexOf(s);if(n===-1)return[];const a=t===void 0?-1:e.indexOf(t);if(a===-1)return[s];const o=Math.min(a,n),i=Math.max(a,n);return e.slice(o,i+1)},Z0=(e,t,s,n)=>t!==void 0&&e.includes(t)?t:s!==void 0&&e.includes(s)?s:n,ew=(e,t)=>{const s=new Set(t),n=new Set;for(const a of e)s.has(a)&&n.add(a);return n},pd=(e,t,s)=>{if(e.length===0)return;const n=t===void 0?-1:e.indexOf(t);if(n===-1)return s>0?e[0]:e[e.length-1];const a=Math.min(Math.max(n+s,0),e.length-1);return e[a]},gd=e=>{const[t,s]=c.useState(new Set),[n,a]=c.useState(void 0),o=c.useCallback(p=>t.has(p),[t]),i=c.useCallback(p=>{a(p),s(v=>{const b=new Set(v);return b.has(p)?b.delete(p):b.add(p),b})},[]),l=c.useCallback(p=>{a(p),s(v=>{if(v.has(p))return v;const b=new Set(v);return b.add(p),b})},[]),u=c.useCallback(p=>{s(v=>{if(!v.has(p))return v;const b=new Set(v);return b.delete(p),b})},[]),m=c.useCallback(p=>{s(new Set(p))},[]),d=c.useCallback(()=>{a(void 0),s(new Set)},[]),f=c.useCallback(p=>{s(v=>p.every(S=>v.has(S))?new Set:new Set(p))},[]),h=c.useCallback(p=>{a(p)},[]),g=c.useCallback(p=>{s(v=>{if(v.size===0)return v;const b=ew(v,p);return b.size===v.size?v:b})},[]),x=c.useCallback((p,v,b)=>{const S=Z0(p,n,b,v);s(w=>{const y=J0(p,S,v);if(y.length===0)return w;const j=new Set(w);for(const E of y)j.add(E);return j}),a(S)},[n]);return{selectedIds:t,selectedCount:t.size,hasSelection:t.size>0,isSelected:o,toggle:i,select:l,deselect:u,selectAll:m,clearSelection:d,toggleAll:f,selectRange:x,setAnchor:h,anchorId:n,intersectWith:g}},xd=(e,t)=>!t&&e>0,tw=(e,t,s)=>e==="BACK"&&t&&s===void 0,sw=({orderedIds:e,isDesktop:t,initialFocusedId:s,onExitSelection:n})=>{const[a,o]=c.useState(s),[i,l]=c.useState(),u=c.useCallback(F=>{l(C=>C===F?C:void 0),o(F)},[]),m=gd(),{selectedCount:d,toggle:f,clearSelection:h,selectRange:g,setAnchor:x,selectAll:p}=m,v=xd(d,t),b=c.useRef(null),S=c.useRef(!1),w=c.useCallback(()=>{n?.(),h()},[h,n]),y=c.useMemo(()=>a?e.indexOf(a):-1,[e,a]),j=c.useCallback(F=>{if(F<0||F>=e.length)return;const C=e[F];if(v){f(C);return}b.current=C,S.current=!1,l(C),o(C)},[e,v,f]),E=c.useCallback(()=>{e.length!==0&&j(y<0?0:Math.min(y+1,e.length-1))},[e.length,y,j]),M=c.useCallback(()=>{e.length!==0&&j(y<=0?0:y-1)},[e.length,y,j]),N=c.useCallback(()=>j(0),[j]),A=c.useCallback(()=>j(e.length-1),[j,e.length]),L=c.useCallback(()=>{a&&f(a)},[a,f]),O=c.useCallback((F,C)=>C.shiftKey?(g(e,F,a),!0):C.metaKey||C.ctrlKey?(f(F),!0):(w(),x(F),!1),[e,a,g,f,w,x]),D=c.useCallback(F=>{const C=pd(e,a,F);C!==void 0&&(g(e,C),b.current=C,S.current=!1,l(void 0),o(C))},[e,a,g]),R=c.useCallback(()=>D(-1),[D]),k=c.useCallback(()=>D(1),[D]),P=c.useCallback(()=>{e.length>0&&p(e)},[e,p]);return{focusedMessageId:a,setFocusedMessageId:u,keyboardFocusedMessageId:i,focusIndex:y,pendingDomFocusRef:b,cursorMovedByPointerRef:S,selection:m,isMultiSelectMode:v,exitSelection:w,moveFocusToIndex:j,focusNext:E,focusPrevious:M,focusFirst:N,focusLast:A,toggleFocusedSelection:L,extendRangeUp:R,extendRangeDown:k,selectAllLoaded:P,handleRowSelect:O}};function bd(e,t){if(e.length!==0)return t!==void 0&&e.includes(t)?t:e[0]}const Ro=c.createContext(null),nw=e=>{const t=c.useContext(Ro);return t?t.rowInteraction(e):null},Mo=()=>{const e=c.useContext(Ro);if(!e)throw new Error("useThreadListSelection must be used inside <ThreadListInteraction>");return e},rw="[data-message-id]",aw=e=>Array.from(e.querySelectorAll(rw)).map(t=>t.dataset.messageId).filter(t=>t!==void 0),ow=(e,t)=>e.length===t.length&&e.every((s,n)=>s===t[n]),iw=e=>{const[t,s]=c.useState([]);return c.useEffect(()=>{const n=e.current;if(!n)return;const a=()=>{const i=aw(n);s(l=>ow(l,i)?l:i)};a();const o=new MutationObserver(a);return o.observe(n,{childList:!0,subtree:!0}),()=>o.disconnect()},[e]),t};function vd({selectedMessageId:e,onOpen:t,onDeleteMessages:s,onSelectionVerb:n,wizardOpen:a=!1,isDeleting:o=!1,commandsRef:i,onTriageContextChange:l,children:u}){const m=Wt(),d=c.useRef(null),f=iw(d),h=sw({orderedIds:f,isDesktop:m,initialFocusedId:e}),{focusedMessageId:g,setFocusedMessageId:x,pendingDomFocusRef:p,cursorMovedByPointerRef:v,selection:b,isMultiSelectMode:S,exitSelection:w,handleRowSelect:y}=h,{selectedIds:j,selectedCount:E,isSelected:M,toggle:N,select:A,toggleAll:L}=b,O=f.length>0&&f.every(H=>j.has(H)),D=c.useCallback(()=>{f.length>0&&L(f)},[f,L]),{intersectWith:R}=b;c.useEffect(()=>{R(f)},[R,f]),c.useEffect(()=>{const H=p.current;H!==null&&(p.current=null,d.current?.querySelector(`[data-message-id="${H}"]`)?.focus())});const k=c.useCallback(H=>{v.current=!0,x(H)},[v,x]),P=c.useCallback(H=>{m||A(H)},[m,A]),F=c.useCallback(()=>{g&&t(g)},[g,t]),C=c.useCallback(H=>t(H,{replace:!0}),[t]);hd({keyboardFocusedMessageId:h.keyboardFocusedMessageId,openMessageId:e,enabled:m&&E===0,open:C});const[T,I]=c.useState(null),q=c.useCallback(H=>T!==null?!0:E>0?(n(H),!0):H!=="delete"||!g?!1:(I([g]),!0),[T,E,n,g]),se=c.useCallback(()=>{T!==null&&(s(T),I(null),w())},[T,s,w]),G=c.useCallback(()=>I(null),[]),oe=c.useCallback(()=>E===0?!1:(w(),!0),[E,w]),ne=f.length>0;c.useEffect(()=>{if(i){if(!ne){i.current=null;return}return i.current={focusNext:h.focusNext,focusPrevious:h.focusPrevious,focusFirst:h.focusFirst,focusLast:h.focusLast,openFocused:F,toggleSelect:h.toggleFocusedSelection,extendSelectDown:h.extendRangeDown,extendSelectUp:h.extendRangeUp,selectAll:h.selectAllLoaded,clearSelection:oe,requestVerb:q,toggleDensity:()=>{}},()=>{i.current=null}}},[i,ne,h.focusNext,h.focusPrevious,h.focusFirst,h.focusLast,h.toggleFocusedSelection,h.extendRangeDown,h.extendRangeUp,h.selectAllLoaded,F,oe,q]);const Z=c.useMemo(()=>Array.from(j),[j]),pe=T!==null;c.useEffect(()=>{l?.({focusedMessageId:g,selectedIds:Z,orderedIds:f,hasList:ne,blocksKeyboard:pe||a})},[l,g,Z,f,ne,pe,a]);const me=bd(f,g),Q=c.useMemo(()=>({selectedIds:j,selectedCount:E,exitSelection:w,startSelectionVerb:n,orderedIds:f,allSelected:O,toggleAllLoaded:D,rowInteraction:H=>({focused:H===g,isTabStop:H===me,isDesktop:m,onFocusRow:k,selection:{isChecked:M(H),onToggleCheck:N,onRowSelect:y,isMultiSelectMode:S,onLongPress:P}})}),[j,E,w,n,f,O,D,g,me,m,k,M,N,y,S,P]);return r.jsxs(Ro.Provider,{value:Q,children:[r.jsx("div",{ref:d,className:"contents",children:u}),r.jsx(Xa,{isOpen:pe,title:Ql(T?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:o,onConfirm:se,onCancel:G})]})}function lw({title:e,isDeleting:t}){const s=jr(),{selectedCount:n,exitSelection:a,startSelectionVerb:o,orderedIds:i,allSelected:l,toggleAllLoaded:u}=Mo();return r.jsx(dr,{title:s.title||e,navSlot:s.navSlot,titleMeta:s.titleMeta,searchSlot:s.searchSlot,searchField:s.searchField,idleSlot:s.makeFilterSlot,count:n,onCancel:a,onDelete:()=>o("delete"),onMarkRead:()=>o("markRead"),isBusy:t,selectAll:i.length>0?{checked:l,indeterminate:n>0&&!l,onChange:u}:void 0})}const Na=e=>({shiftKey:e.shiftKey,metaKey:e.metaKey,ctrlKey:e.ctrlKey}),fl=e=>e.shiftKey||e.metaKey||e.ctrlKey,ta=e=>{e.preventDefault(),e.stopPropagation()},yd=(e,t)=>{const s=c.useRef(!1),n=c.useCallback(i=>{if(s.current=!1,i.button!==0)return;const l=Na(i);fl(l)&&t?.(e,l)&&(ta(i),s.current=!0,i.currentTarget.focus(),l.shiftKey&&window.getSelection()?.removeAllRanges())},[t,e]),a=c.useCallback(i=>{!i.ctrlKey||!t||i.preventDefault()},[t]),o=c.useCallback(i=>{if(s.current)return s.current=!1,ta(i),!0;const l=Na(i);return!fl(l)||!t?.(e,l)?!1:(ta(i),l.shiftKey&&window.getSelection()?.removeAllRanges(),!0)},[t,e]);return{onMouseDown:n,onContextMenu:a,claimClick:o}},cw=({thread:e,active:t=!1,focused:s,isTabStop:n,density:a="comfortable",isDesktop:o,badge:i,selection:l,inListbox:u=!1,linkMailboxId:m,onClick:d,onFocusRow:f})=>{const h=Re(),g=e.id,x=nw(g),p=s??x?.focused??!1,v=n??x?.isTabStop??!1,b=l??x?.selection,S=f??x?.onFocusRow,w=o??x?.isDesktop??!0,y=b?.isChecked??!1,j=b?.isMultiSelectMode??!1,E=b?.onToggleCheck,M=b?.onRowSelect,N=b?.onLongPress,A=c.useCallback(I=>{I.preventDefault(),I.stopPropagation(),E?.(g)},[E,g]),L=yd(g,M),O=c.useCallback(I=>{if(!L.claimClick(I)){if(!w){if(j){I.preventDefault(),I.stopPropagation(),E?.(g);return}d?.();return}M?.(g,Na(I)),d?.()}},[L,w,j,E,M,d,g]),D=c.useCallback(()=>{N?.(g)},[N,g]),{longPressProps:R}=wc({onLongPress:D,accessibilityDescription:y?"Deselect message":"Select message"}),k=c.useCallback(()=>{h.prefetchQuery(ar({path:{messageId:g}}))},[h,g]),P=c.useCallback(()=>{k(),S?.(g)},[k,S,g]),F=Os({"data-list-row":"","data-message-row":!0,"data-message-id":g,...u?{role:"option","aria-selected":y}:{},tabIndex:v?0:-1,onClick:O,onMouseDown:L.onMouseDown,onContextMenu:L.onContextMenu,onMouseEnter:k,onFocus:P},w||!b?{}:R),C=$e(a==="compact"?bc({active:t,focused:p}):$e("group",Ps({active:t,focused:p})),"outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-inset",y&&"bg-accent-soft",!w&&"min-h-11 select-none [-webkit-touch-callout:none]"),T=a==="compact"?r.jsx(vc,{thread:e}):r.jsx(so,{thread:e,badge:i,selection:b?{checked:y,alwaysVisible:j,onToggle:A}:void 0});return m===void 0?r.jsx("button",{type:"button",...F,className:C,children:T}):r.jsx(Et,{to:"/mail/$mailboxId",params:{mailboxId:m},search:I=>({...I,selectedMessageId:g}),...F,className:C,children:T})},Qn=c.memo(cw),wd=8,Sd=e=>e==="From"||e==="FromDomain",uw=e=>({value:e.email,label:e.displayName??e.email,...e.displayName?{hint:e.email}:{},...e.fromSelection?{source:"selected"}:{}}),dw=e=>{const t=Pc(e.email);if(t!==null)return{value:t,...e.fromSelection?{source:"selected"}:{}}},fw=(e,t)=>e.value.toLowerCase().includes(t)||(e.label??"").toLowerCase().includes(t),mw=(e,t,s)=>{if(!Sd(e))return[];const n=t.trim().toLowerCase(),a=new Set,o=[];for(const i of s){if(i.email.trim()==="")continue;const l=e==="From"?uw(i):dw(i);if(!l)continue;const u=l.value.toLowerCase();if(!(u===""||a.has(u))&&(a.add(u),u!==n&&!(n!==""&&!fw(l,n))&&(o.push(l),o.length===wd)))break}return o},hw=250,pw=2,gw=(e,t,s)=>{const n=t.trim(),a=or(n,hw),o=e!==void 0&&Sd(e),{data:i}=ve({...tr({query:{q:a,limit:wd}}),enabled:o&&a.length>=pw});if(!o||e===void 0)return[];const l=[...s.map(u=>({email:u,fromSelection:!0})),...(i?.items??[]).map(u=>({email:u.normalizedEmail,...u.displayName?{displayName:u.displayName}:{}}))];return mw(e,n,l)},xw={delete:(e,t)=>`Deleting ${e} of ${t}…`,move:(e,t)=>`Moving ${e} of ${t}…`,markRead:(e,t)=>`Marking ${e} of ${t} as read…`},bw={delete:"moved to Trash",move:"moved",markRead:"marked as read"},vw={delete:"couldn't be deleted",move:"couldn't be moved",markRead:"couldn't be marked as read"},yw={delete:"Couldn't delete these messages",move:"Couldn't move these messages",markRead:"Couldn't mark these messages as read"},ww={delete:"The delete didn't finish.",move:"The move didn't finish.",markRead:"The update didn't finish."},Sw=(e,t,s)=>xw[e](ss(t),ss(s)),kw=(e,t)=>`${ss(t)} ${bw[e]}. Your mail server is still catching up.`,Cw=(e,t)=>t>0?`Stopped after ${ss(t)} — some messages ${vw[e]}`:yw[e],jw=e=>ww[e],Nw=e=>e==="delete"?"danger":"info",Ew=100,Iw=(e,t)=>e.kind==="move"?[t,e.destinationMailboxId]:[t],kd=({mailboxId:e,accountId:t,enabled:s,predicateKey:n,searchQuery:a})=>{const[o,i]=c.useState({kind:"idle"}),[l,u]=c.useState(void 0),[m,d]=c.useState(void 0),f=c.useRef(!1),h=Re(),{pushError:g}=lt();c.useEffect(()=>{f.current=!0,i({kind:"idle"})},[s,n]);const x=c.useRef(a);x.current=a;const p=c.useCallback(async E=>{const{data:M}=await Kl({path:{mailboxId:e},query:{...x.current,continuationToken:E,limit:Ew},throwOnError:!0});return{ids:(M.items??[]).map(N=>N.messageId),continuationToken:M.continuationToken}},[e]),v=c.useCallback(E=>async M=>{if(E.kind==="move"){const{data:A}=await Xf({body:{messageIds:M,destinationMailboxId:E.destinationMailboxId},throwOnError:!0});return A}if(E.kind==="markRead"){const{data:A}=await Jf({body:{messageIds:M,isRead:!0},throwOnError:!0});return A}const{data:N}=await Zf({body:{messageIds:M},throwOnError:!0});return N},[]),b=c.useCallback(E=>{Dt(h,Ot(Iw(E,e))),t&&h.invalidateQueries({queryKey:is({path:{accountId:t}})})},[h,e,t]),S=c.useCallback(()=>{f.current=!1,i({kind:"counting",countSoFar:0}),Rv(p,E=>i({kind:"counting",countSoFar:E}),()=>f.current).then(E=>{if(E.error){g(ts("Couldn't count matching messages","The count didn't finish.",E.error)),i({kind:"idle"});return}if(E.cancelled){i({kind:"idle"});return}i({kind:"escalated",total:E.total})})},[p,g]),w=c.useCallback(()=>{f.current=!0},[]),y=c.useCallback(()=>{f.current=!0,i({kind:"idle"})},[]),j=c.useCallback(async(E,M)=>{f.current=!1,u(E);const N=O=>d(Tv(O)),A=v(E),L=M!==void 0?await bu(M,A,N,()=>f.current):await Iv(p,o.kind==="escalated"?o.total:0,A,N,()=>f.current);return u(void 0),d(void 0),i({kind:"idle"}),L.error&&g(ts(Cw(E.kind,L.done),jw(E.kind),L.error)),L.done>0&&b(E),L},[v,p,o,g,b]);return{phase:o,escalate:S,stop:w,clear:y,isRunning:l!==void 0,runningAction:l,progress:m,runAction:j}},Cd=12,Tw=e=>{const{envelope:t}=e,s=t.from[0];return{id:t.messageId,sender:s?Lc({normalizedEmail:s.normalizedEmail,displayName:s.displayName}):"Unknown",subject:t.subject??"(No subject)",date:pt(t.date)}},Rw=(e,t)=>{const s=e!==void 0&&t!==void 0,{data:n,isLoading:a}=ve({...Ul({path:{mailboxId:e??""},query:{...t,limit:Cd}}),enabled:s,staleTime:3e4});return{messages:(n?.items??[]).map(Mw),isPending:s&&a}},Mw=e=>({id:e.messageId,sender:e.fromName||e.fromEmail||"Unknown",subject:e.subject??"(No subject)",date:pt(e.sentDate)}),Aw=e=>gt({queries:e.slice(0,Cd).map(t=>({...ar({path:{messageId:t}}),staleTime:Number.POSITIVE_INFINITY})),combine:t=>({messages:t.map(s=>s.data).filter(s=>s!==void 0).map(Tw),isPending:t.some(s=>s.isPending)})}),Ow=e=>({matchOperator:"Or",literalClauses:mr(e)}),Dw=(e,t,s)=>{const n=Oe(em()),{mutate:a,reset:o}=n,[i,l]=c.useState(!1),u=c.useMemo(()=>fr(s),[s]),m=c.useCallback(()=>{!e||!t||(l(!1),a({path:{accountId:e},body:Ho({anchorMessageId:t,matchOperator:"And",literalClauses:[]})}))},[e,t,a]),d=c.useCallback(()=>{l(!1),o()},[o]),f=n.data,h=f?.semanticUnavailable===!0&&!i&&u.length>0;c.useEffect(()=>{!h||!e||(l(!0),a({path:{accountId:e},body:Ho(Ow(u))}))},[h,e,u,a]);const g=i||(f?.semanticUnavailable??!1),x=n.isPending||h,p=i?{matchOperator:"Or",literalClauses:mr(u)}:{...t?{anchorMessageId:t}:{},matchOperator:"And",literalClauses:[]};return{preview:m,reset:d,matchedCount:x?void 0:f?.matchedCount,messageIds:x?void 0:f?.messageIds,semanticUnavailable:g,senderFallback:i,senders:u,matchPredicate:p,isPending:x,isError:n.isError,error:n.error}},Pw=()=>[nr({path:{mailboxId:""}}),Ka({path:{mailboxId:""}}),Ua()].map(e=>[{_id:e[0]._id}]),Lw=e=>vu(e)?e.pages:yu(e)?[e]:[],Fw=e=>typeof e=="object"&&e!==null&&typeof e.messageId=="string",$w=(e,t)=>{const s=new Set(t),n=new Map;for(const a of e)for(const o of Lw(a))for(const i of o.items){if(!Fw(i)||!s.has(i.messageId))continue;const l=i.subject?.trim();l&&n.set(i.messageId,l)}return t.map(a=>n.get(a)).filter(a=>a!==void 0)},_w=e=>{const t=Re(),s=e.join("\0");return c.useMemo(()=>{const n=Pw().flatMap(a=>t.getQueriesData({queryKey:a}).map(([,o])=>o));return $w(n,e)},[t,s])},zw={clauses:[],matchOperator:"any"},Bw={clauses:[],matchOperator:"all",droppedFacets:[],keptTerms:!1,droppedSemantic:!1},Kw=[],Lt={state:"saving",matched:0,applied:0,failed:0,failures:[]},sa=(e,t)=>e.map((s,n)=>({...s,id:`${t}-${n}`})),ml=(e,t,s)=>{if(e==="delete")return{kind:"delete"};if(e==="markRead")return{kind:"markRead"};const n=e==="junk"?s:t;return n?{kind:"move",destinationMailboxId:n}:void 0},na=e=>e==="move"||e==="junk"||e==="organize",hl=(e,t)=>({done:0,failedIds:[...t],cancelled:!1,error:new Error(e==="junk"?"This account has no Junk folder appointed, so there is nowhere to file these. Appoint one under Settings › Folders.":"No destination was chosen, so there is nowhere to file these. Go back and pick a folder.")});function Uw({verb:e,accountId:t,mailboxId:s,selection:n,crossAccount:a=!1,escalated:o,escalatedProgress:i,searchConversion:l,onFinished:u,step:m,goToStep:d,goBack:f,closeWizard:h}){const[g]=c.useState(()=>l),[x]=c.useState(()=>o),p=g!==void 0,[v,b]=c.useState(p?"properties":"selected"),S=x?"escalated":v,[w,y]=c.useState(()=>g?{clauses:sa(g.clauses,"search"),matchOperator:g.matchOperator}:zw),[j,E]=c.useState(void 0),[M,N]=c.useState(void 0),[A,L]=c.useState(!1),[O,D]=c.useState(void 0),[R,k]=c.useState(void 0),[P,F]=c.useState(),C=c.useRef(!1),T=c.useMemo(()=>n.map($=>$.id),[n]),I=c.useMemo(()=>n.map($=>$.email).filter(Boolean),[n]),q=T[0],se=_w(T),{junkMailboxId:G}=Fs(t),oe=Dw(x?void 0:t,q,I),{preview:ne}=oe;c.useEffect(()=>{ne()},[ne]);const Z=S==="similar"||S==="properties",pe=c.useMemo(()=>({matchOperator:w.matchOperator==="all"?"And":"Or",literalClauses:w.clauses.map($=>({field:$.field,value:$.value}))}),[w.clauses,w.matchOperator]),me=S==="similar"?oe.matchPredicate:pe,{count:Q,matchedIds:H}=Im(Z?t:void 0,me),de=Aw(Z?H:[]),ee=Rw(x?s:void 0,x?.searchQuery),fe=x?{status:"ready",count:x.total}:Z?Q:{status:"ready",count:n.length},{data:U}=ve({...it({path:{accountId:t??""}}),enabled:!!t,staleTime:Number.POSITIVE_INFINITY}),_=yo(t),z=c.useMemo(()=>Ga(U?.items??[],_).map($=>({id:$.mailboxId,label:zn($.fullPath),searchValue:$.fullPath,isCurrent:$.mailboxId===s})),[U?.items,_,s]),{createFolder:ce}=Gl(t),be=z.find($=>$.id===w.moveMailboxId)?.label,Ke=Wg(n.map($=>({normalizedEmail:$.email,displayName:$.sender}))),ge=ex({match:S==="properties"&&w.clauses[0]?.value.trim()||void 0,sender:Ke?Lc(Ke):void 0,folder:be}),ie=c.useMemo(()=>({...w,name:w.name??ge}),[w,ge]),Ae=gw(j?.draft.field,j?.draft.value??"",I),we=Tm(t),Ne=Rm(t),ft=kd({mailboxId:s??"",accountId:t,enabled:!1,predicateKey:"selection-wizard",searchQuery:{}}),{runAction:Y}=ft,Ee=nm({verb:e,mode:S,scope:w.scope,fromSearch:p}),ue=Ee[Uo(Ee,m)],ke=!a&&!!t,et=ke?void 0:om,ct=ke?void 0:im,Ie=($=>{if($==="folder")return ct;if($==="rule")return ie.scope==="standing"||ie.scope==="until"?et:void 0})(ue)??rm(ue,ie,fe),De=c.useCallback(()=>sa(Zg(I,se),"seed"),[I,se]),We=c.useCallback($=>{b($),y(J=>({...J,widen:$==="similar"&&q?{anchorCount:Math.max(n.length,1)}:void 0,...$==="properties"&&J.clauses.length===0?{clauses:De()}:{}}))},[q,n.length,De]),Xe=c.useCallback(()=>{L(!0),b("properties"),y($=>({...$,widen:void 0,clauses:sa(mr(I),"sender"),matchOperator:"any"})),d("properties")},[I,d]),Ue=oe.semanticUnavailable||oe.isError;c.useEffect(()=>{ue==="match"&&(S!=="similar"||!Ue||A||Xe())},[ue,S,Ue,A,Xe]);const tt=c.useCallback(()=>{E({mode:"add",draft:{field:"From",value:""}})},[]),Se=c.useCallback($=>{const J=w.clauses.find(qe=>qe.id===$);J&&E({mode:"edit",clauseId:$,draft:{field:J.field,value:J.value}})},[w.clauses]),W=c.useCallback($=>{y(J=>({...J,clauses:J.clauses.filter(qe=>qe.id!==$)}))},[]),re=c.useCallback($=>{E(J=>J&&{...J,draft:$})},[]),he=c.useCallback(()=>{E($=>{if(!$)return;const J=Mm($.draft.field,$.draft.value),qe={...$.draft,value:J};y(mt=>({...mt,clauses:$.clauseId?mt.clauses.map(Ze=>Ze.id===$.clauseId?{...Ze,...qe}:Ze):[...mt.clauses,{id:crypto.randomUUID(),...qe}]}))})},[]),le=c.useCallback(()=>{if(Ie){N(ue);return}N(void 0);const $=Ee[Uo(Ee,ue)+1];$&&d($)},[Ie,ue,Ee,d]),ye=c.useCallback(async $=>{const J=ml(e,ie.moveMailboxId,G);if(!J){k({matched:$.length,outcome:hl(e,$)});return}k({matched:$.length});const qe=await Y(J,[...$]);k({matched:$.length,outcome:qe})},[e,ie.moveMailboxId,G,Y]),Ce=c.useCallback(async()=>{if(!x)return;const $=ml(e,ie.moveMailboxId,G);if(!$){k({matched:x.total,outcome:hl(e,[])});return}k({matched:x.total});const J=await x.run($);k({matched:x.total,outcome:J})},[x,e,ie.moveMailboxId,G]),{start:xe}=we,{createFilterAsync:Ve}=Ne,Pe=c.useCallback(()=>{if(x){Ce();return}const $=Am({mode:v,ruleScope:ie.scope}),J=Om({mode:v,ruleScope:ie.scope,anchorMessageId:q,clauses:ie.clauses,matchOperator:ie.matchOperator,moveMailboxId:ie.moveMailboxId,until:ie.until});if(D($),$==="standing"||$==="temporary"){const qe=Dm(J)?J:void 0;F(qe),Ve(J,$,(ie.name??"").trim()).then(mt=>{mt&&qe&&xe(qe)});return}if($==="all-like-these"&&na(e)){xe(J);return}ye($==="just-these"?T:H)},[x,Ce,v,ie,q,e,T,H,Ve,xe,ye]),Je=c.useCallback(()=>{if(Ie){N(ue);return}C.current||(C.current=!0,d("run"),Pe())},[Ie,ue,d,Pe]),_e=c.useCallback(()=>{const $=we.progress,J={matched:$.matchedCount,applied:$.appliedCount,failures:[]};return we.isError?{...Lt,state:"commitFailed"}:we.isDone?{...J,state:$.failedCount>0?"backApplyFailed":"backApplyComplete",failed:$.failedCount}:we.isStarting||we.isRunning?{...J,state:"backApplyRunning",failed:0}:Lt},[we]),Le=c.useMemo(()=>{const $=new Map;for(const J of[...n,...de.messages,...ee.messages])$.set(J.id,J);return $},[n,de.messages,ee.messages]),st=x?i:ft.progress,Qe=c.useCallback(()=>{if(!R)return Lt;const{matched:$,outcome:J}=R;if(!J){const bt=st?.done??0;return{state:"backApplyRunning",matched:Math.max($,bt),applied:bt,failed:0,failures:[]}}if(!(J.cancelled||J.error!==void 0))return{state:"backApplyComplete",matched:Math.max($,J.done),applied:J.done,failed:0,failures:[]};if(J.done===0)return{...Lt,state:"commitFailed"};const mt=J.failedIds.map(bt=>Le.get(bt)).filter(bt=>bt!==void 0),Ze=J.failedIds.length>0?J.failedIds.length:Math.max($-J.done,1);return{state:"runStopped",matched:Math.max($,J.done),applied:J.done,failed:Ze,failures:mt}},[R,st,Le]),Gt=()=>x?Qe():O==="standing"||O==="temporary"?Ne.isError?{...Lt,state:"commitFailed"}:Ne.isSuccess?P?we.isError?{...Lt,state:"backApplyStartFailed"}:_e():{...Lt,state:"filterSaved"}:Lt:O==="all-like-these"&&na(e)?_e():Qe(),ds=()=>{if(x){Ce();return}if(O==="standing"||O==="temporary"){if(Ne.isError){Ne.reset(),Pe();return}P&&xe(P);return}if(O==="all-like-these"&&na(e)){Pe();return}const $=R?.outcome?.failedIds??[];ye($.length>0?$:T)},fs=c.useCallback(()=>{h(Ee,ue)},[h,Ee,ue]),kt=c.useCallback(()=>{h(Ee,ue),u()},[h,Ee,ue,u]);Xc({shouldBlockFn:({action:$})=>$!=="BACK"?!1:(kt(),!0),enableBeforeUnload:!1,disabled:ue!=="run"});const nt=Gt(),ut={messages:x?ee.messages:Z?de.messages:n,count:fe,label:S==="selected"?"Your selection":"A sample of what matches",emptyReason:S==="similar"&&Ue?"notIndexed":"noMatch",loading:x?ee.isPending:Z&&(fe.status==="loading"||de.isPending)};return r.jsx(am,{verb:e,steps:Ee,step:ue,blockedReason:Ie,nudged:M===ue,onBack:f,onExit:fs,onContinue:le,onCommit:Je,match:{selectedCount:n.length,mode:S,onModeChange:We,semanticUnavailable:Ue,semanticErrorDetail:oe.error instanceof Error?oe.error.message:void 0,semanticFallbackTaken:A,onSemanticFallback:Xe,escalatedScope:x?.scope,sample:ut},properties:{clauses:ie.clauses,matchOperator:ie.matchOperator,onMatchOperatorChange:$=>y(J=>({...J,matchOperator:$})),clauseEdit:j,onStartAddClause:tt,onStartEditClause:Se,onRemoveClause:W,onChangeDraft:re,onSubmitClause:he,onCancelClause:()=>E(void 0),clauseFields:Pm,clauseSuggestions:Ae,conversionNotice:g?sx(g):void 0,semanticFallbackTaken:A,sample:{...ut,label:"What this matches"}},folder:{mailboxes:z,mailboxId:ie.moveMailboxId,onSelect:$=>y(J=>({...J,moveMailboxId:$})),onCreateFolder:t?ce:void 0,restriction:ct},rule:{draft:ie,onScopeChange:$=>y(J=>({...J,scope:$})),onUntilChange:$=>y(J=>({...J,until:$})),restriction:et},name:{name:ie.name??"",onNameChange:$=>y(J=>({...J,name:$})),nudged:M===ue},review:{verb:e,mode:S,selectedCount:n.length,clauses:ie.clauses,matchOperator:ie.matchOperator,folder:be,scope:ie.scope,until:ie.until,ruleName:Ee.includes("name")?ie.name:void 0,escalatedScope:x?.scope,sample:ut},run:{state:nt.state,verb:e,scope:ie.scope,matched:nt.matched,applied:nt.applied,failedCount:nt.failed,failures:nt.failures,onRetry:ds,onDismiss:kt}})}function Ao(e){const t=tm()==="search",{searchConversion:s}=jr(),{accounts:n}=Me(),{step:a,goToStep:o,goBack:i,closeWizard:l}=sm(t?"properties":"match");if(!a)return null;const u=t?s??Bw:void 0;return r.jsx(Uw,{...e,...u?{verb:"organize",accountId:u.targetAccountId??n[0]?.accountId,selection:Kw,crossAccount:!1,escalated:void 0,searchConversion:u}:{},step:a,goToStep:o,goBack:i,closeWizard:l})}const qw=200,Hw={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0,contacts:e=>e.trust==="vip"||e.trust==="wellknown",today:e=>e.sentDate!=null&&new Date(e.sentDate).toDateString()===new Date().toDateString()},pl=()=>r.jsx("div",{className:"animate-pulse",children:Array.from({length:3}).map((e,t)=>r.jsxs("div",{className:"flex items-start gap-3 py-2 pl-5 pr-4 border-b border-line",children:[r.jsx("div",{className:"size-7 rounded-full bg-surface-sunken shrink-0 mt-0.5"}),r.jsxs("div",{className:"flex-1 space-y-1.5",children:[r.jsxs("div",{className:"flex justify-between gap-2",children:[r.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-28"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-12"})]}),r.jsx("div",{className:"h-3.5 bg-surface-sunken rounded w-48"}),r.jsx("div",{className:"h-3 bg-surface-sunken rounded w-full"})]})]},t))}),Ww=({accountEmail:e})=>{const t=He();return r.jsxs("div",{className:"flex items-center gap-2 px-row-inset py-2 border-b border-line bg-danger-soft/40 text-xs text-danger",children:[r.jsx(os,{className:"size-3.5 shrink-0"}),r.jsxs("span",{className:"flex-1 truncate",children:[e," can't connect"]}),r.jsx("button",{type:"button",onClick:()=>t({to:"/settings/accounts"}),className:"shrink-0 underline text-danger hover:opacity-80",children:"Reconnect"})]})};function Vw({sections:e,briefCategory:t,selectedThreadId:s,onSelectThread:n}){const a=t==="all",o=e.flatMap(l=>l.threads).filter(l=>l.category===t),i=a?e.length===0:o.length===0;return r.jsxs("div",{className:"h-full overflow-y-auto",children:[a?e.map(l=>r.jsx(lm,{section:l,Row:Qn,selectedThreadId:s,onSelectThread:n},l.id)):r.jsx("div",{className:"divide-y divide-line",children:o.map(l=>r.jsx(Qn,{thread:l,active:l.id===s,onClick:()=>n?.(l.id)},l.id))}),i&&r.jsx("div",{className:"px-row-inset py-6 text-center text-2xs text-fg-subtle",children:"No threads match these filters."})]})}const Qw=(e,t)=>{if(t.size===0)return{};const s=new Set,n=new Set;for(const o of e)t.has(o.id)&&(o.accountId&&s.add(o.accountId),o.mailboxId&&n.add(o.mailboxId));if(s.size>1)return{moveDisabledHint:"Move only works within one account — clear selection or pick messages from a single account"};const a=s.size===1?[...s][0]:void 0;return n.size>1?{accountId:a,moveDisabledHint:`Move only works within one folder — this selection spans ${n.size} folders`}:{accountId:a,mailboxId:n.size===1?[...n][0]:void 0}};function Gw({header:e,rows:t,wizard:s,children:n}){const{selectedIds:a,selectedCount:o,exitSelection:i,orderedIds:l,allSelected:u,toggleAllLoaded:m}=Mo(),d=c.useMemo(()=>Qw(t,a),[t,a]),{junkMailboxId:f}=Fs(d.accountId),{labels:h}=Ya(d.accountId),g=c.useMemo(()=>Array.from(a),[a]),x=c.useMemo(()=>t.filter(w=>a.has(w.id)).map(w=>({id:w.id,sender:w.fromName,email:w.fromEmail,subject:w.subject,date:w.timeLabel})),[t,a]),p=!!f&&f!==d.mailboxId,v=c.useMemo(()=>l.length>0?{checked:u,indeterminate:o>0&&!u,onChange:m}:void 0,[l.length,u,o,m]),b=d.moveDisabledHint?{tone:"warning",text:d.moveDisabledHint}:void 0,S=w=>r.jsx(dr,{title:w.title,navSlot:w.navSlot,titleMeta:w.titleMeta,searchSlot:w.searchSlot,searchField:w.searchField,idleSlot:w.makeFilterSlot,count:o,onCancel:i,onDelete:()=>s.start("delete"),onMove:()=>s.start("move"),onOrganize:()=>s.start("organize"),onJunk:p?()=>s.start("junk"):void 0,onMarkRead:()=>s.start("markRead"),overflowSlot:d.accountId&&d.mailboxId&&o>0&&h.length>0?r.jsx(ld,{accountId:d.accountId,mailboxId:d.mailboxId,messageIds:g}):void 0,selectAll:v,notice:b});return r.jsx(md,{...e,selectionBar:S,paneOverlay:r.jsx(Ao,{verb:s.verb,accountId:d.accountId,mailboxId:d.mailboxId,selection:x,crossAccount:d.moveDisabledHint!==void 0,onFinished:i}),children:n})}function Yw({accounts:e,selectedMessageId:t,onSelectMessage:s,onSelectSearchResult:n,commandsRef:a,onTriageContextChange:o,onDeleteMessages:i}){const{searchQuery:l,resultFolderIndex:u}=Me(),m=us(),d=Wt(),f=Ha(),h=c.useMemo(()=>b0(e.filter(U=>!U.muted?.value)),[e]),[g,x]=c.useState("all"),[p,v]=c.useState("all"),[b,S]=c.useState(new Set),[w,y]=c.useState(!1),j=c.useCallback(U=>{S(_=>{const z=new Set(_);return z.has(U)?z.delete(U):z.add(U),z})},[]),{data:E,isLoading:M,isError:N,refetch:A}=ve({...la(),staleTime:6e4}),L=gt({queries:h.map(U=>({...it({path:{accountId:U.accountId}}),staleTime:1/0,meta:{softError:!0}}))}),O=c.useMemo(()=>{const U=new Map;for(let _=0;_<h.length;_++){const z=h[_].accountId,be=(L[_]?.data?.items??[]).reduce((Ke,ge)=>Ke+(ge.unseenCount??0),0);U.set(z,be)}return U},[h,L]),D=c.useMemo(()=>h.filter((U,_)=>{const z=L[_];return z?.isError?!ca(z.error):!1}),[h,L]),{freeText:R,tokens:k}=_s(l.trim().toLowerCase(),m),{data:P,isFetching:F}=ve({...la({query:{query:R,limit:qw}}),enabled:R.length>0,staleTime:3e4}),C=c.useMemo(()=>{const U=ll(E?.items??[]).map(Vn);return(R?v0(U.filter(z=>ad(z,R)),ll(P?.items??[]).map(Vn)):U).filter(z=>(g==="all"||z.accountId===g)&&Io(z,k))},[E,P,g,R,k]),T=c.useMemo(()=>y0(C),[C]),I=c.useMemo(()=>h.length<=1?[]:[{id:"all",label:"All",active:g==="all"},...h.map(U=>({id:U.accountId,label:U.email.split("@")[0]??U.email,count:O.get(U.accountId),active:g===U.accountId}))],[h,O,g]),q=c.useMemo(()=>e.filter(U=>U.muted?.value).length,[e]),se=c.useMemo(()=>Array.from(O.values()).reduce((U,_)=>U+_,0),[O]),G=c.useMemo(()=>{const U=Array.from(b).map(_=>Hw[_]).filter(_=>_!=null);return C.filter(_=>(p==="all"||_.category===p)&&U.every(z=>z(_))).map(_=>od(_,u))},[C,p,b,u]),{hits:oe,isLoading:ne}=rd(),Z=c.useMemo(()=>{const U=new Map;for(const z of E?.items??[])U.set(z.messageId,z.threadId);const _=G.map(z=>U.get(z.id)).filter(z=>z!=null);return id(oe,_,u)},[oe,G,E,u]),pe=c.useMemo(()=>{const U=Tg(I.map(_=>({id:_.id,label:_.label,count:_.count,active:_.active})));return{categories:U.categories,filters:U.filters,sources:U.sources,sourcesNote:q>0?`+${q} muted`:void 0,selectedCategory:p,activeFilters:b,expanded:w,onExpandedChange:y,onSelectCategory:_=>v(_),onSelectSource:x,onToggleFilter:j,onClear:()=>{v("all"),x("all"),S(new Set)}}},[I,q,p,b,w,j]),me=T.length===0&&g==="all"&&R.length===0,Q=c.useMemo(()=>h.map(U=>U.accountId),[h]),H=c.useMemo(()=>h.some(U=>Xu(U.syncPhase)),[h]),de=e0(Q,me||H),ee=r.jsxs("div",{className:"h-full overflow-y-auto",children:[r.jsx(pl,{}),r.jsx(pl,{})]}),fe=M?ee:N?r.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 py-12 text-sm text-fg-muted",children:[r.jsx(os,{className:"size-8 text-danger"}),r.jsx("p",{children:"Couldn't load your messages"}),r.jsxs("button",{type:"button",onClick:()=>A(),className:"flex items-center gap-1 text-accent underline text-xs",children:[r.jsx(fc,{className:"size-3.5"}),"Try again"]})]}):me?de.resolved?r.jsx(Up,{sync:de.syncing?{synced:de.synced,total:de.total}:void 0}):ee:r.jsx(Vw,{sections:T,briefCategory:p,selectedThreadId:t,onSelectThread:s});return r.jsx(vd,{selectedMessageId:t,onOpen:(U,_)=>s?.(U,_),onDeleteMessages:i,onSelectionVerb:f.start,wizardOpen:f.isOpen,commandsRef:a,onTriageContextChange:o,children:r.jsx(Gw,{wizard:f,header:{title:"Daily brief",unreadCount:se,footer:d?r.jsx(gc,{}):void 0,searchFilter:pe,searchResults:G,searchLoading:M||F,relatedResults:Z,relatedLoading:ne,onSelectSearchResult:n},rows:C,children:r.jsxs("div",{className:"flex h-full flex-col",children:[D.map(U=>r.jsx(Ww,{accountEmail:U.email,accountId:U.accountId},U.accountId)),r.jsx("div",{className:"min-h-0 flex-1",children:fe})]})})})}const Xw=10,jd=e=>({q:e?.toLowerCase()??"",limit:Xw}),Jw=(e,t)=>{if(!t)return;const s=t.toLowerCase();return e?.find(n=>n.normalizedEmail===s)};function Zw(e){const t=new Date(e),s=new Date;return t.toDateString()===s.toDateString()?"today":Bn(t,{month:"short",year:"numeric"})}function Nd(e){if(!e)return!0;const[,t]=e.split("@");return t?!t.includes("."):!0}const eS="We can't verify the sender of this email, which could mean it's from an insecure source.",tS="We couldn't read this sender's address, so we can't confirm who really sent this message.";function sS(e,t){return{name:e.fromName??e.fromEmail??"Unknown",email:e.fromEmail??"",trust:e.senderTrust,firstSeenLabel:t?Zw(t.createdAt):"unknown",inboundCount:t?.inboundCount,replyCount:t?.replyCount,addressUnverified:Nd(e.fromEmail)}}function nS(e){return e?.flags?{vip:e.flags.vip?.value===!0,muted:e.flags.muted?.value===!0,blocked:e.flags.blocked?.value===!0,unsubscribed:e.flags.unsubscribed?.value===!0}:{}}function rS(e,t){const s=t>0?t:void 0;if(Nd(e.fromEmail))return{verdict:"mismatch",fromDomain:"",addressUnreadable:!0,summary:tS,similarCount:s};const n=e.authenticity;if(!n)return{verdict:"caution",fromDomain:e.fromEmail?.split("@")[1]??"",summary:eS};if(!n.dkimMismatch)return{verdict:"aligned",fromDomain:n.fromDomain,dkimDomain:n.dkimDomain,summary:n.dkimDomain?`We verified this message was really sent by ${n.fromDomain}.`:"Nothing looks unusual about this sender."};const a=n.fromDomain,o=n.dkimDomain,i=e.fromName&&e.fromName!==e.fromEmail?e.fromName:void 0,l=i?`The display name claims "${i}", but this message was actually sent from ${o??"another sender"} — not ${a}. Real senders use their own address.`:`This message claims to be from ${a}, but it was actually sent from ${o??"a different sender"}.`;return{verdict:"mismatch",fromDomain:a,dkimDomain:o,claimedBrand:i,summary:l,similarCount:s}}function Ed(e,t){const s=e?.fromEmail??null,n=e?.subject??"",{data:a,error:o}=ve({...tr({query:jd(s??void 0)}),enabled:!!s,staleTime:3e4}),i=Jw(a?.items,s??void 0),l=[n,s].filter(Boolean).join(" "),{data:u,isLoading:m,error:d}=ve({...Bl({query:{query:l,limit:5}}),enabled:!!(e&&l.length>3),staleTime:6e4,retry:1});return{data:c.useMemo(()=>{if(!e)return null;const h=(u?.items??[]).filter(b=>b.messageId!==e.messageId).map(b=>({id:b.messageId,mailboxId:t!=null&&b.mailboxIds.includes(t)?t:b.mailboxIds[0]??"",fromName:b.fromName??"",subject:b.subject??"(No subject)",timeLabel:b.sentDate!=null?pt(b.sentDate*1e3):"",matched:b.matchedChunkType})),g=sS(e,i),x=rS(e,h.length),p={value:e.category??"personal",overridden:i?.flags?.category?.value!=null&&i.flags.category.value!==e.category},v=nS(i);return{sender:g,authenticity:x,category:p,flags:v,similar:h}},[e,i,u,t]),isSimilarLoading:m,similarError:d,similarErrorIsFatal:ca(d),addressErrorIsFatal:ca(o),addressId:i?.addressId,address:i}}function aS(e,t){const s={...e??{}};for(const[n,a]of Object.entries(t))a==null?delete s[n]:s[n]={...a,setAt:a.setAt??Date.now()};return s}function Id({addressId:e,senderEmail:t}){const s=Re(),{pushError:n}=lt(),a=cm({query:jd(t)}),{mutate:o,isPending:i}=Oe({...zl(),onMutate:async u=>{const m=u.body.flags??{};await s.cancelQueries({queryKey:a});const d=s.getQueryData(a);return s.setQueryData(a,f=>f&&{...f,items:f.items.map(h=>h.addressId===u.path.addressId?{...h,flags:aS(h.flags,m)}:h)}),{previous:d}},onError:(u,m,d)=>{d?.previous!==void 0&&s.setQueryData(a,d.previous),n({title:"Couldn't update sender preference",detail:ht(u),error:u})},onSettled:()=>{s.invalidateQueries({queryKey:a})}});return{updateFlags:c.useCallback(u=>{if(!e){ql(new Error(`Quick action fired but the sender's address record did not resolve (sender: ${t??"unknown"}). This should never happen — the address row exists.`));return}o({path:{addressId:e},body:{flags:u}})},[e,o,t]),isPending:i}}const oS=e=>e==="vip"?"A sender you know":e==="wellknown"?"You've emailed them before":"Passed authentication",Td=e=>e.senderTrust!=="vip"&&e.senderTrust!=="wellknown"?!1:e.authenticity?.dkimMismatch!==!0;function iS(e,t){e.recordEvent("rescue.candidates_surfaced",{count:String(t)})}function lS(e,t){e.recordEvent("rescue.flow_opened",{count:String(t)})}function cS(e,t){e.recordEvent("rescue.committed",{selected:String(t.selected),total:String(t.total),destination:t.toInbox?"inbox":"other"})}function Rd(e,t){e.recordEvent("rescue.sent_to_junk",{count:String(t.count),senderTrust:t.senderTrust,wasRescuable:String(t.wasRescuable)})}const uS=["personal","newsletter","marketing","automated","transactional","social"],dS=e=>{const{mailboxId:t,junkMailboxId:s,inboxMailboxId:n}=e;return t?s&&t===s?n?"notSpam":null:s?"markSpam":null:null},fS=e=>{const{similarError:t,similarErrorIsFatal:s,isSimilarLoading:n}=e;return t&&!s?"error":n?"loading":"ready"};function mS(){return r.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[r.jsx(Tt,{className:"size-3.5 text-fg-subtle"}),r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),r.jsxs("div",{className:"flex-1 animate-pulse space-y-4 p-4",children:[r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx("div",{className:"size-10 rounded-full bg-surface shrink-0"}),r.jsxs("div",{className:"flex-1 space-y-1.5",children:[r.jsx("div",{className:"h-3 rounded bg-surface w-3/4"}),r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/2"})]})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsx("div",{className:"h-8 rounded bg-surface"})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("div",{className:"h-2.5 rounded bg-surface w-1/4"}),r.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Array.from({length:5}).map((e,t)=>r.jsx("div",{className:"h-6 w-16 rounded bg-surface"},t))})]})]})]})}function hS({isOpen:e,current:t,onSelect:s,onCancel:n}){return e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center","aria-hidden":"true",onClick:n,children:[r.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),r.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Reclassify sender",className:"relative z-10 w-full max-w-sm rounded-sm border border-line bg-surface p-6 shadow-lg",onClick:a=>a.stopPropagation(),onKeyDown:a=>a.stopPropagation(),children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Reclassify this sender"}),r.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Set a category override for future messages from this sender."}),r.jsx("div",{className:"mt-4 flex flex-col gap-1",children:uS.map(a=>r.jsxs("button",{type:"button",onClick:()=>s(a),className:`flex min-h-11 items-center justify-between rounded px-3 text-left text-sm capitalize transition-colors hover:bg-surface-raised ${a===t?"font-semibold text-accent":"text-fg"}`,children:[a,a===t&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"current"})]},a))}),r.jsx("div",{className:"mt-6 flex justify-end",children:r.jsx("button",{type:"button",onClick:n,className:"inline-flex min-h-11 items-center justify-center rounded border border-line px-4 text-sm font-medium transition-colors hover:bg-surface-raised",children:"Cancel"})})]})]}):null}function pS({thread:e,onClose:t,mailboxId:s,accountId:n,hideCloseButton:a}){const{data:o,addressId:i,isSimilarLoading:l,similarError:u,similarErrorIsFatal:m}=Ed(e,s),[d,f]=c.useState(!1),[h,g]=c.useState(!1),x=e.fromEmail??void 0,{updateFlags:p,isPending:v}=Id({addressId:i,senderEmail:x}),{junkMailboxId:b}=Fs(n),{inboxMailboxId:S}=vo(n),{moveMessages:w}=rs({mailboxId:s??"",threadId:e.threadId,accountId:n}),y=ln(),j=dS({mailboxId:s,junkMailboxId:b,inboxMailboxId:S}),E=c.useCallback(()=>{S&&w([e.messageId],S)},[S,w,e.messageId]),M=c.useCallback(()=>{b&&(Rd(y,{count:1,senderTrust:e.senderTrust,wasRescuable:Td(e)}),w([e.messageId],b))},[b,w,e,y]),N=c.useCallback(()=>{},[]),A=c.useCallback(()=>{const I=o?.flags?.vip!==!0;p({vip:{value:I}})},[o?.flags?.vip,p]),L=c.useCallback(()=>{const I=o?.flags?.muted!==!0;p({muted:{value:I}})},[o?.flags?.muted,p]),O=c.useCallback(()=>{o?.flags?.blocked===!0?p({blocked:{value:!1}}):f(!0)},[o?.flags?.blocked,p]),D=c.useCallback(()=>{f(!1),p({blocked:{value:!0}})},[p]),R=c.useCallback(()=>{const I=o?.flags?.unsubscribed!==!0;p({unsubscribed:{value:I}})},[o?.flags?.unsubscribed,p]),k=c.useCallback(I=>{g(!1),p({category:{value:I}})},[p]),P=i!==void 0,F={onToggleVip:P?A:void 0,onToggleMute:P?L:void 0,onToggleBlock:P?O:void 0,onToggleUnsubscribe:P?R:void 0,onReclassify:P?()=>g(!0):void 0,onNotSpam:j==="notSpam"?E:void 0,onMarkSpam:j==="markSpam"?M:void 0},C=({mailboxId:I,messageId:q,className:se,ariaLabel:G,children:oe})=>r.jsx(Et,{to:"/mail/$mailboxId",params:{mailboxId:I},search:ne=>({...ne,selectedMessageId:q}),className:se,"aria-label":G,children:oe});if(!o)return r.jsx(mS,{});const T=fS({similarError:u,similarErrorIsFatal:m,isSimilarLoading:l});return r.jsxs(r.Fragment,{children:[r.jsx(pc,{data:o,onClose:t,hideCloseButton:a,onShowSimilar:N,actions:F,similarState:T,similarLinkComponent:C,className:"border-l-0 h-full w-full"}),r.jsx(Xa,{isOpen:d,title:"Block this sender?",description:`Messages from ${x??"this sender"} will never load images and will be flagged. You can undo this in Settings → Senders.`,confirmLabel:"Block sender",destructive:!0,isBusy:v,onConfirm:D,onCancel:()=>f(!1)}),r.jsx(hS,{isOpen:h,current:o.category.value,onSelect:k,onCancel:()=>g(!1)})]})}const zs=({onClose:e,thread:t,mailboxId:s,accountId:n,hideCloseButton:a})=>t?r.jsx(pS,{thread:t,onClose:e,mailboxId:s,accountId:n,hideCloseButton:a}):r.jsxs("aside",{className:"flex h-full w-full flex-col bg-surface-sunken",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-1.5 border-b border-line px-row-inset",children:[r.jsx(Tt,{className:"size-3.5 text-fg-subtle"}),r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:"Intelligence"})]}),r.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-row-inset text-center",children:[r.jsx(Tt,{className:"size-8 text-fg-subtle"}),r.jsx("p",{className:"mt-3 text-sm text-fg-muted",children:"Intelligence"}),r.jsx("p",{className:"mt-1 text-2xs text-fg-subtle",children:"Sender trust, authenticity and similar messages will appear here."})]})]}),ra="Open a message first",Oo=({hasThread:e,intelligenceOpen:t,canToggleIntelligence:s,onToggleIntelligence:n,onReply:a,onReplyAll:o,onForward:i,onDelete:l,canDelete:u,onToggleStar:m,isStarred:d,moveContext:f})=>{const[h,g]=c.useState(null),x=u??e,p=v=>()=>g(v);return r.jsx(rp,{hasThread:e,isStarred:d,onUnavailable:v=>g(ra),unavailableHint:h,replyTitle:`Reply ${ys("reply")}`,replyAllTitle:`Reply all ${ys("replyAll")}`,forwardTitle:`Forward ${ys("forward")}`,deleteTitle:`Move to Trash ${ys("delete")}`,flagTitle:`Star ${ys("toggleStar")}`,onReply:a,onReplyAll:o,onForward:i,onDelete:x?l:p(ra),onToggleStar:m,onMove:p(ra),moveSlot:f?r.jsx(jo,{accountId:f.accountId,currentMailboxId:f.currentMailboxId,onMove:f.onMove,label:"Move to mailbox"}):void 0,children:r.jsx(np,{open:t,enabled:s,onToggle:n})})},Md=()=>{const e=Re();return c.useCallback(t=>{const s=ls({path:{threadId:t.threadId}}),a=e.getQueriesData({queryKey:s}).flatMap(([,o])=>o?.items.map(i=>i.messageId)??[]);return a.length>0?a:[t.messageId]},[e])},sn=({thread:e,mailboxId:t,accountId:s,onAfterOptimisticRemove:n})=>{const a=t??e?.mailboxId,o=s??e?.accountId,{accountId:i}=go(o?void 0:a),l=o??i,u=Md(),{deleteMessages:m}=as({mailboxId:a??"",threadId:e?.threadId,accountId:l,onAfterOptimisticRemove:n}),{moveMessages:d}=rs({mailboxId:a??"",threadId:e?.threadId,accountId:l,onAfterOptimisticRemove:n}),{toggleStar:f}=xo({threadId:e?.threadId??"",mailboxId:a??""}),h=c.useCallback(()=>{e&&m(u(e))},[e,u,m]),g=c.useCallback(S=>{e&&d(u(e),S)},[e,u,d]),x=c.useCallback(()=>{e&&f(e.messageId,e.hasStars)},[e,f]),[p,v]=c.useState(null),b=c.useCallback(()=>v(null),[]);return{mailboxId:a,accountId:l,isStarred:e?.hasStars,deleteThread:h,moveThread:g,toggleStar:x,composeRequest:p,requestCompose:v,clearComposeRequest:b}},Hs={action:null,nextPrefix:null,preventDefault:!1},gS={b:"goBrief",i:"goInbox",s:"goSent",f:"goFlagged",",":"goSettings"},xS={j:{action:"focusNext"},k:{action:"focusPrevious"},arrowdown:{action:"focusNext"},arrowup:{action:"focusPrevious"},home:{action:"focusFirst"},end:{action:"focusLast"},enter:{action:"openFocused"}," ":{action:"toggleSelect"},delete:{action:"delete"},backspace:{action:"delete"},u:{action:"toggleRead"},x:{action:"toggleSelect"},r:{action:"reply"},a:{action:"replyAll"},f:{action:"forward"},"#":{action:"delete"},s:{action:"toggleStar"},m:{action:"muteSender"},b:{action:"blockSender"},v:{action:"vipSender"},"!":{action:"markJunk"},i:{action:"toggleIntelligence"},d:{action:"toggleDensity"},"/":{action:"focusSearch"},c:{action:"compose"},"?":{action:"help"}};function bS(e,t){const s=e.key.toLowerCase(),n=e.metaKey||e.ctrlKey;if(e.inEditable)return{...Hs,nextPrefix:t==="g"?null:t};if(e.onControl&&(s==="enter"||s===" "))return{...Hs,nextPrefix:t==="g"?null:t};if(n&&s==="n")return{action:"compose",nextPrefix:null,preventDefault:!0};if(n&&s==="a")return{action:"selectAll",nextPrefix:null,preventDefault:!0};if(n)return{...Hs,nextPrefix:t==="g"?null:t};if(s==="escape")return{action:"back",nextPrefix:null,preventDefault:!1};if(t==="g"){const i=gS[s===","?",":s]??null;return{action:i,nextPrefix:null,preventDefault:i!==null}}if(s==="g"&&!e.shiftKey)return{action:null,nextPrefix:"g",preventDefault:!0};if(e.shiftKey){const o=s==="j"||s==="arrowdown";if(o||(s==="k"||s==="arrowup"))return{action:o?"extendSelectDown":"extendSelectUp",nextPrefix:null,preventDefault:!0}}const a=xS[s];if(a){const o=a.requireShift===!0,i=s.length===1&&!/[a-z0-9]/.test(s);return!o&&e.shiftKey&&!i?Hs:{action:a.action,nextPrefix:null,preventDefault:!0}}return Hs}function vS(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable}const yS="data-message-row",wS='button, a[href], summary, [role="button"], [role="menuitem"], [role="tab"], [role="switch"], [role="checkbox"]';function SS(e){if(!(e instanceof HTMLElement))return!1;const t=e.closest(wS);return t?!t.hasAttribute(yS):!1}function kS({handlers:e,enabled:t=!0,sequenceTimeoutMs:s=1e3}){const n=c.useRef(e);n.current=e;const a=c.useRef(null),o=c.useRef(null);c.useEffect(()=>{if(!t)return;const i=()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},l=u=>{const m=bS({key:u.key,shiftKey:u.shiftKey,metaKey:u.metaKey,ctrlKey:u.ctrlKey,altKey:u.altKey,inEditable:vS(u.target),onControl:SS(u.target)},a.current);if(i(),a.current=m.nextPrefix,m.nextPrefix!==null&&(o.current=setTimeout(()=>{a.current=null,o.current=null},s)),m.action===null)return;const d=n.current[m.action];d&&(m.preventDefault&&u.preventDefault(),d())};return window.addEventListener("keydown",l),()=>{window.removeEventListener("keydown",l),i(),a.current=null}},[t,s])}const gl=(e,t,s)=>{if(!t)return null;const n=e.indexOf(t);if(n===-1)return null;const a=s==="next"?n+1:n-1;return a<0||a>=e.length?null:e[a]},Do=()=>{const[e,t]=c.useState(void 0),[s,n]=c.useState([]),[a,o]=c.useState([]),i=c.useRef(null),[l,u]=c.useState(!1),[m,d]=c.useState(!1),f=c.useCallback(h=>{t(h.focusedMessageId),n(h.selectedIds),h.orderedIds&&o(h.orderedIds),u(h.hasList),d(h.blocksKeyboard)},[]);return{listCommandsRef:i,onTriageContextChange:f,focusedMessageId:e,selectedIds:s,orderedIds:a,hasList:l,blocksKeyboard:m}},Po=({context:e,orderedIds:t,selectedMessageId:s,enabled:n=!0,onClose:a,handlers:o})=>{const{listCommandsRef:i,hasList:l,blocksKeyboard:u}=e,m=c.useCallback(()=>{i.current?.clearSelection()||s&&a()},[i,s,a]);return kS({enabled:n&&!u,handlers:{...l?{focusNext:()=>i.current?.focusNext(),focusPrevious:()=>i.current?.focusPrevious(),focusFirst:()=>i.current?.focusFirst(),focusLast:()=>i.current?.focusLast(),openFocused:()=>i.current?.openFocused(),toggleSelect:()=>i.current?.toggleSelect(),extendSelectDown:()=>i.current?.extendSelectDown(),extendSelectUp:()=>i.current?.extendSelectUp(),selectAll:()=>i.current?.selectAll(),toggleDensity:()=>i.current?.toggleDensity()}:{},back:m,...o}}),{goBack:m,nextMessageId:gl(t,s,"next")??void 0,previousMessageId:gl(t,s,"previous")??void 0}};function CS(e){return{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,messageId:e.messageId,authenticity:e.authenticity}}function Ad(e,t){if(e)return CS(e);if(t.messageId&&t.threadId&&t.mailboxId)return{threadId:t.threadId,mailboxId:t.mailboxId,messageId:t.messageId}}const Od=c.createContext(null);function Nr(){const e=c.useContext(Od);if(!e)throw new Error("BriefPane.* must be used inside <BriefPane>");return e}function jS({selectedMessageId:e,children:t}){const s=He(),{searchInput:n}=Me(),{selectedThreadId:a,selectedMailboxId:o}=Is({strict:!1}),{data:i}=ve({...la(),staleTime:6e4}),l=c.useMemo(()=>{if(e)return i?.items.find(A=>A.messageId===e)},[i,e]),u=c.useMemo(()=>Ad(l,{messageId:e,threadId:a,mailboxId:o}),[l,e,a,o]),m=c.useCallback((A,L)=>{s({to:"/mail",search:O=>({...O,selectedMessageId:A,selectedThreadId:void 0,selectedMailboxId:void 0}),replace:L?.replace})},[s]),d=c.useCallback(A=>{s({to:"/mail",search:L=>({...L,q:n||void 0,selectedMessageId:A.id,selectedThreadId:A.threadId,selectedMailboxId:A.mailboxId})})},[s,n]),f=c.useCallback(A=>{e&&A.includes(e)&&s({to:"/mail",search:L=>({...L,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[e,s]),h=sn({thread:l,onAfterOptimisticRemove:f}),g=c.useCallback(()=>{s({to:"/mail",search:A=>({...A,selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0})})},[s]),x=Do(),p=c.useMemo(()=>i?.items??[],[i]),{deleteMessages:v}=as({mailboxId:l?.mailboxId??"",messages:p,onAfterOptimisticRemove:f}),{toggleReadFor:b}=yr({mailboxId:l?.mailboxId??"",messages:p}),S=x.focusedMessageId,y=c.useMemo(()=>i?.items.find(A=>A.messageId===S),[i,S])??l,j=sn({thread:y}),{nextMessageId:E,previousMessageId:M}=Po({context:x,orderedIds:x.orderedIds,selectedMessageId:e,onClose:g,handlers:{reply:()=>h.requestCompose("reply"),replyAll:()=>h.requestCompose("reply_all"),forward:()=>h.requestCompose("forward"),delete:()=>{x.listCommandsRef.current?.requestVerb("delete")||j.deleteThread()},toggleStar:j.toggleStar,toggleRead:()=>{x.listCommandsRef.current?.requestVerb("markRead")||y&&b([y.messageId],!y.isRead)},goFlagged:()=>s({to:"/mail/flagged"}),goSettings:()=>s({to:"/settings"})}}),N={selectedMessageId:e,selectedThread:l,conversation:u,onSelectMessage:m,onSelectSearchResult:d,onCloseThread:g,actions:h,triage:x,onDeleteMessages:v,nextMessageId:E,previousMessageId:M};return r.jsx(Od.Provider,{value:N,children:t})}function Dd(){const{selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,triage:n,onDeleteMessages:a}=Nr(),{accounts:o}=Me();return r.jsx(Yw,{accounts:o,selectedMessageId:e,onSelectMessage:t,onSelectSearchResult:s,commandsRef:n.listCommandsRef,onTriageContextChange:n.onTriageContextChange,onDeleteMessages:a})}function NS(){const{conversation:e,actions:t}=Nr(),{intelligenceOpen:s,onToggleIntelligence:n}=Me(),a=As()?.showIntelligencePane??!1,o=!!e,i=a&&o;return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(Oo,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx($s,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,selectedMessageId:e.messageId,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx(Ls,{})})]})}function ES(){const{selectedThread:e}=Nr(),{onToggleIntelligence:t}=Me();return r.jsx(zs,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function IS(){const{selectedThread:e,conversation:t,onSelectMessage:s,onCloseThread:n,nextMessageId:a,previousMessageId:o}=Nr(),{intelligenceOpen:i,onToggleIntelligence:l}=Me();return t?r.jsxs(r.Fragment,{children:[r.jsx($s,{threadId:t.threadId,mailboxId:t.mailboxId,subject:t.subject,selectedMessageId:t.messageId,authenticity:t.authenticity,onBack:n,onOpenIntelligence:l,onSwipeNext:a?()=>s(a):void 0,onSwipePrevious:o?()=>s(o):void 0,mobileIntelligenceOpen:i}),r.jsx(mo,{isOpen:i,onClose:l,ariaLabel:"Message details",side:"right",children:r.jsx(zs,{onClose:l,thread:e,hideCloseButton:!0})})]}):r.jsx("div",{className:"h-full",children:r.jsx(Dd,{})})}const Ws=Object.assign(jS,{List:Dd,Reading:NS,Intelligence:ES,Phone:IS}),TS=()=>Ua({query:{starred:!0,order:"desc"}});function Pd(){const{data:e,isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}=Yc({queryKey:TS(),queryFn:async({pageParam:m})=>{const{data:d}=await um({query:{starred:!0,order:"desc",continuationToken:m},throwOnError:!0});return d},initialPageParam:void 0,getNextPageParam:m=>m.continuationToken,staleTime:6e4});return{threads:c.useMemo(()=>(e?.pages??[]).flatMap(m=>m.items??[]),[e]),isLoading:t,isError:s,error:n,refetch:a,fetchNextPage:o,hasNextPage:i,isFetchingNextPage:l}}const RS=e=>{const t=new Set;return e.filter(s=>t.has(s.threadId)?!1:(t.add(s.threadId),!0))};function Ld({title:e,unreadCount:t,preset:s,selectedCategory:n,activeFilters:a,onSelectCategory:o,onToggleFilter:i,onSelectSource:l,onClearFilters:u,children:m,footer:d,searchResults:f,searchLoading:h,relatedResults:g,relatedLoading:x,onSelectSearchResult:p,searchResultsLabel:v,relatedResultsLabel:b,searchResultsInBody:S}){const[w,y]=c.useState(!1),{searchInput:j}=Me(),E=j.trim().length>0,M={categories:s.categories,filters:s.filters,sources:s.sources,selectedCategory:n,activeFilters:a,expanded:w,onExpandedChange:y,onSelectCategory:o,onSelectSource:l,onToggleFilter:i,onClear:u};return r.jsx(md,{title:e,unreadCount:t,footer:d,searchFilter:M,searchResults:f,searchLoading:h,relatedResults:g,relatedLoading:x,onSelectSearchResult:p,searchResultsLabel:v,relatedResultsLabel:b,searchResultsInBody:S,children:r.jsx(Rl,{...M,hideChrome:E,children:m})})}const MS={unread:e=>!e.isRead,attachment:e=>e.hasAttachment===!0};function AS({rows:e,verb:t}){const{selectedIds:s,exitSelection:n}=Mo(),a=c.useMemo(()=>e.filter(o=>s.has(o.id)).map(o=>({id:o.id,sender:o.fromName,email:o.fromEmail,subject:o.subject,date:o.timeLabel})),[e,s]);return r.jsx(Ao,{verb:t,selection:a,crossAccount:!0,onFinished:n})}function OS({selectedMessageId:e,onSelectMessage:t,commandsRef:s,onTriageContextChange:n,onDeleteMessages:a}){const{searchQuery:o,resultFolderIndex:i}=Me(),l=us(),u=Wt(),m=Ha(),[d,f]=c.useState("all"),[h,g]=c.useState(new Set),x=c.useCallback(T=>{g(I=>{const q=new Set(I);return q.has(T)?q.delete(T):q.add(T),q})},[]),p=c.useCallback(()=>{f("all"),g(new Set)},[]),{threads:v,isLoading:b,isError:S,error:w,refetch:y,fetchNextPage:j,hasNextPage:E,isFetchingNextPage:M}=Pd(),{freeText:N,tokens:A}=_s(o.trim().toLowerCase(),l),L=c.useMemo(()=>{const T=Array.from(h).map(I=>MS[I]).filter(I=>I!=null);return RS(v).map(Vn).filter(I=>(d==="all"||I.category===d)&&T.every(q=>q(I))&&(!N||ad(I,N))&&Io(I,A))},[v,d,h,N,A]),O=c.useMemo(()=>Rg(),[]),D=c.useMemo(()=>L.map(T=>od(T,i)),[L,i]),R=c.useMemo(()=>L.filter(T=>!T.isRead).length,[L]),k=b?"loading":S?"error":L.length===0?"empty":"ready",P=c.useCallback(()=>{const T=za(_a());window.open(T,"_blank","noopener,noreferrer")},[]),F=jr(),C=r.jsx("div",{className:"flex h-full min-h-0 flex-col",children:r.jsxs("div",{className:"flex-1 overflow-y-auto",children:[r.jsx("div",{className:"divide-y divide-line",children:L.map(T=>r.jsx(Qn,{thread:T,active:T.id===e,onClick:()=>t?.(T.id)},T.id))}),E?r.jsx("button",{type:"button",className:"w-full py-3 text-sm text-muted hover:text-fg disabled:opacity-50",onClick:()=>j(),disabled:M,children:M?"Loading…":"Load more"}):null]})});return r.jsx(Ld,{title:"Starred",unreadCount:R,preset:O,selectedCategory:d,activeFilters:h,onSelectCategory:f,onToggleFilter:x,onClearFilters:p,searchResults:D,searchLoading:b,onSelectSearchResult:T=>t?.(T.id),children:r.jsxs(vd,{selectedMessageId:e,onOpen:(T,I)=>t?.(T,I),onDeleteMessages:a,onSelectionVerb:m.start,wizardOpen:m.isOpen,commandsRef:s,onTriageContextChange:n,children:[r.jsx(kc,{listTitle:"Starred",sections:[{id:"flagged",threads:L}],flatList:!0,hideHeader:!0,listState:F.searchResults?"ready":k,searchQuery:N?o:void 0,errorMessage:S?Wl(w):void 0,onRetry:()=>y(),onReportError:P,selectedThreadId:e,onSelectThread:t,onSelectBriefCategory:()=>{},isDesktop:u,selectionBar:r.jsx(lw,{title:"Starred"}),listBody:F.searchResults??(k==="ready"?C:void 0)}),r.jsx(AS,{rows:L,verb:m.verb})]})})}const Fd=c.createContext(null);function Er(){const e=c.useContext(Fd);if(!e)throw new Error("FlaggedPane.* must be used inside <FlaggedPane>");return e}function DS({selectedMessageId:e,children:t}){const s=He(),{threads:n}=Pd(),a=c.useMemo(()=>{if(e)return n.find(w=>w.messageId===e)},[n,e]),o=c.useCallback((w,y)=>{s({to:"/mail/flagged",search:j=>({...j,selectedMessageId:w}),replace:y?.replace})},[s]),i=c.useCallback(()=>{s({to:"/mail/flagged",search:w=>({...w,selectedMessageId:void 0})})},[s]),l=c.useCallback(w=>{e&&w.includes(e)&&i()},[e,i]),u=sn({thread:a,onAfterOptimisticRemove:l}),m=Do(),{deleteMessages:d}=as({mailboxId:a?.mailboxId??"",messages:n,onAfterOptimisticRemove:l}),{toggleReadFor:f}=yr({mailboxId:a?.mailboxId??"",messages:n}),h=m.focusedMessageId,x=c.useMemo(()=>n.find(w=>w.messageId===h),[n,h])??a,p=sn({thread:x}),{nextMessageId:v,previousMessageId:b}=Po({context:m,orderedIds:m.orderedIds,selectedMessageId:e,onClose:i,handlers:{reply:()=>u.requestCompose("reply"),replyAll:()=>u.requestCompose("reply_all"),forward:()=>u.requestCompose("forward"),delete:()=>{m.listCommandsRef.current?.requestVerb("delete")||p.deleteThread()},toggleStar:p.toggleStar,toggleRead:()=>{m.listCommandsRef.current?.requestVerb("markRead")||x&&f([x.messageId],!x.isRead)},goBrief:()=>s({to:"/mail"}),goSettings:()=>s({to:"/settings"})}}),S={selectedMessageId:e,selectedThread:a,onSelectMessage:o,onCloseThread:i,actions:u,triage:m,onDeleteMessages:d,nextMessageId:v,previousMessageId:b};return r.jsx(Fd.Provider,{value:S,children:t})}function $d(){const{selectedMessageId:e,onSelectMessage:t,triage:s,onDeleteMessages:n}=Er();return r.jsx(OS,{selectedMessageId:e,onSelectMessage:t,commandsRef:s.listCommandsRef,onTriageContextChange:s.onTriageContextChange,onDeleteMessages:n})}function PS(){const{selectedThread:e,actions:t}=Er(),{intelligenceOpen:s,onToggleIntelligence:n}=Me(),a=As()?.showIntelligencePane??!1,o=!!e,i=a&&o;return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(Oo,{hasThread:o,intelligenceOpen:i&&s,canToggleIntelligence:i,onToggleIntelligence:n,onReply:o?()=>t.requestCompose("reply"):void 0,onReplyAll:o?()=>t.requestCompose("reply_all"):void 0,onForward:o?()=>t.requestCompose("forward"):void 0,onDelete:o?t.deleteThread:void 0,onToggleStar:o?t.toggleStar:void 0,isStarred:t.isStarred,moveContext:o&&t.accountId&&t.mailboxId?{accountId:t.accountId,currentMailboxId:t.mailboxId,onMove:t.moveThread}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx($s,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,composeRequest:t.composeRequest,onComposeClose:t.clearComposeRequest}):r.jsx(Ls,{})})]})}function LS(){const{selectedThread:e}=Er(),{onToggleIntelligence:t}=Me();return r.jsx(zs,{onClose:t,thread:e,mailboxId:e?.mailboxId,accountId:e?.accountId})}function FS(){const{selectedThread:e,onCloseThread:t,onSelectMessage:s,nextMessageId:n,previousMessageId:a}=Er(),{intelligenceOpen:o,onToggleIntelligence:i}=Me();return e?r.jsxs(r.Fragment,{children:[r.jsx($s,{threadId:e.threadId,mailboxId:e.mailboxId,subject:e.subject,authenticity:e.authenticity,onBack:t,onOpenIntelligence:i,onSwipeNext:n?()=>s(n):void 0,onSwipePrevious:a?()=>s(a):void 0,mobileIntelligenceOpen:o}),r.jsx(mo,{isOpen:o,onClose:i,ariaLabel:"Message details",side:"right",children:r.jsx(zs,{onClose:i,thread:e,hideCloseButton:!0})})]}):r.jsx("div",{className:"h-full",children:r.jsx($d,{})})}const Vs=Object.assign(DS,{List:$d,Reading:PS,Intelligence:LS,Phone:FS}),$S={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},_S=()=>{const e=c.useRef(!1);return c.useCallback(()=>{const s=document.querySelector("[data-subject-field]")?.value??"",o=(document.querySelector("[data-slate-editor]")?.textContent??"").replace(/--\s*/g,"").trim();return e.current=s.trim().length>0||o.length>0,e.current},[])},zS=()=>{const{state:e,closeCompose:t}=Ht(),s=_S(),[n,a]=c.useState(!1),{isError:o,error:i,refetch:l}=ve({...Mt(),staleTime:1/0}),u=c.useCallback(h=>{h||(s()?a(!0):t())},[t,s]),m=c.useCallback(()=>{a(!1),t()},[t]),d=c.useCallback(()=>{a(!1)},[]);if(!e.isOpen)return null;const f=$S[e.mode]??"New Message";return r.jsxs(dt.Root,{open:e.isOpen,onOpenChange:u,children:[r.jsxs(dt.Portal,{children:[r.jsx(dt.Overlay,{className:"fixed inset-0 z-40 bg-black/40"}),r.jsxs(dt.Content,{className:"fixed inset-x-0 bottom-0 z-50 flex flex-col bg-canvas rounded-t-lg",style:{height:"95dvh"},children:[r.jsx(dt.Handle,{className:"mx-auto mt-2 mb-1 h-1.5 w-12 rounded-full bg-fg-muted/30"}),r.jsx(dt.Title,{className:"px-4 py-2 text-base font-semibold border-b border-line",children:f}),o?r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(Vt,{title:"Couldn't load compose",error:i,onRetry:()=>{l()}})}):r.jsx("div",{className:"flex-1 overflow-hidden",children:r.jsx(ho,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t})})]})]}),n&&r.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/50",children:r.jsxs("div",{className:"mx-4 w-full max-w-sm rounded-xl bg-canvas p-6 shadow-xl",children:[r.jsx("h3",{className:"text-lg font-semibold",children:"Discard draft?"}),r.jsx("p",{className:"mt-2 text-sm text-fg-muted",children:"Your message has unsaved content. Are you sure you want to discard it?"}),r.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[r.jsx("button",{type:"button",onClick:d,className:"rounded-md px-4 py-2 text-sm font-medium hover:bg-surface-raised transition-colors",children:"Keep editing"}),r.jsx("button",{type:"button",onClick:m,className:"rounded-md bg-danger px-4 py-2 text-sm font-medium text-canvas hover:bg-danger/90 transition-colors",children:"Discard"})]})]})})]})},BS={reply:"Reply",reply_all:"Reply All",forward:"Forward",new:"New Message"},_d=()=>{const{state:e,closeCompose:t}=Ht(),s=Wt(),{isError:n,error:a,refetch:o}=ve({...Mt(),staleTime:1/0});if(!s)return r.jsx(zS,{});if(!e.isOpen)return null;const i=BS[e.mode]??"New Message",l=r.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 py-3 border-b border-line shrink-0",children:[r.jsx("div",{className:"flex items-center gap-2 min-w-0",children:r.jsx("h2",{className:"text-lg font-semibold truncate",children:i})}),r.jsx("button",{type:"button",onClick:t,className:"p-2 rounded-md hover:bg-surface-raised transition-colors min-h-11 min-w-11 inline-flex items-center justify-center","aria-label":"Close",children:r.jsx(St,{className:"size-5"})})]});return n?r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[l,r.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:r.jsx(Vt,{title:"Couldn't load compose",error:a,onRetry:()=>{o()}})})]}):r.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-canvas",children:[l,r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:r.jsx(ho,{mode:e.mode,account:e.account,sourceMessage:e.sourceMessage,onClose:t},e.outboxMessageId??"new")})]})};function KS(e){const t=e.toAddresses.join(", ");return{id:e.outboxMessageId,accountId:e.accountId,fromName:e.fromName??e.fromAddress??"Me",fromEmail:e.fromAddress??"",subject:e.subject??"(No subject)",snippet:t?`To: ${t}`:"(No recipients)",timeLabel:pt(e.updatedAt),isRead:!0}}function US(e){return{id:e.messageId,accountId:e.accountId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:pt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0}}function qS({outboxMessages:e,accountId:t,imapThreads:s}){const n=e.filter(i=>i.status==="draft"&&i.accountId===t).map(KS),a=s.map(US),o=[];return n.length>0&&o.push({id:"remit-drafts",label:"Not yet sent (Remit)",threads:n}),a.length>0&&o.push({id:"imap-drafts",label:"On the server",threads:a}),o}function Lo(){const e=As();return!e||e.showNavPane?null:r.jsx(ae,{variant:"ghost",size:"sm",icon:r.jsx(Va,{className:"size-4"}),onClick:e.openNav,"aria-label":"Open folders",className:"-ml-1 shrink-0"})}const HS=({label:e,count:t})=>r.jsxs("div",{className:"sticky top-0 z-10 flex items-baseline justify-between border-b border-line bg-surface-sunken px-row-inset py-1",children:[r.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wider text-fg-subtle",children:e}),r.jsx("span",{className:"text-2xs text-fg-subtle tabular-nums",children:t})]}),WS=({row:e,isSelected:t,onOpen:s,onDelete:n,isDeleting:a})=>r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:V("group",Ps({active:t})),children:[r.jsx(Tl,{className:"size-7 shrink-0 text-fg-muted mt-0.5"}),r.jsx(Zs,{thread:e}),r.jsx("div",{className:"flex items-center gap-1 shrink-0",children:r.jsx("button",{type:"button",onClick:o=>{o.stopPropagation(),n(e.id)},disabled:a,className:"p-1.5 rounded-md text-fg-muted hover:text-danger hover:bg-surface-raised transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100",title:"Delete draft",children:r.jsx(Rt,{className:"size-3.5"})})})]}),VS=({row:e,isSelected:t,onOpen:s})=>{const n=!e.isRead;return r.jsxs("button",{type:"button",onClick:()=>s(e.id),className:V("group",Ps({active:t})),children:[n&&r.jsx("span",{className:"absolute left-1.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full bg-accent"}),r.jsx(wt,{name:e.fromName,email:e.fromEmail,size:"sm"}),r.jsx(Zs,{thread:e})]})};function QS({mailboxId:e,accountId:t,selectedMessageId:s,imapThreads:n,title:a,unreadCount:o}){const{openCompose:i,state:l}=Ht(),u=He(),m=Re(),{data:d}=ve(er()),f=c.useMemo(()=>qS({outboxMessages:d?.items??[],accountId:t,imapThreads:n}),[d?.items,t,n]),h=Oe({...sr(),onSuccess:()=>{m.invalidateQueries({queryKey:Wa()})}}),g=b=>{h.mutate({path:{outboxMessageId:b}})},x=b=>{s&&u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:void 0}}),i({mode:"new",outboxMessageId:b})},p=b=>{u({to:"/mail/$mailboxId",params:{mailboxId:e},search:{selectedMessageId:b}})},v=f.length===0;return r.jsxs("section",{className:"flex h-full w-full flex-col bg-surface",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx(Lo,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:a}),(o??0)>0&&r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle tabular-nums",children:[o," unread"]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto",children:v?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-2 text-center px-4",children:[r.jsx(Aa,{className:"size-8 text-fg-subtle"}),r.jsx("p",{className:"text-sm font-medium text-fg",children:"No drafts"}),r.jsx("p",{className:"text-xs text-fg-subtle",children:"Messages you start composing will appear here."})]}):f.map(b=>r.jsxs("div",{children:[b.label&&r.jsx(HS,{label:b.label,count:b.threads.length}),r.jsx("div",{className:"divide-y divide-line",children:b.threads.map(S=>b.id==="remit-drafts"?r.jsx(WS,{row:S,isSelected:l.isOpen&&S.id===l.outboxMessageId,onOpen:x,onDelete:g,isDeleting:h.isPending},S.id):r.jsx(VS,{row:S,isSelected:S.id===s,onOpen:p},S.id))})]},b.id))})]})}function GS(e,t,s){const n=new Array(e);return new Proxy(n,{get(a,o,i){if(typeof o=="string"){const l=o.charCodeAt(0);if(l>=48&&l<=57){const u=+o;if(Number.isInteger(u)&&u>=0&&u<e){let m=a[u];if(!m){const d=t[u*2];m=a[u]={index:u,key:s(u),start:d,size:t[u*2+1],end:d+t[u*2+1],lane:0}}return m}}if(o==="length")return e}return Reflect.get(a,o,i)}})}function vs(e,t,s){let n=s.initialDeps??[],a,o=!0;function i(){const l=e();return(l.length!==n.length||l.some((m,d)=>n[d]!==m))&&(n=l,a=t(...l),s?.onChange&&!(o&&s.skipInitialOnChange)&&s.onChange(a),o=!1),a}return i.updateDeps=l=>{n=l},i}function xl(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const YS=(e,t)=>Math.abs(e-t)<1.01,XS=(e,t,s)=>{let n;return function(...a){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,a),s)}};let Qs;const aa=()=>{if(Qs!==void 0)return Qs;if(typeof navigator>"u")return Qs=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Qs=!0;const e=navigator.maxTouchPoints;return Qs=navigator.platform==="MacIntel"&&e!==void 0&&e>0},bl=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},JS=e=>e,ZS=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,a=new Array(n);for(let o=0;o<n;o++)a[o]=t+o;return a},ek=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const a=i=>{const{width:l,height:u}=i;t({width:Math.round(l),height:Math.round(u)})};if(a(bl(s)),!n.ResizeObserver)return()=>{};const o=new n.ResizeObserver(i=>{const l=()=>{const u=i[0];if(u?.borderBoxSize){const m=u.borderBoxSize[0];if(m){a({width:m.inlineSize,height:m.blockSize});return}}a(bl(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return o.observe(s,{box:"border-box"}),()=>{o.unobserve(s)}},Gn={passive:!0},tk=typeof window>"u"?!0:"onscrollend"in window,sk=(e,t,s)=>{const n=e.scrollElement;if(!n)return;const a=e.targetWindow;if(!a)return;const o=e.options.useScrollendEvent&&tk;let i=0;const l=o?null:XS(a,()=>t(i,!1),e.options.isScrollingResetDelay),u=f=>()=>{i=s(n),l?.(),t(i,f)},m=u(!0),d=u(!1);return n.addEventListener("scroll",m,Gn),o&&n.addEventListener("scrollend",d,Gn),()=>{n.removeEventListener("scroll",m),o&&n.removeEventListener("scrollend",d)}},nk=(e,t)=>sk(e,t,s=>{const{horizontal:n,isRtl:a}=e.options;return n?s.scrollLeft*(a&&-1||1):s.scrollTop}),rk=(e,t,s)=>{if(s.options.useCachedMeasurements){const n=s.indexFromElement(e),a=s.options.getItemKey(n);return s.itemSizeCache.get(a)??s.options.estimateSize(n)}if(t?.borderBoxSize){const n=t.borderBoxSize[0];if(n)return Math.round(n[s.options.horizontal?"inlineSize":"blockSize"])}if(!t){const n=s.indexFromElement(e),a=s.options.getItemKey(n),o=s.itemSizeCache.get(a);if(o!==void 0)return o}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},ak=(e,{adjustments:t=0,behavior:s},n)=>{var a,o;(o=(a=n.scrollElement)==null?void 0:a.scrollTo)==null||o.call(a,{[n.options.horizontal?"left":"top"]:e+t,behavior:s})},ok=ak;class ik{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var s,n,a;return((a=(n=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:n.now)==null?void 0:a.call(n))??Date.now()},this.observer=(()=>{let s=null;const n=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(a=>{a.forEach(o=>{const i=()=>{const l=o.target,u=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[m,d]of this.elementsCache)if(d===l){this.elementsCache.delete(m);break}return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(l,o,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var a;(a=n())==null||a.disconnect(),s=null},observe:a=>{var o;return(o=n())==null?void 0:o.observe(a,{box:"border-box"})},unobserve:a=>{var o;return(o=n())==null?void 0:o.unobserve(a)}}})(),this.range=null,this.setOptions=s=>{var n,a;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:JS,rangeExtractor:ZS,onChange:()=>{},measureElement:rk,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const h in s){const g=s[h];g!==void 0&&(o[h]=g)}const i=this.options;let l=null,u=null,m=!1;if(i!==void 0&&i.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const h=i.count,g=o.count,x=this.getMeasurements(),p=h>0?((n=x[0])==null?void 0:n.key)??i.getItemKey(0):null,v=h>0?((a=x[h-1])==null?void 0:a.key)??i.getItemKey(h-1):null;if(g!==h||h>0&&g>0&&(o.getItemKey(0)!==p||o.getItemKey(g-1)!==v)){m=!0;const w=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??x[0]:null;w&&(l=[w.key,this.getScrollOffset()-w.start]);const y=o.followOnAppend===!0?"auto":o.followOnAppend||null;y&&g>h&&this.isAtEnd(i.scrollEndThreshold)&&(h===0||o.getItemKey(g-1)!==v)&&(u=y)}}this.options=o,m&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,f=0;if(l&&this.scrollOffset!==null){const[h,g]=l,x=this.getMeasurements(),{count:p,getItemKey:v}=this.options;let b=0;for(;b<p&&v(b)!==h;)b++;if(b<p){const S=x[b];if(S){const w=S.start+g;w!==this.scrollOffset&&(f=w-this.scrollOffset,this.scrollOffset=w,d=!0)}}}(d||u)&&(this.pendingScrollAnchor=[d?l[0]:null,d?l[1]:0,u,f])},this.notify=s=>{var n,a;(a=(n=this.options).onChange)==null||a.call(n,this,s)},this.maybeNotify=vs(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}if(this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,i)=>{if(i&&this._intendedScrollOffset===null&&o===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(o-this._intendedScrollOffset)<1.5&&(o=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=i?l===o?this.scrollDirection:l<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const o=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!aa()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};o.addEventListener("touchstart",i,Gn),o.addEventListener("touchend",l,Gn),this.unsubs.push(()=>{o.removeEventListener("touchstart",i),o.removeEventListener("touchend",l),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const a=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,a&&this.scrollElement&&this.options.enabled){const[o,i,l,u]=a;o!==null&&!l&&(aa()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?u!==0&&(this._iosDeferredAdjustment+=u):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const s=this.getScrollOffset(),n=this.getMaxScrollOffset();if(s<0||s>n)return;const a=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(s,{adjustments:this.scrollAdjustments+=a,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=vs(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(s,n,a,o,i,l,u,m)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:m}),{key:!1}),this.getMeasurements=vs(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:s,paddingStart:n,scrollMargin:a,getItemKey:o,enabled:i,lanes:l,laneAssignmentMode:u,gap:m},d)=>{const f=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const b of this.laneAssignments.keys())b>=s&&this.laneAssignments.delete(b);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(b=>{this.itemSizeCache.set(b.key,b.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1),l===1){const b=s*2;let S=this._flatMeasurements;if(!S||S.length<b){const j=new Float64Array(b);S&&h>0&&j.set(S.subarray(0,h*2)),S=j,this._flatMeasurements=S}let w;if(h===0)w=n+a;else{const j=h-1;w=S[j*2]+S[j*2+1]+m}for(let j=h;j<s;j++){const E=o(j),M=f.get(E),N=typeof M=="number"?M:this.options.estimateSize(j);S[j*2]=w,S[j*2+1]=N,w+=N+m}const y=GS(s,S,o);return this.measurementsCache=y,y}const g=this.measurementsCache.slice(0,h),x=new Array(l).fill(void 0),p=new Float64Array(l);let v=0;for(let b=0;b<h;b++){const S=g[b];S&&(x[S.lane]===void 0&&v++,x[S.lane]=b,p[S.lane]=S.end)}for(let b=h;b<s;b++){const S=o(b),w=this.laneAssignments.get(b);let y,j;const E=u==="estimate"||f.has(S);if(w!==void 0&&this.options.lanes>1){y=w;const L=x[y],O=L!==void 0?g[L]:void 0;j=O?O.end+m:n+a}else if(v===l){let L=0,O=p[0],D=x[0];for(let R=1;R<l;R++){const k=p[R];(k<O||k===O&&x[R]<D)&&(L=R,O=k,D=x[R])}y=L,j=O+m,E&&this.laneAssignments.set(b,y)}else y=b%this.options.lanes,j=n+a,E&&this.laneAssignments.set(b,y);const M=f.get(S),N=typeof M=="number"?M:this.options.estimateSize(b),A=j+N;g[b]={index:b,start:j,size:N,end:A,key:S,lane:y},x[y]===void 0&&v++,x[y]=b,p[y]=A}return this.measurementsCache=g,g},{key:!1,debug:()=>this.options.debug}),this.calculateRange=vs(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,a,o)=>s.length===0||n===0?(this.range=null,null):(this.range=ck(s,n,a,o,o===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=vs(()=>{let s=null,n=null;const a=this.calculateRange();return a&&(s=a.startIndex,n=a.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,a,o,i)=>o===null||i===null?[]:s({startIndex:o,endIndex:i,overscan:n,count:a}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,a=s.getAttribute(n);return a?parseInt(a,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const a=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(a!==void 0&&this.range){const o=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,a-o),l=Math.min(this.options.count-1,a+o);return s>=i&&s<=l}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((i,l)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(l))});return}const n=this.indexFromElement(s),a=this.options.getItemKey(n),o=this.elementsCache.get(a);o!==s&&(o&&this.observer.unobserve(o),this.observer.observe(s),this.elementsCache.set(a,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,n)=>{var a,o;if(s<0||s>=this.options.count)return;let i,l,u;const m=this._flatMeasurements;if(this.options.lanes===1&&m!==null)u=this.options.getItemKey(s),l=m[s*2],i=m[s*2+1];else{const h=this.measurementsCache[s];if(!h)return;u=h.key,l=h.start,i=h.size}const d=this.itemSizeCache.get(u)??i,f=n-d;if(f!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,g=h?this.getTotalSize():0,x=((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[s]??{index:s,key:u,start:l,size:i,end:l+i,lane:0},f,this):l<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(u)||this.scrollDirection!=="backward"));(this.pendingMin===null||s<this.pendingMin)&&(this.pendingMin=s),this.itemSizeCache.set(u,n),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-g):x&&this.applyScrollAdjustment(f),this.notify(!1)}},this.getVirtualItems=vs(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const a=[];for(let o=0,i=s.length;o<i;o++){const l=s[o],u=n[l];a.push(u)}return a},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const n=this.getMeasurements();if(n.length===0)return;const a=this._flatMeasurements,o=this.options.lanes===1&&a!=null,i=zd(0,n.length-1,o?l=>a[l*2]:l=>xl(n[l]).start,s);return xl(n[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(s=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=s,this.getOffsetForAlignment=(s,n,a=0)=>{if(!this.scrollElement)return 0;const o=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=s>=i+o?"end":"start"),n==="center"?s+=(a-o)/2:n==="end"&&(s-=o);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,s),0)},this.getOffsetForIndex=(s,n="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const a=this.getSize(),o=this.getScrollOffset(),i=this.measurementsCache[s];if(!i)return;if(n==="auto")if(i.end>=o+a-this.options.scrollPaddingEnd)n="end";else if(i.start<=o+this.options.scrollPaddingStart)n="start";else return[o,n];if(n==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),n];const l=n==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,n,i.size),n]},this.scrollToOffset=(s,{align:n="start",behavior:a="auto"}={})=>{const o=this.getOffsetForAlignment(s,n),i=this.now();this.scrollState={index:null,align:n,behavior:a,startedAt:i,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:n="auto",behavior:a="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getOffsetForIndex(s,n);if(!o)return;const[i,l]=o,u=this.now();this.scrollState={index:s,align:l,behavior:a,startedAt:u,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:a}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:n="auto"}={})=>{const a=this.getScrollOffset()+s,o=this.now();this.scrollState={index:null,align:"start",behavior:n,startedAt:o,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:s="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:s});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:s})},this.getTotalSize=()=>{var s;const n=this.getMeasurements();let a;if(n.length===0)a=this.options.paddingStart;else if(this.options.lanes===1){const o=n.length-1,i=this._flatMeasurements;i!=null?a=i[o*2]+i[o*2+1]:a=((s=n[o])==null?void 0:s.end)??0}else{const o=Array(this.options.lanes).fill(null);let i=n.length-1;for(;i>=0&&o.some(l=>l===null);){const l=n[i];o[l.lane]===null&&(o[l.lane]=l.end),i--}a=Math.max(...o.filter(l=>l!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const s=[];if(this.itemSizeCache.size===0)return s;const n=this.getMeasurements();for(const a of n)a&&this.itemSizeCache.has(a.key)&&s.push({index:a.index,key:a.key,start:a.start,size:a.size,end:a.end,lane:a.lane});return s},this._scrollToOffset=(s,{adjustments:n,behavior:a})=>{this._intendedScrollOffset=s+(n??0),this.options.scrollToFn(s,{behavior:a,adjustments:n},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,s){t!==0&&(aa()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:s}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const n=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,a=n?n[0]:this.scrollState.lastTargetOffset,o=1,i=a!==this.scrollState.lastTargetOffset;if(!i&&YS(a,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=o){this.getScrollOffset()!==a&&this._scrollToOffset(a,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,u=Math.abs(a-this.getScrollOffset()),m=this.scrollState.behavior==="smooth"&&u>l;this.scrollState.lastTargetOffset=a,m||(this.scrollState.behavior="auto"),this._scrollToOffset(a,{adjustments:void 0,behavior:m?"smooth":"auto"})}this.scheduleScrollReconcile()}}const zd=(e,t,s,n)=>{for(;e<=t;){const a=(e+t)/2|0,o=s(a);if(o<n)e=a+1;else if(o>n)t=a-1;else return a}return e>0?e-1:0};function lk(e,t,s){let n=0;for(;n<=t;){const a=(n+t)/2|0,o=e[a*2];if(o<s)n=a+1;else if(o>s)t=a-1;else return a}return n>0?n-1:0}function ck(e,t,s,n,a){const o=e.length-1;if(e.length<=n)return{startIndex:0,endIndex:o};if(n===1&&a!==null){const m=lk(a,o,s);let d=m;const f=s+t;for(;d<o&&a[d*2]+a[d*2+1]<f;)d++;return{startIndex:m,endIndex:d}}let l=zd(0,o,m=>e[m].start,s),u=l;if(n===1)for(;u<o&&e[u].end<s+t;)u++;else if(n>1){const m=Array(n).fill(0);for(;u<o&&m.some(f=>f<s+t);){const f=e[u];m[f.lane]=f.end,u++}const d=Array(n).fill(s+t);for(;l>=0&&d.some(f=>f>=s);){const f=e[l];d[f.lane]=f.start,l--}l=Math.max(0,l-l%n),u=Math.min(o,u+(n-1-u%n))}return{startIndex:l,endIndex:u}}const oa=typeof document<"u"?c.useLayoutEffect:c.useEffect;function uk({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:s="transform",...n}){const a=c.useReducer(m=>m+1,0)[1],o=c.useRef({enabled:t,mode:s,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=s;const i=m=>{const d=o.current;if(!d.enabled||!d.container)return;const f=m.getTotalSize();if(f!==d.lastSize){d.lastSize=f;const b=m.options.horizontal?"width":"height";d.container.style[b]=`${f}px`}const h=!!m.options.horizontal,g=d.mode==="transform",x=h?"left":"top",p=m.options.scrollMargin,v=m.getVirtualItems();for(const b of v){const S=b.start-p,w=m.elementsCache.get(b.key);w&&d.lastPositions.get(w)!==S&&(d.lastPositions.set(w,S),g?w.style.transform=h?`translate3d(${S}px, 0, 0)`:`translate3d(0, ${S}px, 0)`:w.style[x]=`${S}px`)}},l={...n,onChange:(m,d)=>{var f;const h=o.current;let g=!0;if(h.enabled){i(m);const x=m.range,p=h.prevRange;g=!p||p.isScrolling!==m.isScrolling||p.startIndex!==x?.startIndex||p.endIndex!==x?.endIndex,g&&(h.prevRange=x?{startIndex:x.startIndex,endIndex:x.endIndex,isScrolling:m.isScrolling}:null)}g&&(e&&d?Pa.flushSync(a):a()),(f=n.onChange)==null||f.call(n,m,d)}},[u]=c.useState(()=>{const m=new ik(l);return Object.assign(m,{containerRef:d=>{const f=o.current;if(f.container=d,f.lastSize=null,d&&f.enabled){const h=m.getTotalSize();f.lastSize=h;const g=m.options.horizontal?"width":"height";d.style[g]=`${h}px`}}})});return u.setOptions(l),oa(()=>u._didMount(),[]),oa(()=>u._willUpdate()),oa(()=>{i(u)}),u}function dk(e){return uk({observeElementRect:ek,observeElementOffset:nk,scrollToFn:ok,...e})}const Fo=e=>e.query?`matching "${e.query}"`:e.from?`from "${e.from}"`:"matching your search",fk=e=>`Select all ${Fo(e)}`,mk=(e,t)=>`All ${ss(t)} ${Fo(e)} selected`,hk=(e,t)=>({id:e.messageId,accountId:e.accountId,mailboxId:e.mailboxId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:pt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:wr(e.category),messageCount:t,suspicious:e.authenticity?.dkimMismatch===!0,labels:e.labels}),pk=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,messageCount:m,isMultiSelectMode:d,onLongPress:f,isDesktop:h,density:g})=>r.jsx(Qn,{thread:hk(e,m),linkMailboxId:t,inListbox:!0,active:s,focused:n,isTabStop:a,density:g,isDesktop:h,onFocusRow:o,selection:{isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:d,onLongPress:f}}),gk=c.memo(pk),xk=e=>{const t=e.authenticity?.dkimMismatch===!0;return{id:e.messageId,accountId:e.accountId,fromName:e.fromName??e.fromEmail??"Unknown",fromEmail:e.fromEmail??"",subject:e.subject??"(No subject)",snippet:e.snippet??"",timeLabel:pt(e.sentDate),isRead:e.isRead,hasAttachment:e.hasAttachment,starred:e.hasStars===!0,trust:e.senderTrust,category:wr(e.category),suspicious:t}},bk=({thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:m,onLongPress:d,isDesktop:f,onDelete:h,onToggleRead:g,density:x})=>{const[p,v]=c.useState("none"),b=c.useCallback(j=>{navigator.vibrate?.(10),j==="trailing"?h(e.messageId):g(e.messageId,e.isRead),v("none")},[h,g,e.messageId,e.isRead]),S=c.useCallback(()=>{d(e.messageId)},[d,e.messageId]),w=c.useCallback(()=>{l(e.messageId)},[l,e.messageId]),y=yd(e.messageId,u);return f||m?r.jsx(gk,{thread:e,mailboxId:t,isSelected:s,isFocused:n,isTabStop:a,onFocusRow:o,isChecked:i,onToggleCheck:l,onRowSelect:u,isMultiSelectMode:m,onLongPress:d,isDesktop:f,density:x}):r.jsx(Sc,{thread:xk(e),selectionMode:!1,checked:!1,active:s,peek:p,onPeek:v,onToggleCheck:w,onLongPress:S,onOpen:()=>{},onAct:b,linkComponent:({onOpenClick:j,children:E,...M})=>r.jsx(Et,{...M,to:"/mail/$mailboxId",params:{mailboxId:t},search:N=>({...N,selectedMessageId:e.messageId}),"data-message-row":!0,onMouseDown:y.onMouseDown,onContextMenu:y.onContextMenu,onClick:N=>{y.claimClick(N)||j(N)},children:E})})},vk=72,yk=32,wk=5,Bd="remit:list-density",Sk=()=>{try{const e=localStorage.getItem(Bd);if(e==="compact"||e==="comfortable")return e}catch{}return"comfortable"},kk=({query:e})=>r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line bg-surface-sunken/30",children:[r.jsx(Jn,{className:"size-4 text-fg-muted"}),r.jsxs("span",{className:"text-sm text-fg-muted",children:["Results for “",e,"”"]})]}),Ck=({mailboxId:e,threads:t,selectedMessageId:s,isLoading:n,isError:a=!1,error:o,onRetry:i,searchQuery:l,searchPredicate:u,onDeleteMessages:m,isDeleting:d=!1,isMoving:f=!1,onLoadMore:h,hasMore:g=!1,isLoadingMore:x=!1,accountId:p,listTitle:v,listMeta:b,listFilter:S,listScopeLabel:w,onTriageContextChange:y,commandsRef:j,hideHeader:E=!1})=>{const M=c.useRef(null),N=He(),A=Wt(),L=Ha(),{verb:O,start:D,startFromSearch:R}=L,k=dm(),P=!!l?.trim(),F=jr(),{labels:C}=Ya(p),[T,I]=c.useState(s),[q,se]=c.useState(),G=c.useCallback(B=>{se(te=>te===B?te:void 0),I(B)},[]),[oe,ne]=c.useState(Sk),Z=c.useCallback(()=>{ne(B=>{const te=B==="comfortable"?"compact":"comfortable";try{localStorage.setItem(Bd,te)}catch{}return te})},[]),{toggleReadFor:pe}=yr({mailboxId:e}),{junkMailboxId:me}=Fs(p),{selectedIds:Q,selectedCount:H,hasSelection:de,isSelected:ee,toggle:fe,select:U,clearSelection:_,selectRange:z,setAnchor:ce,selectAll:be,toggleAll:Ke,intersectWith:ge}=gd(),ie=xd(H,A),[Ae,we]=c.useState(null),Ne=P&&!!u,ft=`${e}|${JSON.stringify(u??{})}`,Y=kd({mailboxId:e,accountId:p,enabled:Ne,predicateKey:ft,searchQuery:u??{}}),Ee=Y.phase.kind,ue=Y.clear,ke=c.useCallback(()=>{Ee==="escalated"&&ue(),_()},[_,ue,Ee]),[et,ct]=c.useState(null),Ye=c.useRef(null),Ie=c.useRef(!1),De=c.useRef(null),We=!n&&t.length>0,Xe=Ae!==null,Ue=dk({count:t.length,getScrollElement:()=>M.current,estimateSize:()=>oe==="compact"?yk:vk,overscan:wk}),tt=s?t.findIndex(B=>B.messageId===s):-1,Se=T?t.findIndex(B=>B.messageId===T):-1,W=c.useCallback(B=>{if(B<0||B>=t.length)return;const te=t[B];if(ie){fe(te.messageId);return}Ye.current=te.messageId,Ie.current=!1,se(te.messageId),I(te.messageId)},[t,ie,fe]),re=c.useCallback(()=>{if(t.length===0)return;const B=Se<0?0:Math.min(Se+1,t.length-1);W(B)},[t.length,Se,W]),he=c.useCallback(()=>{if(t.length===0)return;const B=Se<=0?0:Se-1;W(B)},[t.length,Se,W]),le=c.useCallback(()=>W(0),[W]),ye=c.useCallback(()=>W(t.length-1),[W,t.length]),Ce=c.useCallback(()=>{T&&fe(T)},[T,fe]),xe=c.useMemo(()=>t.map(B=>B.messageId),[t]),Ve=c.useMemo(()=>{const B=[];for(const te of t)Q.has(te.messageId)&&B.push({id:te.messageId,sender:te.fromName??te.fromEmail??"Unknown",email:te.fromEmail??"",subject:te.subject??"(No subject)",date:pt(te.sentDate)});return B},[t,Q]),Pe=c.useCallback((B,te)=>te.shiftKey?(z(xe,B,T),!0):te.metaKey||te.ctrlKey?(fe(B),!0):(ke(),ce(B),!1),[xe,T,z,fe,ke,ce]),Je=c.useCallback(B=>{!m||B.length===0||(De.current=T??null,we(B))},[m,T]),_e=c.useCallback(B=>{const te=pd(xe,T,B);te!==void 0&&(z(xe,te),Ye.current=te,Ie.current=!1,se(void 0),I(te))},[xe,T,z]),Le=c.useCallback(()=>_e(-1),[_e]),st=c.useCallback(()=>_e(1),[_e]),Qe=c.useCallback(()=>{xe.length>0&&be(xe)},[xe,be]),Gt=c.useCallback(B=>Ae!==null?!0:de?(D(B),!0):B!=="delete"||!m||!T?!1:(Je([T]),!0),[Ae,m,de,D,T,Je]),ds=c.useCallback(()=>{T&&N({to:"/mail/$mailboxId",params:{mailboxId:e},search:B=>({...B,selectedMessageId:T})})},[T,N,e]),fs=c.useCallback(B=>{N({to:"/mail/$mailboxId",params:{mailboxId:e},search:te=>({...te,selectedMessageId:B}),replace:!0})},[N,e]);hd({keyboardFocusedMessageId:q,openMessageId:s,enabled:A&&H===0,open:fs});const kt=Y.phase.kind==="escalated"?{scope:Fo(u??{}),total:Y.phase.total,searchQuery:u??{},run:B=>Y.runAction(B)}:void 0,nt=c.useCallback(()=>{if(!Ae)return;const B=Ae;if(B.length===0){we(null);return}const te=new Set(B),wn=t.findIndex(Ge=>te.has(Ge.messageId));let jt;for(let Ge=wn+1;Ge<t.length;Ge++)if(!te.has(t[Ge].messageId)){jt=t[Ge].messageId;break}if(jt===void 0){for(let Ge=wn-1;Ge>=0;Ge--)if(!te.has(t[Ge].messageId)){jt=t[Ge].messageId;break}}m?.(B),ke(),De.current=null,we(null),jt!==void 0&&(Ye.current=jt,Ie.current=!1,G(jt),A&&N({to:"/mail/$mailboxId",params:{mailboxId:e},search:Ge=>({...Ge,selectedMessageId:jt}),replace:!0})),A||ct(kw("delete",B.length))},[Ae,t,m,ke,N,e,A,G]),Yt=c.useCallback(()=>{const B=De.current;De.current=null,we(null),B!==null&&(Ye.current=B,Ie.current=!1,G(B))},[G]),ut=c.useMemo(()=>{if(H===0)return;const B=new Set;for(const te of t)Q.has(te.messageId)&&B.add(te.accountConfigId);if(B.size>1)return"Move only works within one account — clear selection or pick messages from a single account"},[H,Q,t]),$=c.useCallback(()=>{if(kt){R();return}D("organize")},[kt,R,D]),J=c.useCallback(B=>{m?.([B])},[m]),qe=c.useCallback((B,te)=>{pe([B],!te)},[pe]),mt=c.useCallback(B=>{A||U(B)},[A,U]),Ze=c.useCallback(()=>{if(Y.isRunning||Y.phase.kind==="counting"){Y.stop();return}ke()},[Y,ke]),bt=c.useCallback(()=>{Y.clear()},[Y]);c.useEffect(()=>{if(Ie.current||!A&&s)return;const B=Se>=0?Se:tt;B>=0&&Ue.scrollToIndex(B,{align:"auto"})},[Se,tt,Ue,A,s]),c.useEffect(()=>{s&&(Ie.current=!1,G(s))},[s,G]),c.useEffect(()=>{T&&(t.some(B=>B.messageId===T)||G(t[0]?.messageId))},[t,T,G]),c.useEffect(()=>{y?.({focusedMessageId:T,selectedIds:Array.from(Q),hasList:We,blocksKeyboard:Xe||L.isOpen})},[T,Q,We,Xe,L.isOpen,y]);const gn=c.useRef(y);gn.current=y,c.useEffect(()=>()=>gn.current?.({focusedMessageId:void 0,selectedIds:[],hasList:!1,blocksKeyboard:!1}),[]),c.useEffect(()=>{Y.phase.kind!=="idle"||Y.isRunning||ge(t.map(B=>B.messageId))},[t,ge,Y.phase,Y.isRunning]);const xn=c.useRef(e);c.useEffect(()=>{xn.current!==e&&(xn.current=e,ke())},[e,ke]),Xc({shouldBlockFn:({action:B})=>tw(B,de,k)?(ke(),!0):!1,enableBeforeUnload:!1,disabled:!de||k!==void 0}),c.useEffect(()=>{const B=M.current;if(!B||!g||!h)return;const te=()=>{if(x)return;const{scrollTop:wn,scrollHeight:jt,clientHeight:Ge}=B;wn+Ge>=jt-200&&h()};return B.addEventListener("scroll",te,{passive:!0}),te(),()=>B.removeEventListener("scroll",te)},[g,x,h]),c.useEffect(()=>{const B=Ye.current;if(!B)return;const te=M.current?.querySelector(`[data-message-id="${B}"]`);te&&(Ye.current=null,te.focus({preventScroll:!0}))}),c.useEffect(()=>{if(j){if(!We){j.current=null;return}return j.current={focusNext:re,focusPrevious:he,focusFirst:le,focusLast:ye,openFocused:ds,toggleSelect:Ce,extendSelectDown:st,extendSelectUp:Le,selectAll:Qe,clearSelection:()=>de?(ke(),!0):!1,requestVerb:Gt,toggleDensity:Z},()=>{j.current=null}}},[j,We,re,he,le,ye,ds,Ce,st,Le,Qe,de,ke,Gt,Z]);const bn=n?"loading":a?"error":t.length===0?"empty":"ready",Tr=a?Wl(o):void 0,Rr=c.useCallback(()=>{const B=za(_a());window.open(B,"_blank","noopener,noreferrer")},[]),Mr=[{id:"inbox",threads:[]}],Ct=xe.length>0&&xe.every(B=>Q.has(B)),vn=Ne&&g&&Ct&&!d&&!f&&Y.phase.kind==="idle"&&!Y.isRunning,yn=d||f||Y.isRunning,Ar=Y.phase.kind==="escalated"?Y.phase.total:H,Or=Y.runningAction?Sw(Y.runningAction.kind,Y.progress?.done??0,Y.progress?.total??0):Y.phase.kind==="counting"?Y.phase.countSoFar>=5e3?`Counting… ${ss(Y.phase.countSoFar)} so far. This is a big result set.`:`Counting… ${ss(Y.phase.countSoFar)} so far`:Y.phase.kind==="escalated"?mk(u??{},Y.phase.total):void 0,Dr=Y.phase.kind!=="escalated"&&xe.length>0?{checked:Ct,indeterminate:H>0&&!Ct,onChange:()=>Ke(xe)}:void 0,Pr=Y.runningAction&&Y.progress?{value:Y.progress.done,max:Y.progress.total,tone:Nw(Y.runningAction.kind)}:void 0,X=(Y.phase.kind==="counting"?{tone:"info",text:"",action:{label:"Stop",onClick:Y.stop}}:Y.phase.kind==="escalated"&&!Y.isRunning?{tone:"info",text:"",action:{label:"Clear selection",onClick:bt}}:vn?{tone:"info",text:"",action:{label:fk(u??{}),onClick:Y.escalate}}:void 0)??(ut?{tone:"warning",text:ut}:void 0),rt=r.jsx(dr,{title:F.title||v,navSlot:F.navSlot,titleMeta:F.titleMeta,searchSlot:F.searchSlot,searchField:F.searchField,idleSlot:F.makeFilterSlot,count:Ar,onCancel:Ze,onDelete:()=>D("delete"),onMove:()=>D("move"),onOrganize:$,onJunk:me&&me!==e?()=>D("junk"):void 0,onMarkRead:()=>D("markRead"),overflowSlot:p&&e&&H>0&&C.length>0?r.jsx(ld,{accountId:p,mailboxId:e,messageIds:Array.from(Q)}):void 0,isBusy:yn,isCounting:Y.phase.kind==="counting",selectAll:Dr,statusLabel:Or,progress:Pr,notice:X}),at=bd(xe,T),Zd=c.useCallback(B=>{Ie.current=!0,G(B)},[G]),ef=r.jsxs(r.Fragment,{children:[P&&l&&r.jsx(kk,{query:l}),r.jsxs("div",{ref:M,role:"listbox","aria-multiselectable":!0,"aria-label":v,className:"flex-1 overflow-y-auto",children:[r.jsx("div",{role:"presentation",className:"relative w-full",style:{height:`${Ue.getTotalSize()}px`},children:Ue.getVirtualItems().map(B=>{const te=t[B.index];return r.jsx("div",{role:"presentation","data-index":B.index,ref:Ue.measureElement,className:$e("absolute left-0 top-0 w-full border-b border-line",Y.isRunning&&"pointer-events-none opacity-50"),style:{transform:`translateY(${B.start}px)`},children:r.jsx(bk,{thread:te,mailboxId:e,isSelected:s===te.messageId,isFocused:T===te.messageId,isTabStop:at===te.messageId,onFocusRow:Zd,isChecked:ee(te.messageId),onToggleCheck:fe,onRowSelect:Pe,isMultiSelectMode:ie,onLongPress:mt,isDesktop:A,onDelete:J,onToggleRead:qe,density:oe})},B.key)})}),x&&r.jsx(Wh,{})]})]});return r.jsxs(r.Fragment,{children:[et&&!A&&r.jsx(rn,{tone:"success",variant:"soft",className:"m-2 rounded-md",onDismiss:()=>ct(null),children:et}),r.jsx(kc,{listTitle:v,listMeta:b,sections:Mr,flatList:!0,listState:F.searchResults?"ready":bn,searchQuery:P?l:void 0,listFilter:S,listScopeLabel:w,errorMessage:Tr,onRetry:i,onReportError:Rr,density:oe,selectedThreadId:s,onSelectThread:B=>N({to:"/mail/$mailboxId",params:{mailboxId:e},search:te=>({...te,selectedMessageId:B})}),onSelectBriefCategory:()=>{},isDesktop:A,hideHeader:E,selectionBar:rt,listBody:F.searchResults??(bn==="ready"?ef:void 0)}),r.jsx(Xa,{isOpen:Ae!==null,title:Ql(Ae?.length??0),description:"You can restore them from Trash later.",confirmLabel:"Move to Trash",destructive:!0,isBusy:d,onConfirm:nt,onCancel:Yt}),r.jsx(Ao,{verb:O,accountId:p,mailboxId:e,selection:Ve,crossAccount:ut!==void 0,escalated:kt,escalatedProgress:Y.progress,onFinished:ke})]})},jk=e=>is({path:{accountId:e}}),Nk=e=>{const t=Re(),s=ln(),n=Oe({...fm(),onSuccess:()=>{s.recordEvent("sync.triggered"),t.invalidateQueries({queryKey:jk(e)})}});return{trigger:()=>{n.mutate({path:{accountId:e}})},triggerAsync:()=>n.mutateAsync({path:{accountId:e}}),isPending:n.isPending,error:n.error,reset:n.reset}},Ek=({accountId:e,children:t})=>{const{triggerAsync:s,isPending:n}=Nk(e);return r.jsx(mg,{onRefresh:s,isRefreshing:n,children:t})};function Ik({accountId:e,currentMailboxId:t,candidates:s,onMove:n,children:a}){const[o,i]=c.useState(!1),l=ln(),{t:u}=Zn("mail",{useSuspense:!1}),m=c.useCallback((S,w)=>u(S,{defaultValue:w}),[u]),{inboxMailboxId:d}=vo(e),f=yo(e),{data:h}=ve({...it({path:{accountId:e}}),staleTime:1/0}),g=c.useMemo(()=>{const S=Ga(h?.items??[],f),w=on(f);return S.map(y=>({id:y.mailboxId,label:Es(y,w.get(y.mailboxId),m),searchValue:y.fullPath,isCurrent:y.mailboxId===t}))},[h?.items,f,t,m]),x=c.useMemo(()=>d||(g.find(w=>w.label.toLowerCase()==="inbox")?.id??g.find(w=>!w.isCurrent)?.id??""),[d,g]),p=c.useRef(!1);c.useEffect(()=>{p.current||(p.current=!0,iS(l,s.length))},[l,s.length]);const v=c.useCallback(()=>{lS(l,s.length),i(!0)},[l,s.length]),b=c.useCallback((S,w)=>{cS(l,{selected:S.length,total:s.length,toInbox:w===d}),n(S,w)},[l,s.length,d,n]);return r.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[r.jsx("div",{className:"shrink-0 px-row-inset pt-2",children:r.jsx(gg,{count:s.length,onReview:v})}),r.jsx("div",{className:"min-h-0 flex-1",children:a}),r.jsx(Ng,{open:o,candidates:s,defaultDestinationId:x,availableFolders:g,onConfirmMove:b,onCancel:()=>i(!1)})]})}const Tk="We can verify this sender";function Rk(e){const{data:t}=ve({...Ul({path:{mailboxId:e??""},query:{senderTrust:["vip","wellknown"],dkimMismatch:!1,results:!0,limit:500}}),enabled:!!e,staleTime:6e4});return{candidates:(t?.items??[]).map(n=>({id:n.messageId,senderName:n.fromName||n.fromEmail||"Unknown sender",senderAddress:n.fromEmail??"",subject:n.subject||"(no subject)",snippet:n.snippet??"",trustReason:Tk,trustSubReason:oS(n.senderTrust),senderTrust:n.senderTrust}))}}const Mk=e=>{const t=new Set,s=[];for(const n of e)t.has(n.threadMessageId)||(t.add(n.threadMessageId),s.push(n));return s},Ak={unread:"unread",flagged:"starred",attachment:"attachments"},Ok=new Set(Object.values(ot)),Kd=e=>Ok.has(e),Dk=e=>Kd(e.category)||e.attributes.size>0,Pk=e=>{const t={};Kd(e.category)&&(t.category=[e.category]);for(const s of e.attributes){const n=Ak[s];n&&(t[n]=!0)}return t},Lk=e=>(e.senderTrust?.length??0)>0||e.dkimMismatch!==void 0?"loaded-pages":"whole-folder",Fk=["category","unread","starred","attachments"],vl=e=>JSON.stringify(Fk.map(t=>e?.[t]??null)),$k=e=>{if(!Array.isArray(e))return;const[t]=e;if(typeof t!="object"||t===null)return;const s=t.query;if(!(typeof s!="object"||s===null))return s},_k=(e,t)=>{const s=$k(e);return s?vl(s)===vl(t):!1},Ud="remit:intelligence-open";function zk(){try{return localStorage.getItem(Ud)!=="closed"}catch{return!0}}function yl(e){try{localStorage.setItem(Ud,e?"open":"closed")}catch{}}const Bk=(e,t)=>e!==t,Kk=(e,t,s)=>{if(!(s||!t))return e.find(n=>n.messageId===t)},Uk=(e,t,s,n)=>{if(e)return e;if(!(n||!s))return t?.messageId===s?t:void 0},An=e=>e[0],qk=e=>{const t=An(e.filter(l=>l.type==="from").map(l=>l.value)),s=An(e.filter(l=>l.type==="subject").map(l=>l.value)),n=An(e.filter(l=>l.type==="category").map(l=>l.category)),a=An(e.filter(l=>l.type==="isUnread"||l.type==="isRead").map(l=>l.type==="isUnread")),o=e.some(l=>l.type==="isStarred")?!0:void 0,i=e.some(l=>l.type==="hasAttachment")?!0:void 0;return{...t!==void 0?{from:t}:{},...s!==void 0?{subject:s}:{},...n!==void 0?{category:[n]}:{},...a!==void 0?{unread:a}:{},...o!==void 0?{starred:o}:{},...i!==void 0?{attachments:i}:{}}},Hk=(e,t)=>{switch(t.type){case"from":return e.from?.toLowerCase()===t.value.toLowerCase();case"subject":return e.subject?.toLowerCase()===t.value.toLowerCase();case"category":return e.category?.length===1&&e.category[0]===t.category;case"isUnread":return e.unread===!0;case"isRead":return e.unread===!1;case"isStarred":return e.starred===!0;case"hasAttachment":return e.attachments===!0;case"before":case"after":case"in":case"account":return!1}};function Wk(e,t={}){const s=qk(e),n={...s,...t};return{params:s,residual:e.filter(a=>!Hk(n,a))}}function Vk(e,t,s){if(t.length===0)return e;const n=[...t];return e.filter(a=>{const o=Vn(a);return Io({...o,accountId:o.accountId??s},n)})}const Qk=50,Gk=new Map(Dc().categories.filter(e=>e.id!=="all").map(e=>[e.id,e.label])),qd=c.createContext(null);function Ir(){const e=c.useContext(qd);if(!e)throw new Error("MailboxPane.* must be used inside <MailboxPane>");return e}function Yk({mailboxId:e,selectedMessageId:t,children:s}){const n=He(),o=Cr()==="desktop",i=ln(),{accounts:l,searchQuery:u,searchInput:m,intelligenceOpen:d,onToggleIntelligence:f,onSetIntelligenceOpen:h}=Me(),g=us(),x=No(u),p=x.length>0,{freeText:v,tokens:b}=_s(x,g),[S,w]=c.useState("all"),[y,j]=c.useState(new Set),E=c.useMemo(()=>({category:S,attributes:y}),[S,y]),M=c.useMemo(()=>Pk(E),[E]),N=p||Dk(E),{params:A,residual:L}=Wk(b,M),O={order:"desc",limit:Qk,...v?{query:v}:{},...A,...M},D={category:O.category,unread:O.unread,starred:O.starred,attachments:O.attachments},R=N?Ka({path:{mailboxId:e},query:O}):nr({path:{mailboxId:e},query:{order:"desc"}}),{data:k,isLoading:P,isError:F,error:C,refetch:T,fetchNextPage:I,hasNextPage:q,isFetchingNextPage:se}=Yc({queryKey:R,queryFn:async({pageParam:X})=>{if(N){const{data:at}=await Kl({path:{mailboxId:e},query:{...O,continuationToken:X},throwOnError:!0});return at}const{data:rt}=await mm({path:{mailboxId:e},query:{order:"desc",continuationToken:X},throwOnError:!0});return rt},initialPageParam:void 0,getNextPageParam:X=>X.continuationToken,placeholderData:(X,rt)=>_k(rt?.queryKey,D)?X:void 0}),G=c.useCallback(X=>{t&&X.includes(t)&&n({to:"/mail/$mailboxId",params:{mailboxId:e},search:rt=>({...rt,selectedMessageId:void 0,selectedThreadId:void 0})})},[t,e,n]),{deleteMessages:oe,isPending:ne}=as({mailboxId:e,onAfterOptimisticRemove:G}),{accountId:Z}=go(e),pe=lu({accounts:l}),{moveMessages:me,isPending:Q}=rs({mailboxId:e,accountId:Z,onAfterOptimisticRemove:G}),H=Vk(Gv(Mk(k?.pages.flatMap(X=>X.items??[])??[])),L,Z),de=c.useCallback(X=>{w(X)},[]),ee=c.useCallback(X=>{j(rt=>{const at=new Set(rt);return at.has(X)?at.delete(X):at.add(X),at})},[]),fe=c.useCallback(()=>{w("all"),j(new Set)},[]),U=Gk.get(S),_=U?{label:U,reach:L.length>0?"loaded-pages":Lk(O),onClear:fe}:void 0,z=Bk(m,u),ce=Kk(H,t,z),[be,Ke]=c.useState(void 0);c.useEffect(()=>{ce&&Ke(ce)},[ce]);const ge=Uk(ce,be,t,z),{selectedThreadId:ie}=Is({strict:!1}),Ae=c.useMemo(()=>Ad(ge,{messageId:t,threadId:z?void 0:ie,mailboxId:e}),[ge,t,ie,z,e]),we=Do(),{listCommandsRef:Ne,onTriageContextChange:ft,focusedMessageId:Y,selectedIds:Ee}=we,ue=H.find(X=>X.messageId===Y)??ge,ke=c.useRef(null);c.useEffect(()=>{const X=ge?.messageId??null;X&&ke.current!==X&&ge?.authenticity?.dkimMismatch&&(ke.current=X,d||f())},[ge?.messageId,ge?.authenticity?.dkimMismatch,d,f]);const et=c.useRef(!1);c.useEffect(()=>{et.current||o&&ge?.messageId&&(et.current=!0,zk()&&!d&&h(!0))},[o,ge?.messageId,d,h]);const ct=Wb({accounts:l})??0,Ye=Re(),{pushError:Ie}=lt(),De=sn({thread:ge,mailboxId:e,accountId:Z,onAfterOptimisticRemove:G}),{draftsMailboxId:We}=Wv(Z),Xe=We!==void 0&&We===e,{archiveMailboxId:Ue}=Hv(Z),tt=Md(),{requestCompose:Se}=De,W=c.useCallback(()=>{Se("reply")},[Se]),re=c.useCallback(()=>{Se("reply_all")},[Se]),he=c.useCallback(()=>{Se("forward")},[Se]),{state:le,openCompose:ye,closeCompose:Ce}=Ht(),xe=c.useCallback(()=>{ye({mode:"new"})},[ye]),Ve=Oe({...sr(),onError:X=>{Ie(ts("Couldn't discard draft","The draft wasn't deleted.",X))}}),Pe=c.useCallback(()=>{const X=le.outboxMessageId;X&&(Ve.mutate({path:{outboxMessageId:X}}),Ye.invalidateQueries({queryKey:Wa()}),Ce())},[le.outboxMessageId,Ve,Ye,Ce]),Je=c.useCallback(()=>{n({to:"/mail/$mailboxId",params:{mailboxId:e},search:X=>({...X,selectedMessageId:void 0,selectedThreadId:void 0})})},[e,n]),_e=c.useCallback(X=>X?tt(X):[],[tt]),{toggleStar:Le}=xo({threadId:ue?.threadId??"",mailboxId:e}),{toggleReadFor:st}=yr({mailboxId:e,accountId:Z}),{junkMailboxId:Qe}=Fs(Z),Gt=Qe!=null&&Qe===e,{candidates:ds}=Rk(Gt?Qe:void 0),{moveMessages:fs}=rs({mailboxId:e,threadId:ue?.threadId,accountId:Z,onAfterOptimisticRemove:G}),{deleteMessages:kt}=as({mailboxId:e,threadId:ue?.threadId,onAfterOptimisticRemove:G}),{addressId:nt,address:Yt}=Ed(ue),{updateFlags:ut}=Id({addressId:nt,senderEmail:ue?.fromEmail??void 0}),$=c.useCallback(()=>t||!Y?!1:(n({to:"/mail/$mailboxId",params:{mailboxId:e},search:X=>({...X,selectedMessageId:Y})}),!0),[t,Y,e,n]),J=c.useCallback(()=>{$()||ge&&Se("reply")},[$,ge,Se]),qe=c.useCallback(()=>{$()||ge&&Se("reply_all")},[$,ge,Se]),mt=c.useCallback(()=>{$()||ge&&Se("forward")},[$,ge,Se]),Ze=c.useCallback(()=>_e(ue),[_e,ue]),bt=c.useCallback(()=>{if(Ne.current?.requestVerb("delete"))return;const X=Ze();X.length>0&&kt(X)},[Ne,Ze,kt]),gn=c.useCallback(()=>{if(Ne.current?.requestVerb("junk")||!Qe)return;const X=Ze();X.length!==0&&(Rd(i,{count:X.length,senderTrust:ue?.senderTrust??"unknown",wasRescuable:ue?Td(ue):!1}),fs(X,Qe))},[Ne,Qe,Ze,fs,i,ue]),xn=c.useCallback(()=>{if(Ee.length>0){const X=!(ue?.hasStars??!1),rt=new Set(Ee);for(const at of H)rt.has(at.messageId)&&at.hasStars!==X&&Le(at.messageId,at.hasStars);return}ue&&Le(ue.messageId,ue.hasStars)},[Ee,H,ue,Le]),bn=c.useCallback(()=>{if(Ne.current?.requestVerb("markRead"))return;const X=Ze();if(X.length===0)return;const rt=!(ue?.isRead??!1);st(X,rt)},[Ne,Ze,ue,st]),Tr=c.useCallback(()=>{if(!nt)return;const X=Yt?.flags?.muted?.value!==!0;ut({muted:{value:X}})},[nt,Yt,ut]),Rr=c.useCallback(()=>{if(!nt)return;const X=Yt?.flags?.vip?.value!==!0;ut({vip:{value:X}})},[nt,Yt,ut]),Mr=c.useCallback(()=>{d||f()},[d,f]),Ct=c.useCallback(X=>{n({to:X})},[n]),vn=Xe?"drafts":Ue===e?"archive":Qe===e?"junk":"inbox",yn=c.useRef("");c.useEffect(()=>{const X=yn.current;yn.current=x,x.length>0&&X.length===0&&i.recordEvent("search.submitted",{mailboxType:vn})},[x,vn,i]);const Ar=Xe&&le.isOpen&&!!le.outboxMessageId&&!ge,{goBack:Or,nextMessageId:Dr,previousMessageId:Pr}=Po({context:we,orderedIds:H.map(X=>X.messageId),selectedMessageId:t,enabled:!le.isOpen,onClose:Je,handlers:{reply:J,replyAll:qe,forward:mt,delete:bt,toggleStar:xn,toggleRead:bn,muteSender:Tr,blockSender:Mr,vipSender:Rr,markJunk:gn,toggleIntelligence:ge?f:void 0,compose:xe,goBrief:()=>Ct("/mail"),goInbox:()=>Ct("/mail"),goSent:()=>Ct("/mail"),goFlagged:()=>Ct("/mail/flagged"),goSettings:()=>Ct("/settings")}});po({enabled:le.isOpen,bindings:[{key:"Escape",handler:Ce,preventDefault:!0}]});const zo={mailboxId:e,selectedMessageId:t,selectedThread:ge,conversation:Ae,threads:H,isLoading:P,isError:F,error:C,mailboxAccountId:Z,mailboxName:pe,unreadCount:ct,isDraftsMailbox:Xe,isSpamFolder:Gt,rescueCandidates:ds,filterCategory:S,filterAttributes:y,onSelectFilterCategory:de,onToggleFilterAttribute:ee,onClearFilters:fe,listFilter:_,intelligenceOpen:d,onToggleIntelligence:f,searchPredicate:p&&L.length===0?O:void 0,onDeleteMessages:oe,onMoveMessages:me,isDeleting:ne,isMoving:Q,onLoadMore:I,hasMore:q,isLoadingMore:se,onTriageContextChange:ft,listCommandsRef:Ne,onRetry:()=>T(),toolbarComposeRequest:De.composeRequest,onToolbarReply:W,onToolbarReplyAll:re,onToolbarForward:he,onClearComposeRequest:De.clearComposeRequest,onToolbarDelete:De.deleteThread,onToolbarStar:De.toggleStar,onToolbarDiscardDraft:Pe,onToolbarMove:De.moveThread,composeState:le,closeCompose:Ce,hasRemitDraftOpen:Ar,onBack:Or,nextMessageId:Dr,previousMessageId:Pr};return r.jsx(qd.Provider,{value:zo,children:s})}function Hd(){const{mailboxId:e,selectedMessageId:t,threads:s,isLoading:n,isError:a,error:o,onDeleteMessages:i,onMoveMessages:l,isDeleting:u,isMoving:m,onLoadMore:d,hasMore:f,isLoadingMore:h,mailboxAccountId:g,mailboxName:x,unreadCount:p,isDraftsMailbox:v,isSpamFolder:b,rescueCandidates:S,onTriageContextChange:w,listCommandsRef:y,onRetry:j,filterCategory:E,filterAttributes:M,onSelectFilterCategory:N,onToggleFilterAttribute:A,onClearFilters:L,listFilter:O,searchPredicate:D}=Ir(),{searchQuery:R,searchInput:k,accounts:P,resultFolderIndex:F}=Me(),C=Cr(),T=He(),I=x??"Inbox",q=c.useMemo(()=>Dc(),[]),se=c.useMemo(()=>s.map(de=>k0(de,F)),[s,F]),{hits:G,isLoading:oe}=rd({mailboxId:e,filterCategory:E}),ne=c.useMemo(()=>id(G,s.map(de=>de.threadId),F),[G,s,F]),Z=c.useCallback(de=>T({to:"/mail/$mailboxId",params:{mailboxId:de.mailboxId??e},search:ee=>({...ee,q:k||void 0,selectedMessageId:de.id,selectedThreadId:de.threadId})}),[e,T,k]);if(v&&g)return r.jsx(QS,{mailboxId:e,accountId:g,selectedMessageId:t,imapThreads:s,title:x??"Drafts",unreadCount:p??void 0});const pe=r.jsx(Ck,{mailboxId:e,threads:s,selectedMessageId:t,isLoading:n,isError:a,error:o,onRetry:j,searchQuery:R,searchPredicate:D,onDeleteMessages:i,isDeleting:u,isMoving:m,onLoadMore:d,hasMore:f,isLoadingMore:h,accountId:g,listTitle:I,listFilter:O,listScopeLabel:I,hideHeader:!0,onTriageContextChange:w,commandsRef:y}),me=P[0]?.accountId,Q=C==="phone"&&me?r.jsx(Ek,{accountId:me,children:pe}):pe,H=b&&S.length>0&&g?r.jsx(Ik,{accountId:g,currentMailboxId:e,candidates:S,onMove:l,children:Q}):Q;return r.jsx(Ld,{title:I,unreadCount:p,preset:q,selectedCategory:E,activeFilters:M,onSelectCategory:N,onToggleFilter:A,onClearFilters:L,searchResults:se,searchLoading:n,relatedResults:ne,relatedLoading:oe,onSelectSearchResult:Z,searchResultsInBody:!0,children:H})}function Xk(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,conversation:n,hasRemitDraftOpen:a,intelligenceOpen:o,onToggleIntelligence:i,toolbarComposeRequest:l,onToolbarReply:u,onToolbarReplyAll:m,onToolbarForward:d,onClearComposeRequest:f,onToolbarDelete:h,onToolbarStar:g,onToolbarDiscardDraft:x,onToolbarMove:p,composeState:v}=Ir(),b=As()?.showIntelligencePane??!1,S=!!n,w=b&&S,y=v.isOpen&&!n?r.jsx(_d,{}):n?r.jsx($s,{threadId:n.threadId,mailboxId:n.mailboxId,subject:n.subject,selectedMessageId:n.messageId,authenticity:n.authenticity,onOpenIntelligence:n.authenticity?.dkimMismatch?i:void 0,composeRequest:l,onComposeClose:f}):r.jsx(Ls,{});return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx(Oo,{hasThread:S,intelligenceOpen:w&&o,canToggleIntelligence:w,onToggleIntelligence:i,onReply:S?u:void 0,onReplyAll:S?m:void 0,onForward:S?d:void 0,canDelete:S||a,onDelete:S?h:a?x:void 0,onToggleStar:S?g:void 0,isStarred:s?.hasStars,moveContext:S&&t?{accountId:t,currentMailboxId:e,onMove:p}:void 0}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:y})]})}function Jk(){const{mailboxId:e,mailboxAccountId:t,selectedThread:s,onToggleIntelligence:n}=Ir();return r.jsx(zs,{onClose:n,thread:s,mailboxId:e,accountId:t})}function Zk(){const{mailboxId:e,selectedThread:t,conversation:s,intelligenceOpen:n,onToggleIntelligence:a,onBack:o,nextMessageId:i,previousMessageId:l,composeState:u}=Ir(),m=He();if(s){const d=f=>m({to:"/mail/$mailboxId",params:{mailboxId:e},search:h=>({...h,selectedMessageId:f,selectedThreadId:void 0})});return r.jsxs(r.Fragment,{children:[r.jsx($s,{threadId:s.threadId,mailboxId:s.mailboxId,subject:s.subject,selectedMessageId:s.messageId,authenticity:s.authenticity,onBack:o,onOpenIntelligence:a,onSwipeNext:i?()=>d(i):void 0,onSwipePrevious:l?()=>d(l):void 0,mobileIntelligenceOpen:n}),r.jsx(mo,{isOpen:n,onClose:a,ariaLabel:"Message details",side:"right",children:r.jsx(zs,{onClose:a,thread:t,hideCloseButton:!0})})]})}return u.isOpen?r.jsx("div",{className:"h-full",children:r.jsx(_d,{})}):r.jsx(Hd,{})}const Gs=Object.assign(Yk,{List:Hd,Reading:Xk,Intelligence:Jk,Phone:Zk}),Wd=e=>e==="failed"||e==="blocked",Vd=e=>e!=="draft"&&e!=="sent",$o="remit.savedSearches",eC=25;function Yn(){try{const e=localStorage.getItem($o);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}}function tC(e){const t=e.trim();if(!t)return Yn();const s=[t,...Yn().filter(n=>n!==t)].slice(0,eC);try{localStorage.setItem($o,JSON.stringify(s))}catch{return s}return s}function sC(e){const t=Yn().filter(s=>s!==e);try{localStorage.setItem($o,JSON.stringify(t))}catch{return t}return t}const wl=e=>/^\d/.test(e),nC=(e,t)=>{const s=wl(e),n=wl(t);return s&&!n?-1:!s&&n?1:e.localeCompare(t,void 0,{sensitivity:"base",numeric:!0})};function rC(e,t,s){const n=[],a=[];for(const o of e)t.has(o.mailboxId)?n.push(o):a.push(o);return a.sort((o,i)=>nC(Es(o,void 0,s),Es(i,void 0,s))),{system:n,labels:a}}function aC(e,t,s){const n=hm(t)&&e.unseenCount>0;return{id:e.mailboxId,name:Es(e,t,s),unseen:n?e.unseenCount:void 0,role:t,fullPath:e.fullPath}}function oC(){const e=gr(),t=Ba({strict:!1});return e.pathname.startsWith("/settings")?"settings":e.pathname.startsWith("/mail/outbox")?"outbox":e.pathname.startsWith("/mail/flagged")?"flagged":t.mailboxId?t.mailboxId:e.pathname==="/mail"||e.pathname==="/mail/"?"brief":""}function Sl({accounts:e,onMailboxSelect:t,variant:s="desktop"}){const n=Re(),a=He(),o=oC(),{searchInput:i,onSearchChange:l}=Me(),[u,m]=c.useState(Yn),{t:d}=Zn("mail",{useSuspense:!1}),f=c.useCallback((N,A)=>d(N,{defaultValue:A}),[d]),h=gt({queries:e.map(N=>({...it({path:{accountId:N.accountId}}),staleTime:1/0}))}),{data:g}=ve(er()),x=c.useMemo(()=>(g?.items??[]).filter(N=>Vd(N.status)).length,[g?.items]),p=c.useMemo(()=>e.map((N,A)=>{const L=h[A],O=L?.data?.items??[],D=on(N.folderAppointments),{system:R,labels:k}=rC(O,D,f),P=L?.isError?"error":L?.isLoading?"loading":"ready";return{id:N.accountId,label:N.email,email:N.email,muted:!!N.muted,outboxPending:x,status:P,onRetry:()=>L?.refetch(),mailboxes:[...R,...k].map(F=>aC(F,D.get(F.mailboxId),f))}}),[e,h,x,f]),v=N=>{n.invalidateQueries({queryKey:nr({path:{mailboxId:N},query:{order:"desc"}})})},b=({navId:N,className:A,ariaLabel:L,title:O,children:D,onClick:R})=>N==="brief"?r.jsx(Et,{to:"/mail",search:{q:void 0,selectedMessageId:void 0},onClick:()=>R?.(),className:A,"aria-label":L,title:O,children:D}):N==="outbox"?r.jsx(Et,{to:"/mail/outbox",search:{q:void 0,selectedOutboxMessageId:void 0},onClick:()=>R?.(),className:A,"aria-label":L,title:O,children:D}):N==="flagged"?r.jsx(Et,{to:"/mail/flagged",search:{q:void 0,selectedMessageId:void 0},onClick:()=>R?.(),className:A,"aria-label":L,title:O,children:D}):N==="settings"?r.jsx(Et,{to:"/settings/accounts",onClick:()=>R?.(),className:A,"aria-label":L,title:O,children:D}):r.jsx(Et,{to:"/mail/$mailboxId",params:{mailboxId:N},search:{q:void 0,selectedMessageId:void 0},onClick:()=>{v(N),R?.()},className:A,"aria-label":L,title:O,children:D}),S=()=>{l(""),t?.()},w=i.trim(),y=w.length>0&&!u.includes(w)?w:void 0,j=c.useCallback(()=>{y&&m(tC(y))},[y]),E=c.useCallback(N=>{m(sC(N))},[]),M=c.useCallback(N=>{l(N),a({to:"/mail",search:{q:N,selectedMessageId:void 0}}),t?.()},[l,a,t]);return r.jsx(zp,{accounts:p,selectedNavId:o,onSelectNav:S,linkComponent:b,variant:s,savedSearches:u,saveableQuery:y,onSaveCurrentSearch:j,onSelectSavedSearch:M,onRemoveSavedSearch:E})}function iC({accounts:e,onMailboxSelect:t}){return As()?.showNavPane??!0?r.jsx(Sl,{accounts:e}):r.jsxs("div",{className:"flex h-full flex-col",children:[r.jsx("div",{className:"flex-1 overflow-y-auto",children:r.jsx(Sl,{accounts:e,onMailboxSelect:t,variant:"drawer"})}),r.jsxs("div",{className:"border-t border-line px-2 py-2",children:[r.jsxs(Et,{to:"/settings/accounts",onClick:t,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg",children:[r.jsx(to,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Settings"})]}),r.jsx(tu,{variant:"drawer"}),r.jsx(eu,{children:({signOut:a})=>r.jsxs("button",{type:"button",onClick:()=>{t?.(),a()},className:"flex min-h-11 w-full items-center gap-2 rounded-md px-2 py-1 text-sm text-fg-muted transition-colors hover:bg-surface hover:text-fg","data-testid":"sign-out-button",children:[r.jsx(dc,{className:"size-4 shrink-0"}),r.jsx("span",{className:"flex-1 truncate text-left",children:"Sign out"})]})})]})]})}function lC(e,t){const s=t.trim().toLowerCase();if(s.length===0)return!0;const n=[e.subject,e.fromAddress,e.fromName,...e.toAddresses??[],...e.ccAddresses??[]].filter(a=>typeof a=="string").join(" ").toLowerCase();return s.split(/\s+/).every(a=>a.length===0||n.includes(a))}function cC(e){return e.tokens.length>0&&e.freeText.trim().length===0}const Qd={queued:{icon:Qa,label:"Queued",className:"text-warning"},sending:{icon:Ms,label:"Sending…",className:"text-accent-2"},sent:{icon:ic,label:"Sent",className:"text-positive"},failed:{icon:os,label:"Failed",className:"text-danger"},blocked:{icon:Oa,label:"Blocked",className:"text-warning"}},uC=e=>Lm(e).toDateString()===new Date().toDateString()?Bn(e,{hour:"numeric",minute:"2-digit"}):Bn(e,{month:"short",day:"numeric"}),kl=e=>Bn(e,{dateStyle:"medium",timeStyle:"short"}),dC=e=>{const t=e.toAddresses??[];return t.length===0?"No recipients":t.length===1?t[0]:`${t[0]} +${t.length-1}`},Gd=(e,t)=>t?"The outbox cannot filter on those terms":e?"No matching outbox messages":"No outbox messages",Yd=c.createContext(null);function _o(){const e=c.useContext(Yd);if(!e)throw new Error("OutboxPane.* must be used inside <OutboxPane>");return e}function fC({children:e}){const t=He(),{selectedOutboxMessageId:s}=Is({strict:!1}),{data:n,isLoading:a}=ve(er()),{searchQuery:o}=Me(),i=us(),l=No(o),u=_s(l,i),m=l.length>0,d=cC(u),f=c.useMemo(()=>d?[]:(n?.items??[]).filter(p=>Vd(p.status)).filter(p=>lC(p,u.freeText)),[n,u.freeText,d]),h=c.useMemo(()=>f.find(p=>p.outboxMessageId===s),[f,s]),g=c.useCallback(p=>{t({to:"/mail/outbox",search:v=>({...v,selectedOutboxMessageId:p})})},[t]),x={messages:f,hasQuery:m,unsupportedQuery:d,isLoading:a,selectedMessageId:s,selectedMessage:h,onSelectMessage:g};return r.jsx(Yd.Provider,{value:x,children:e})}function Xd({message:e,isSelected:t,onSelect:s}){const n=Re(),{openCompose:a}=Ht(),{pushError:o}=lt(),i=c.useCallback(()=>{n.invalidateQueries({queryKey:Wa()})},[n]),l=Oe({..._l(),onSuccess:i,onError:f=>{o(ts("Couldn't resend message","The message wasn't sent.",f))}}),u=Oe({...sr(),onSuccess:i,onError:f=>{o(ts("Couldn't delete message","The message wasn't deleted.",f))}}),m=e.status;if(!Qd[m])return null;const d=Wd(e.status);return r.jsx(dg,{recipients:dC(e),subject:e.subject||"",time:uC(e.sentAt??e.updatedAt),status:m,error:d?e.lastError??void 0:void 0,selected:t,onSelect:s,onRetry:m==="failed"?()=>l.mutate({path:{outboxMessageId:e.outboxMessageId}}):void 0,retrying:l.isPending,onEdit:()=>a({mode:"new",outboxMessageId:e.outboxMessageId}),onDelete:()=>u.mutate({path:{outboxMessageId:e.outboxMessageId}}),deleting:u.isPending})}function Jd({message:e,onBack:t}){const s=e.status,n=Qd[s],a=n?.icon??an,o=e.sentAt?kl(e.sentAt):kl(e.updatedAt);return r.jsxs("div",{className:"h-full overflow-y-auto bg-canvas",children:[r.jsxs("div",{className:"border-b border-line p-4",children:[t&&r.jsxs("button",{type:"button",onClick:t,className:"mb-3 inline-flex items-center gap-1 text-sm text-fg-muted hover:text-fg",children:[r.jsx(Ta,{className:"size-4"}),r.jsx("span",{children:"Back"})]}),r.jsx("h1",{className:"text-xl font-semibold mb-3",children:e.subject||"(No subject)"}),r.jsxs("div",{className:"space-y-1 text-sm",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"From:"}),r.jsx("span",{className:"text-fg",children:e.fromName?`${e.fromName} <${e.fromAddress}>`:e.fromAddress})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"To:"}),r.jsx("span",{className:"text-fg",children:(e.toAddresses??[]).join(", ")})]}),e.ccAddresses&&e.ccAddresses.length>0&&r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Cc:"}),r.jsx("span",{className:"text-fg",children:e.ccAddresses.join(", ")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("span",{className:"text-fg-muted shrink-0 w-12",children:"Date:"}),r.jsx("span",{className:"text-fg",children:o})]}),n&&r.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[r.jsx(a,{className:$e("size-4",n.className,s==="sending"&&"animate-spin")}),r.jsx("span",{className:$e("text-xs font-medium",n.className),children:n.label}),Wd(e.status)&&e.lastError&&r.jsxs("span",{className:"text-xs text-fg-muted",children:["— ",e.lastError]})]})]})]}),r.jsx("div",{className:"p-4",children:r.jsx(Qu,{html:e.htmlBody,text:e.textBody})})]})}function mC(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,onSelectMessage:o}=_o(),i=c.useRef(null);return Xn({containerRef:i,itemSelector:Ma}),n?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:r.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx(Ls,{message:Gd(t,s),showHints:!1})}):r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx(Lo,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),r.jsx("div",{ref:i,className:"flex-1 overflow-y-auto",children:e.map(l=>r.jsx(Xd,{message:l,isSelected:a===l.outboxMessageId,onSelect:()=>o(l.outboxMessageId)},l.outboxMessageId))})]})}function hC(){const{selectedMessage:e}=_o();return r.jsxs("section",{className:"flex h-full w-full min-w-0 flex-col bg-canvas",children:[r.jsx("header",{className:"flex h-pane-header shrink-0 items-center border-b border-line px-3"}),r.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e?r.jsx(Jd,{message:e}):r.jsx(Ls,{message:"Select a message to read",showHints:!1})})]})}function pC(){const{messages:e,hasQuery:t,unsupportedQuery:s,isLoading:n,selectedMessageId:a,selectedMessage:o,onSelectMessage:i}=_o(),l=c.useRef(null);return Xn({containerRef:l,itemSelector:Ma}),n?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas",children:r.jsx("span",{className:"text-fg-muted",children:"Loading..."})}):o?r.jsx(Jd,{message:o,onBack:()=>i(void 0)}):e.length===0?r.jsx("div",{className:"flex h-full bg-surface",children:r.jsx(Ls,{message:Gd(t,s),showHints:!1})}):r.jsxs("div",{className:"h-full flex flex-col bg-canvas",children:[r.jsxs("header",{className:"flex h-pane-header shrink-0 items-center gap-2 border-b border-line px-row-inset",children:[r.jsx(Lo,{}),r.jsx("h1",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-fg",children:"Outbox"}),r.jsxs("span",{className:"shrink-0 text-2xs text-fg-subtle",children:[e.length," ",e.length===1?"message":"messages"]})]}),r.jsx("div",{ref:l,className:"flex-1 overflow-y-auto",children:e.map(u=>r.jsx(Xd,{message:u,isSelected:a===u.outboxMessageId,onSelect:()=>i(u.outboxMessageId)},u.outboxMessageId))})]})}const On=Object.assign(fC,{List:mC,Reading:hC,Phone:pC}),gC=({isOpen:e,onClose:t})=>{const s=c.useCallback(n=>{n.key==="Escape"&&(n.preventDefault(),t())},[t]);return c.useEffect(()=>{if(e)return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,s]),e?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",onClick:t,onKeyDown:n=>n.key==="Escape"&&t(),children:[r.jsx("div",{className:"absolute inset-0 bg-canvas/80 backdrop-blur-sm"}),r.jsxs("div",{className:$e("relative z-10 max-h-[85vh] w-full max-w-2xl overflow-y-auto","rounded-lg border border-line bg-surface shadow-lg","p-6"),onClick:n=>n.stopPropagation(),onKeyDown:n=>{n.key!=="Escape"&&n.stopPropagation()},children:[r.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold",children:"Keyboard shortcuts"}),r.jsx("button",{type:"button",onClick:t,className:"p-1 text-fg-muted transition-colors hover:text-fg","aria-label":"Close",children:r.jsx(St,{className:"size-5"})})]}),r.jsx("div",{className:"grid gap-x-8 gap-y-6 sm:grid-cols-2",children:uu.map(n=>r.jsxs("div",{children:[r.jsx("h3",{className:"mb-3 text-sm font-medium text-fg-muted",children:n.title}),r.jsx("div",{className:"space-y-2",children:n.hints.map(a=>r.jsxs("div",{className:"flex items-center justify-between gap-4",children:[r.jsx("span",{className:"text-sm",children:a.description}),r.jsx("span",{className:"flex shrink-0 items-center gap-1",children:a.keys.map((o,i)=>r.jsxs(c.Fragment,{children:[i>0&&a.keys[0]==="g"&&r.jsx("span",{className:"text-2xs text-fg-subtle",children:"then"}),r.jsx(ks,{children:o})]},o))})]},`${a.action}-${a.keys.join("+")}`))})]},n.title))}),r.jsx("div",{className:"mt-6 border-t border-line pt-4",children:r.jsxs("p",{className:"text-center text-xs text-fg-muted",children:["Press ",r.jsx(ks,{children:"Esc"})," to close"]})})]})]}):null};function xC(e){const t=gt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0}))});return c.useMemo(()=>$0(t.map(s=>s.data?.items??[])),[t])}const bC=e=>e.map(t=>t.data?.items??[]);function vC(e){const t=gt({queries:e.map(s=>({...it({path:{accountId:s.accountId}}),staleTime:1/0})),combine:bC});return c.useMemo(()=>pm(e.map((s,n)=>({folderAppointments:s.folderAppointments,mailboxes:t[n]??[]}))),[e,t])}var Dn={exports:{}},Cl;function yC(){if(Cl)return Dn.exports;Cl=1;const e=(t,s,n)=>new Promise((a,o)=>{if(n=Object.assign({concurrency:1/0},n),typeof s!="function")throw new TypeError("Mapper function is required");const{concurrency:i}=n;if(!(typeof i=="number"&&i>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${i}\` (${typeof i})`);const l=[],u=t[Symbol.iterator]();let m=!1,d=!1,f=0,h=0;const g=()=>{if(m)return;const x=u.next(),p=h;if(h++,x.done){d=!0,f===0&&a(l);return}f++,Promise.resolve(x.value).then(v=>s(v,p)).then(v=>{l[p]=v,f--,g()},v=>{m=!0,o(v)})};for(let x=0;x<i&&(g(),!d);x++);});return Dn.exports=e,Dn.exports.default=e,Dn.exports}var wC=yC();const SC=gm(wC),kC=900*1e3,CC=300,jC=(e,t)=>{if(!e)return t;const s=Number.parseInt(e,10);return Number.isFinite(s)&&s>0?s:t},NC=60*1e3,EC=e=>Math.max(jC(e,CC)*1e3,NC),_n=EC(vm().mailboxPollIntervalSeconds),IC=5,Ea=new Set,TC=(e,t,s=kC)=>e.filter(n=>{const a=n.lastSyncAt;return a==null?!0:t-a>s}).map(n=>n.accountId),RC=(e,t,s=_n)=>e-t>=s,MC=(e,t)=>e.filter(s=>!t.has(s)),jl=(e,t)=>{if(Ea.delete(e),bm(t,{softError:!0})){ql(t);return}console.warn("[remit] background mailbox sync failed",{accountId:e,error:t})},Nl=(e,t)=>xm({path:{accountId:e},throwOnError:!0}).then(()=>{t.invalidateQueries({queryKey:is({path:{accountId:e}})})}),AC=e=>{const t=Re(),s=c.useRef(e);s.current=e;const n=e.map(a=>a.accountId).join(",");c.useEffect(()=>{const a=Date.now(),i=TC(s.current,a).filter(l=>!Ea.has(l));if(i.length!==0)for(const l of i)Ea.add(l),Nl(l,t).catch(u=>{jl(l,u)})},[n,t]),c.useEffect(()=>{let a=Date.now(),o;const i=new Set,l=()=>{a=Date.now();const d=MC(s.current.map(f=>f.accountId),i);for(const f of d)i.add(f);SC(d,f=>Nl(f,t).catch(h=>{jl(f,h)}).finally(()=>{i.delete(f)}),{concurrency:IC})},u=()=>{if(document.visibilityState==="visible"){l(),o=setTimeout(u,_n);return}},m=()=>{document.visibilityState==="visible"&&RC(Date.now(),a)&&(o!==void 0&&clearTimeout(o),l(),o=setTimeout(u,_n))};return o=setTimeout(u,_n),document.addEventListener("visibilitychange",m),()=>{o!==void 0&&clearTimeout(o),document.removeEventListener("visibilitychange",m)}},[n,t])};function OC(e,t,s){if(e!==t)return s}function DC(e,t){return e===""?"":t}function PC(e,t,s){return t!==e?!1:t!==s}function LC(){const{q:e=""}=Is({from:"/mail"}),t=He(),s=Cr(),n=cd(s),[a,o]=c.useState(!1),[i,l]=c.useState(!1),[u,m]=c.useState(!1),d=c.useCallback(Q=>{m(Q),yl(Q)},[]),[f,h]=c.useState(e),g=or(f,200),x=DC(f,g),p=c.useRef(e);p.current=e;const v=It({select:Q=>Bb(Q.matches)}),[b,S]=c.useState(v);if(b!==v){const Q=OC(b,v,e);S(v),Q!==void 0&&h(Q)}c.useEffect(()=>{PC(f,x,p.current)&&t({to:".",search:Q=>{const H=Q.q===x;return{...Q,q:x||void 0,...x&&!H?{selectedMessageId:void 0,selectedThreadId:void 0,selectedMailboxId:void 0}:{}}},replace:!0})},[f,x,t]);const{data:w,isLoading:y,isError:j,error:E,refetch:M}=ve({...Mt(),staleTime:1/0}),N=!!(w&&(w.accounts?.length??0)===0);c.useEffect(()=>{N&&t({to:"/onboarding",replace:!0})},[N,t]),po({enabled:!a,bindings:[{key:"?",handler:()=>o(!0),noModifiers:!1,preventDefault:!0}]});const A=c.useCallback(Q=>{h(Q)},[]),L=c.useCallback(()=>{h("")},[]),O=c.useCallback(()=>{h("")},[]),D=c.useCallback(()=>{m(Q=>{const H=!Q;return yl(H),H})},[]),R=w?.accounts??[],k=xC(R),P=vC(R),F=c.useMemo(()=>F0(R),[R]),C=It({select:Q=>Q.matches.find(de=>"mailboxId"in de.params)?.params.mailboxId}),{selectedMessageId:T}=Is({strict:!1}),I=It({select:Q=>fo(Q.matches)}),q=It({select:Q=>un(Q.matches)}),se=It({select:Q=>xr(Q.matches)});AC(R);const G=c.useCallback(()=>{l(!1)},[]),oe={accounts:R,mailboxNameIndex:k,accountNameIndex:F,resultFolderIndex:P,searchQuery:x,searchInput:f,searchViewKey:v,onSearchChange:A,onSearchClear:L,onSearchClearQuery:O,intelligenceOpen:u,onToggleIntelligence:D,onSetIntelligenceOpen:d},ne=r.jsx(iC,{accounts:R,onMailboxSelect:G}),Z=n?r.jsx($b,{accounts:R}):void 0,pe=n?void 0:r.jsx(Gb,{accounts:R}),me={navOpen:i,onOpenNav:()=>l(!0),onCloseNav:()=>l(!1)};return r.jsxs(ym.Provider,{value:oe,children:[j?r.jsx("div",{className:"flex h-full items-center justify-center bg-canvas p-4",children:r.jsx(Vt,{title:"Couldn't load your account",error:E,onRetry:()=>{M()}})}):I?r.jsx(Ws,{selectedMessageId:T,children:n?r.jsx(Pt,{nav:ne,list:r.jsx(Ws.Phone,{}),intelligenceOpen:u,overlay:Z,skeleton:r.jsx(Nt,{}),isLoading:y||N,...me}):r.jsx(Pt,{nav:ne,topBar:pe,list:r.jsx(Ws.List,{}),reading:r.jsx(Ws.Reading,{}),intelligence:r.jsx(Ws.Intelligence,{}),intelligenceOpen:u,hasThread:!!T,overlay:Z,skeleton:r.jsx(Nt,{}),isLoading:y||N,...me})}):q?r.jsx(Vs,{selectedMessageId:T,children:n?r.jsx(Pt,{nav:ne,list:r.jsx(Vs.Phone,{}),intelligenceOpen:u,overlay:Z,skeleton:r.jsx(Nt,{}),isLoading:y||N,...me}):r.jsx(Pt,{nav:ne,topBar:pe,list:r.jsx(Vs.List,{}),reading:r.jsx(Vs.Reading,{}),intelligence:r.jsx(Vs.Intelligence,{}),intelligenceOpen:u,hasThread:!!T,overlay:Z,skeleton:r.jsx(Nt,{}),isLoading:y||N,...me})}):C?r.jsx(Gs,{mailboxId:C,selectedMessageId:T,children:n?r.jsx(Pt,{nav:ne,list:r.jsx(Gs.Phone,{}),intelligenceOpen:u,overlay:Z,skeleton:r.jsx(Nt,{}),isLoading:y||N,...me}):r.jsx(Pt,{nav:ne,topBar:pe,list:r.jsx(Gs.List,{}),reading:r.jsx(Gs.Reading,{}),intelligence:r.jsx(Gs.Intelligence,{}),intelligenceOpen:u,hasThread:!!T,overlay:Z,skeleton:r.jsx(Nt,{}),isLoading:y||N,...me})}):se?r.jsx(On,{children:n?r.jsx(Pt,{nav:ne,list:r.jsx(On.Phone,{}),intelligenceOpen:!1,overlay:Z,skeleton:r.jsx(Nt,{}),isLoading:y||N,...me}):r.jsx(Pt,{nav:ne,topBar:pe,list:r.jsx(On.List,{}),reading:r.jsx(On.Reading,{}),intelligenceOpen:!1,overlay:Z,skeleton:r.jsx(Nt,{}),isLoading:y||N,...me})}):r.jsx(Nt,{}),r.jsx(gC,{isOpen:a,onClose:()=>o(!1)}),r.jsx(wm,{})]})}const ej=Object.freeze(Object.defineProperty({__proto__:null,component:LC,useMailContext:Me},Symbol.toStringTag,{value:"Module"}));export{ZC as S,Mh as U,ej as m};
|